Merge branch 'master' into es-cqrs

This commit is contained in:
CHANDRAKANT Kumar 2020-05-16 23:59:35 +05:30
commit b8e4c8a249
354 changed files with 5571 additions and 1318 deletions

View File

@ -3,7 +3,7 @@
This module contains articles about Apache CXF
## Relevant Articles:
- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf)
- [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api)
- [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring)
- [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf)

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)

56
aws-app-sync/pom.xml Normal file
View File

@ -0,0 +1,56 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.baeldung</groupId>
<artifactId>aws-app-sync</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>aws-app-sync</name>
<description>Spring Boot using AWS App Sync</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,32 @@
package com.baeldung.awsappsync;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class AppSyncClientHelper {
static String apiUrl = "https://m4i3b6icrrb7livfbypfspiifi.appsync-api.us-east-2.amazonaws.com";
static String apiKey = "da2-bm4rpatkkrc5jfyhvvq7itjeke";
static String API_KEY_HEADER = "x-api-key";
public static WebClient.ResponseSpec getResponseBodySpec(Map<String, Object> requestBody) {
return WebClient
.builder()
.baseUrl(apiUrl)
.defaultHeader(API_KEY_HEADER, apiKey)
.defaultHeader("Content-Type", "application/json")
.build()
.method(HttpMethod.POST)
.uri("/graphql")
.body(BodyInserters.fromValue(requestBody))
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
.acceptCharset(StandardCharsets.UTF_8)
.retrieve();
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.awsappsync;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AwsAppSyncApplication {
public static void main(String[] args) {
SpringApplication.run(AwsAppSyncApplication.class, args);
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.awsappsync;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.reactive.function.client.WebClient;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class AwsAppSyncApplicationTests {
@Test
void givenGraphQuery_whenListEvents_thenReturnAllEvents() {
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("query", "query ListEvents {"
+ " listEvents {"
+ " items {"
+ " id"
+ " name"
+ " where"
+ " when"
+ " description"
+ " }"
+ " }"
+ "}");
requestBody.put("variables", "");
requestBody.put("operationName", "ListEvents");
String bodyString = AppSyncClientHelper.getResponseBodySpec(requestBody)
.bodyToMono(String.class).block();
assertNotNull(bodyString);
assertTrue(bodyString.contains("My First Event"));
assertTrue(bodyString.contains("where"));
assertTrue(bodyString.contains("when"));
}
@Test
void givenGraphAdd_whenMutation_thenReturnIdNameDesc() {
String queryString = "mutation add {"
+ " createEvent("
+ " name:\"My added GraphQL event\""
+ " where:\"Day 2\""
+ " when:\"Saturday night\""
+ " description:\"Studying GraphQL\""
+ " ){"
+ " id"
+ " name"
+ " description"
+ " }"
+ "}";
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("query", queryString);
requestBody.put("variables", "");
requestBody.put("operationName", "add");
WebClient.ResponseSpec response = AppSyncClientHelper.getResponseBodySpec(requestBody);
String bodyString = response.bodyToMono(String.class).block();
assertNotNull(bodyString);
assertTrue(bodyString.contains("My added GraphQL event"));
assertFalse(bodyString.contains("where"));
assertFalse(bodyString.contains("when"));
}
}

View File

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

View File

@ -13,4 +13,5 @@ This module contains articles about core Groovy concepts
- [Metaprogramming in Groovy](https://www.baeldung.com/groovy-metaprogramming)
- [A Quick Guide to Working with Web Services in Groovy](https://www.baeldung.com/groovy-web-services)
- [Categories in Groovy](https://www.baeldung.com/groovy-categories)
- [How to Determine the Data Type in Groovy](https://www.baeldung.com/groovy-determine-data-type)
- [[<-- Prev]](/core-groovy)

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

@ -8,3 +8,4 @@ This module contains articles about Java 14.
- [Java Text Blocks](https://www.baeldung.com/java-text-blocks)
- [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof)
- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception)
- [Foreign Memory Access API in Java 14](https://www.baeldung.com/java-foreign-memory-access)

View File

@ -0,0 +1,22 @@
package com.baeldung.java14.record;
import java.util.Objects;
public record Person (String name, String address) {
public static String UNKWOWN_ADDRESS = "Unknown";
public static String UNNAMED = "Unnamed";
public Person {
Objects.requireNonNull(name);
Objects.requireNonNull(address);
}
public Person(String name) {
this(name, UNKWOWN_ADDRESS);
}
public static Person unnamed(String address) {
return new Person(UNNAMED, address);
}
}

View File

@ -0,0 +1,84 @@
package com.baeldung.java14.foreign.api;
import jdk.incubator.foreign.*;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
public class ForeignMemoryUnitTest {
@Test
public void whenAValueIsSet_thenAccessTheValue() {
long value = 10;
MemoryAddress memoryAddress =
MemorySegment.allocateNative(8).baseAddress();
VarHandle varHandle = MemoryHandles.varHandle(long.class,
ByteOrder.nativeOrder());
varHandle.set(memoryAddress, value);
assertThat(varHandle.get(memoryAddress), is(value));
}
@Test
public void whenMultipleValuesAreSet_thenAccessAll() {
VarHandle varHandle = MemoryHandles.varHandle(int.class,
ByteOrder.nativeOrder());
try(MemorySegment memorySegment =
MemorySegment.allocateNative(100)) {
MemoryAddress base = memorySegment.baseAddress();
for(int i=0; i<25; i++) {
varHandle.set(base.addOffset((i*4)), i);
}
for(int i=0; i<25; i++) {
assertThat(varHandle.get(base.addOffset((i*4))), is(i));
}
}
}
@Test
public void whenSetValuesWithMemoryLayout_thenTheyCanBeRetrieved() {
SequenceLayout sequenceLayout =
MemoryLayout.ofSequence(25,
MemoryLayout.ofValueBits(64, ByteOrder.nativeOrder()));
VarHandle varHandle =
sequenceLayout.varHandle(long.class,
MemoryLayout.PathElement.sequenceElement());
try(MemorySegment memorySegment =
MemorySegment.allocateNative(sequenceLayout)) {
MemoryAddress base = memorySegment.baseAddress();
for(long i=0; i<sequenceLayout.elementCount().getAsLong(); i++) {
varHandle.set(base, i, i);
}
for(long i=0; i<sequenceLayout.elementCount().getAsLong(); i++) {
assertThat(varHandle.get(base, i), is(i));
}
}
}
@Test
public void whenSlicingMemorySegment_thenTheyCanBeAccessedIndividually() {
MemoryAddress memoryAddress =
MemorySegment.allocateNative(12).baseAddress();
MemoryAddress memoryAddress1 =
memoryAddress.segment().asSlice(0,4).baseAddress();
MemoryAddress memoryAddress2 =
memoryAddress.segment().asSlice(4,4).baseAddress();
MemoryAddress memoryAddress3 =
memoryAddress.segment().asSlice(8,4).baseAddress();
VarHandle intHandle =
MemoryHandles.varHandle(int.class, ByteOrder.nativeOrder());
intHandle.set(memoryAddress1, Integer.MIN_VALUE);
intHandle.set(memoryAddress2, 0);
intHandle.set(memoryAddress3, Integer.MAX_VALUE);
assertThat(intHandle.get(memoryAddress1), is(Integer.MIN_VALUE));
assertThat(intHandle.get(memoryAddress2), is(0));
assertThat(intHandle.get(memoryAddress3), is(Integer.MAX_VALUE));
}
}

View File

@ -0,0 +1,150 @@
package com.baeldung.java14.record;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class PersonTest {
@Test
public void givenSameNameAndAddress_whenEquals_thenPersonsEqual() {
String name = "John Doe";
String address = "100 Linda Ln.";
Person person1 = new Person(name, address);
Person person2 = new Person(name, address);
assertTrue(person1.equals(person2));
}
@Test
public void givenDifferentObject_whenEquals_thenNotEqual() {
Person person = new Person("John Doe", "100 Linda Ln.");
assertFalse(person.equals(new Object()));
}
@Test
public void givenDifferentName_whenEquals_thenPersonsNotEqual() {
String address = "100 Linda Ln.";
Person person1 = new Person("Jane Doe", address);
Person person2 = new Person("John Doe", address);
assertFalse(person1.equals(person2));
}
@Test
public void givenDifferentAddress_whenEquals_thenPersonsNotEqual() {
String name = "John Doe";
Person person1 = new Person(name, "100 Linda Ln.");
Person person2 = new Person(name, "200 London Ave.");
assertFalse(person1.equals(person2));
}
@Test
public void givenSameNameAndAddress_whenHashCode_thenPersonsEqual() {
String name = "John Doe";
String address = "100 Linda Ln.";
Person person1 = new Person(name, address);
Person person2 = new Person(name, address);
assertEquals(person1.hashCode(), person2.hashCode());
}
@Test
public void givenDifferentObject_whenHashCode_thenNotEqual() {
Person person = new Person("John Doe", "100 Linda Ln.");
assertNotEquals(person.hashCode(), new Object().hashCode());
}
@Test
public void givenDifferentName_whenHashCode_thenPersonsNotEqual() {
String address = "100 Linda Ln.";
Person person1 = new Person("Jane Doe", address);
Person person2 = new Person("John Doe", address);
assertNotEquals(person1.hashCode(), person2.hashCode());
}
@Test
public void givenDifferentAddress_whenHashCode_thenPersonsNotEqual() {
String name = "John Doe";
Person person1 = new Person(name, "100 Linda Ln.");
Person person2 = new Person(name, "200 London Ave.");
assertNotEquals(person1.hashCode(), person2.hashCode());
}
@Test
public void givenValidNameAndAddress_whenGetNameAndAddress_thenExpectedValuesReturned() {
String name = "John Doe";
String address = "100 Linda Ln.";
Person person = new Person(name, address);
assertEquals(name, person.name());
assertEquals(address, person.address());
}
@Test
public void givenValidNameAndAddress_whenToString_thenCorrectStringReturned() {
String name = "John Doe";
String address = "100 Linda Ln.";
Person person = new Person(name, address);
assertEquals("Person[name=" + name + ", address=" + address + "]", person.toString());
}
@Test(expected = NullPointerException.class)
public void givenNullName_whenConstruct_thenErrorThrown() {
new Person(null, "100 Linda Ln.");
}
@Test(expected = NullPointerException.class)
public void givenNullAddress_whenConstruct_thenErrorThrown() {
new Person("John Doe", null);
}
@Test
public void givenUnknownAddress_whenConstructing_thenAddressPopulated() {
String name = "John Doe";
Person person = new Person(name);
assertEquals(name, person.name());
assertEquals(Person.UNKWOWN_ADDRESS, person.address());
}
@Test
public void givenUnnamed_whenConstructingThroughFactory_thenNamePopulated() {
String address = "100 Linda Ln.";
Person person = Person.unnamed(address);
assertEquals(Person.UNNAMED, person.name());
assertEquals(address, person.address());
}
}

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

@ -11,4 +11,5 @@ This module contains articles about advanced topics about multithreading with co
- [Guide to Work Stealing in Java](https://www.baeldung.com/java-work-stealing)
- [Asynchronous Programming in Java](https://www.baeldung.com/java-asynchronous-programming)
- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock)
- [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference)
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

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

@ -0,0 +1,83 @@
package com.baeldung.exchanger;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import static java.util.concurrent.CompletableFuture.runAsync;
public class ExchangerPipeLineManualTest {
private static final int BUFFER_SIZE = 100;
@Test
public void givenData_whenPassedThrough_thenCorrect() throws InterruptedException, ExecutionException {
Exchanger<Queue<String>> readerExchanger = new Exchanger<>();
Exchanger<Queue<String>> writerExchanger = new Exchanger<>();
int counter = 0;
Runnable reader = () -> {
Queue<String> readerBuffer = new ConcurrentLinkedQueue<>();
while (true) {
readerBuffer.add(UUID.randomUUID().toString());
if (readerBuffer.size() >= BUFFER_SIZE) {
try {
readerBuffer = readerExchanger.exchange(readerBuffer);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}
};
Runnable processor = () -> {
Queue<String> processorBuffer = new ConcurrentLinkedQueue<>();
Queue<String> writterBuffer = new ConcurrentLinkedQueue<>();
try {
processorBuffer = readerExchanger.exchange(processorBuffer);
while (true) {
writterBuffer.add(processorBuffer.poll());
if (processorBuffer.isEmpty()) {
try {
processorBuffer = readerExchanger.exchange(processorBuffer);
writterBuffer = writerExchanger.exchange(writterBuffer);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
Runnable writer = () -> {
Queue<String> writterBuffer = new ConcurrentLinkedQueue<>();
try {
writterBuffer = writerExchanger.exchange(writterBuffer);
while (true) {
System.out.println(writterBuffer.poll());
if (writterBuffer.isEmpty()) {
writterBuffer = writerExchanger.exchange(writterBuffer);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
CompletableFuture.allOf(runAsync(reader), runAsync(processor), runAsync(writer)).get();
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.exchanger;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import static java.util.concurrent.CompletableFuture.runAsync;
public class ExchangerUnitTest {
@Test
public void givenThreads_whenMessageExchanged_thenCorrect() {
Exchanger<String> exchanger = new Exchanger<>();
Runnable taskA = () -> {
try {
String message = exchanger.exchange("from A");
assertEquals("from B", message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
Runnable taskB = () -> {
try {
String message = exchanger.exchange("from B");
assertEquals("from A", message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
CompletableFuture.allOf(runAsync(taskA), runAsync(taskB)).join();
}
@Test
public void givenThread_WhenExchangedMessage_thenCorrect() throws InterruptedException, ExecutionException {
Exchanger<String> exchanger = new Exchanger<>();
Runnable runner = () -> {
try {
String message = exchanger.exchange("from runner");
assertEquals("to runner", message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
CompletableFuture<Void> result = CompletableFuture.runAsync(runner);
String msg = exchanger.exchange("to runner");
assertEquals("from runner", msg);
result.join();
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.weeknumber;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class WeekNumberUsingCalendar {
public int getWeekNumberFrom(String day, String dateFormat, Locale locale) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance(locale);
Date date = sdf.parse(day);
calendar.setTime(date);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
public int getWeekNumberFrom(int year, int month, int day, Locale locale) {
Calendar calendar = Calendar.getInstance(locale);
calendar.set(year, month, day);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
public int getWeekNumberFrom(int year, int month, int day, int firstDayOfWeek, int minimalDaysInFirstWeek, Locale locale) {
Calendar calendar = Calendar.getInstance(locale);
calendar.setFirstDayOfWeek(firstDayOfWeek);
calendar.setMinimalDaysInFirstWeek(minimalDaysInFirstWeek);
calendar.set(year, month, day);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
public static void main(String[] args) {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
System.out.println(calendar.getWeekNumberFrom(2020, 2, 22, Locale.CANADA));
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.weeknumber;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class WeekNumberUsingLocalDate {
public Integer getWeekNumberUsingWeekFiedsFrom(String day, String dayFormat, Locale locale) {
LocalDate date = LocalDate.parse(day, DateTimeFormatter.ofPattern(dayFormat));
return date.get(WeekFields.of(locale)
.weekOfYear());
}
public Integer getWeekNumberUsinWeekFieldsFrom(int year, int month, int day, Locale locale) {
LocalDate date = LocalDate.of(year, month, day);
return date.get(WeekFields.of(locale)
.weekOfYear());
}
public Integer getWeekNumberUsingChronoFieldFrom(int year, int month, int day) {
LocalDate date = LocalDate.of(year, month, day);
return date.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.weeknumber;
import static org.junit.Assert.assertEquals;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Locale;
import org.junit.Test;
public class WeekNumberUsingCalendarUnitTest {
@Test
public void givenDateInStringAndDateFormatUsingLocaleItaly_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() throws ParseException {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(12, calendar.getWeekNumberFrom("20200322", "yyyyMMdd", Locale.ITALY));
}
@Test
public void givenDateInStringAndDateFormatUsingLocaleCanada_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() throws ParseException {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(13, calendar.getWeekNumberFrom("20200322", "yyyyMMdd", Locale.CANADA));
}
@Test
public void givenDateInYearMonthDayNumbersLocaleItaly_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(12, calendar.getWeekNumberFrom(2020, 2, 22, Locale.ITALY));
}
@Test
public void givenDateInYearMonthDayNumbersLocaleItalyChangingWeekCalculationSettings_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(13, calendar.getWeekNumberFrom(2020, 2, 22, Calendar.SUNDAY, 4, Locale.ITALY));
}
@Test
public void givenDateInYearMonthDayNumbersLocaleCanada_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(13, calendar.getWeekNumberFrom(2020, 2, 22, Locale.CANADA));
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.weeknumber;
import static org.junit.Assert.assertEquals;
import java.util.Locale;
import org.junit.Test;
public class WeekNumberUsingLocalDateUnitTest {
@Test
public void givenDateInStringAndDateFormatUsingWeekFieldsWithLocaleItaly_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(12, localDate.getWeekNumberUsingWeekFiedsFrom("20200322", "yyyyMMdd", Locale.ITALY)
.longValue());
}
@Test
public void givenDateInStringAndDateFormatUsingWeekFieldsWithLocaleCanada_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(13, localDate.getWeekNumberUsingWeekFiedsFrom("20200322", "yyyyMMdd", Locale.CANADA)
.longValue());
}
@Test
public void givenDateInStringAndDateFormatUsingChronoFieds_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(12, localDate.getWeekNumberUsingChronoFieldFrom(2020, 3, 22)
.longValue());
}
@Test
public void givenDateInYearMonthDayNumbersUsingWeekFieldsWithLocaleItaly_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(12, localDate.getWeekNumberUsinWeekFieldsFrom(2020, 3, 22, Locale.ITALY)
.longValue());
}
@Test
public void givenDateInYearMonthDayNumbersUsingWeekFieldsWithLocaleCanada_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(13, localDate.getWeekNumberUsinWeekFieldsFrom(2020, 3, 22, Locale.CANADA)
.longValue());
}
}

View File

@ -11,13 +11,26 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
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.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.equalTo;
@ -46,6 +59,18 @@ public class JavaInputStreamToXUnitTest {
assertEquals(textBuilder.toString(), originalString);
}
@Test
public void givenUsingJava8_whenConvertingAnInputStreamToAString_thenCorrect() {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
final String text = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))
.lines()
.collect(Collectors.joining("\n"));
assertThat(text, equalTo(originalString));
}
@Test
public final void givenUsingJava7_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);

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

@ -10,3 +10,4 @@
- [Difference Between Java Matcher find() and matches()](https://www.baeldung.com/java-matcher-find-vs-matches)
- [How to Use Regular Expressions to Replace Tokens in Strings](https://www.baeldung.com/java-regex-token-replacement)
- [Regular Expressions \s and \s+ in Java](https://www.baeldung.com/java-regex-s-splus)
- [Validate Phone Numbers With Java Regex](https://www.baeldung.com/java-regex-validate-phone-numbers)

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

@ -4,8 +4,10 @@ import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
@ -39,6 +41,27 @@ public class EncodeDecodeUnitTest {
}
@Test
public void givenJavaBase64_whenEncodedStream_thenDecodedStreamOK() throws IOException {
try (OutputStream os = java.util.Base64.getEncoder().wrap(new FileOutputStream(OUT_FILE));
FileInputStream fis = new FileInputStream(IN_FILE)) {
byte[] bytes = new byte[1024];
int read;
while ((read = fis.read(bytes)) > -1) {
os.write(bytes, 0, read);
}
}
byte[] encoded = java.util.Base64.getEncoder().encode(inFileBytes);
byte[] encodedOnDisk = Files.readAllBytes(Paths.get(OUT_FILE));
assertArrayEquals(encoded, encodedOnDisk);
byte[] decoded = java.util.Base64.getDecoder().decode(encoded);
byte[] decodedOnDisk = java.util.Base64.getDecoder().decode(encodedOnDisk);
assertArrayEquals(decoded, decodedOnDisk);
}
@Test
public void givenApacheCommons_givenJavaBase64_whenEncoded_thenDecodedOK() throws IOException {

View File

@ -9,3 +9,4 @@ This module contains articles about core Kotlin collections.
- [Converting a List to Map in Kotlin](https://www.baeldung.com/kotlin-list-to-map)
- [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection)
- [Collection Transformations in Kotlin](https://www.baeldung.com/kotlin-collection-transformations)
- [Difference between fold and reduce in Kotlin](https://www.baeldung.com/kotlin/fold-vs-reduce)

View File

@ -0,0 +1,86 @@
package com.baeldung.ifelseexpression
fun ifStatementUsage(): String {
val number = 15
if (number > 0) {
return "Positive number"
}
return "Positive number not found"
}
fun ifElseStatementUsage(): String {
val number = -50
if (number > 0) {
return "Positive number"
} else {
return "Negative number"
}
}
fun ifElseExpressionUsage(): String {
val number = -50
val result = if (number > 0) {
"Positive number"
} else {
"Negative number"
}
return result
}
fun ifElseExpressionSingleLineUsage(): String {
val number = -50
val result = if (number > 0) "Positive number" else "Negative number"
return result
}
fun ifElseMultipleExpressionUsage(): Int {
val x = 24
val y = 73
val result = if (x > y) {
println("$x is greater than $y")
x
} else {
println("$x is less than or equal to $y")
y
}
return result
}
fun ifElseLadderExpressionUsage(): String {
val number = 60
val result = if (number < 0) {
"Negative number"
} else if (number in 0..9) {
"Single digit number"
} else if (number in 10..99) {
"Double digit number"
} else {
"Number has more digits"
}
return result
}
fun ifElseNestedExpressionUsage(): Int {
val x = 37
val y = 89
val z = 6
val result = if (x > y) {
if (x > z)
x
else
z
} else {
if (y > z)
y
else
z
}
return result
}

View File

@ -0,0 +1,43 @@
package com.baeldung.ifelseexpression
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotEquals
class IfElseExpressionExampleTest {
@Test
fun givenNumber_whenIfStatementCalled_thenReturnsString() {
assertEquals("Positive number", ifStatementUsage())
}
@Test
fun givenNumber_whenIfElseStatementCalled_thenReturnsString() {
assertEquals("Negative number", ifElseStatementUsage())
}
@Test
fun givenNumber_whenIfElseExpressionCalled_thenReturnsString() {
assertEquals("Negative number", ifElseExpressionUsage())
}
@Test
fun givenNumber_whenIfElseExpressionSingleLineCalled_thenReturnsString() {
assertEquals("Negative number", ifElseExpressionSingleLineUsage())
}
@Test
fun givenNumber_whenIfElseMultipleExpressionCalled_thenReturnsNumber() {
assertEquals(73, ifElseMultipleExpressionUsage())
}
@Test
fun givenNumber_whenIfElseLadderExpressionCalled_thenReturnsString() {
assertEquals("Double digit number", ifElseLadderExpressionUsage())
}
@Test
fun givenNumber_whenIfElseNestedExpressionCalled_thenReturnsNumber() {
assertEquals(89, ifElseNestedExpressionUsage())
}
}

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:
- [Building a Java Application With Gradle](https://www.baeldung.com/gradle-building-a-java-app)

View File

@ -4,4 +4,5 @@ This module contains articles about conversions among Collection types and array
### Relevant Articles:
- [Array to String Conversions](https://www.baeldung.com/java-array-to-string)
- More articles: [[<-- prev]](../java-collections-conversions)
- [Mapping Lists with ModelMapper](https://www.baeldung.com/java-modelmapper-lists)
- More articles: [[<-- prev]](../java-collections-conversions)

View File

@ -6,6 +6,7 @@ import org.apache.commons.collections4.MapUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ConvertListToMapService {
@ -21,7 +22,7 @@ public class ConvertListToMapService {
}
public Map<Integer, Animal> convertListAfterJava8(List<Animal> list) {
Map<Integer, Animal> map = list.stream().collect(Collectors.toMap(Animal::getId, animal -> animal));
Map<Integer, Animal> map = list.stream().collect(Collectors.toMap(Animal::getId, Function.identity()));
return map;
}

View File

@ -53,14 +53,14 @@ public class CollectionToArrayListUnitTest {
verifyShallowCopy(srcCollection, newList);
}
/**
* Section 5. Deep Copy
*/
@Test
public void whenUsingDeepCopy_thenVerifyDeepCopy() {
ArrayList<Foo> newList = srcCollection.stream()
.map(foo -> foo.deepCopy())
.map(Foo::deepCopy)
.collect(toCollection(ArrayList::new));
verifyDeepCopy(srcCollection, newList);
@ -83,13 +83,13 @@ public class CollectionToArrayListUnitTest {
* @param a
* @param b
*/
private void verifyShallowCopy(Collection a, Collection b) {
private void verifyShallowCopy(Collection<Foo> a, Collection<Foo> b) {
assertEquals("Collections have different lengths", a.size(), b.size());
Iterator<Foo> iterA = a.iterator();
Iterator<Foo> iterB = b.iterator();
while (iterA.hasNext()) {
// use '==' to test instance identity
assertTrue("Foo instances differ!", iterA.next() == iterB.next());
// test instance identity
assertSame("Foo instances differ!", iterA.next(), iterB.next());
}
}
@ -98,7 +98,7 @@ public class CollectionToArrayListUnitTest {
* @param a
* @param b
*/
private void verifyDeepCopy(Collection a, Collection b) {
private void verifyDeepCopy(Collection<Foo> a, Collection<Foo> b) {
assertEquals("Collections have different lengths", a.size(), b.size());
Iterator<Foo> iterA = a.iterator();
Iterator<Foo> iterB = b.iterator();
@ -106,7 +106,7 @@ public class CollectionToArrayListUnitTest {
Foo nextA = iterA.next();
Foo nextB = iterB.next();
// should not be same instance
assertFalse("Foo instances are the same!", nextA == nextB);
assertNotSame("Foo instances are the same!", nextA, nextB);
// but should have same content
assertFalse("Foo instances have different content!", fooDiff(nextA, nextB));
}

View File

@ -23,7 +23,7 @@ public class ConvertIteratorToListServiceUnitTest {
Iterator<Integer> iterator;
@Before
public void setUp() throws Exception {
public void setUp() {
iterator = Arrays.asList(1, 2, 3)
.iterator();
}
@ -31,7 +31,7 @@ public class ConvertIteratorToListServiceUnitTest {
@Test
public void givenAnIterator_whenConvertIteratorToListUsingWhileLoop_thenReturnAList() {
List<Integer> actualList = new ArrayList<Integer>();
List<Integer> actualList = new ArrayList<>();
// Convert Iterator to List using while loop dsf
while (iterator.hasNext()) {
@ -44,7 +44,7 @@ public class ConvertIteratorToListServiceUnitTest {
@Test
public void givenAnIterator_whenConvertIteratorToListAfterJava8_thenReturnAList() {
List<Integer> actualList = new ArrayList<Integer>();
List<Integer> actualList = new ArrayList<>();
// Convert Iterator to List using Java 8
iterator.forEachRemaining(actualList::add);

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

@ -0,0 +1,5 @@
## Java Python Interop
This module contains articles about Java and Python interoperability.
### Relevant Articles:

View File

@ -0,0 +1,55 @@
<?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>
<artifactId>java-python-interop</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>java-python-interop</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-slim</artifactId>
<version>${jython.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>${commons-exec.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>java-python-interop</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<jython.version>2.7.2</jython.version>
<commons-exec.version>1.3</commons-exec.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,34 @@
package com.baeldung.python.interop;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class ScriptEngineManagerUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(ScriptEngineManagerUtils.class);
private ScriptEngineManagerUtils() {
}
public static void listEngines() {
ScriptEngineManager manager = new ScriptEngineManager();
List<ScriptEngineFactory> engines = manager.getEngineFactories();
for (ScriptEngineFactory engine : engines) {
LOGGER.info("Engine name: {}", engine.getEngineName());
LOGGER.info("Version: {}", engine.getEngineVersion());
LOGGER.info("Language: {}", engine.getLanguageName());
LOGGER.info("Short Names:");
for (String names : engine.getNames()) {
LOGGER.info(names);
}
}
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,131 @@
package com.baeldung.python.interop;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasItem;
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.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.List;
import java.util.stream.Collectors;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleScriptContext;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.PumpStreamHandler;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.python.core.PyException;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class JavaPythonInteropUnitTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void givenPythonScript_whenPythonProcessInvoked_thenSuccess() throws Exception {
ProcessBuilder processBuilder = new ProcessBuilder("python", resolvePythonScriptPath("hello.py"));
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
List<String> results = readProcessOutput(process.getInputStream());
assertThat("Results should not be empty", results, is(not(empty())));
assertThat("Results should contain output of script: ", results, hasItem(containsString("Hello Baeldung Readers!!")));
int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);
}
@Test
public void givenPythonScriptEngineIsAvailable_whenScriptInvoked_thenOutputDisplayed() throws Exception {
StringWriter output = new StringWriter();
ScriptContext context = new SimpleScriptContext();
context.setWriter(output);
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("python");
engine.eval(new FileReader(resolvePythonScriptPath("hello.py")), context);
assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", output.toString()
.trim());
}
@Test
public void givenPythonInterpreter_whenPrintExecuted_thenOutputDisplayed() {
try (PythonInterpreter pyInterp = new PythonInterpreter()) {
StringWriter output = new StringWriter();
pyInterp.setOut(output);
pyInterp.exec("print('Hello Baeldung Readers!!')");
assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", output.toString()
.trim());
}
}
@Test
public void givenPythonInterpreter_whenNumbersAdded_thenOutputDisplayed() {
try (PythonInterpreter pyInterp = new PythonInterpreter()) {
pyInterp.exec("x = 10+10");
PyObject x = pyInterp.get("x");
assertEquals("x: ", 20, x.asInt());
}
}
@Test
public void givenPythonInterpreter_whenErrorOccurs_thenExceptionIsThrown() {
thrown.expect(PyException.class);
thrown.expectMessage("ImportError: No module named syds");
try (PythonInterpreter pyInterp = new PythonInterpreter()) {
pyInterp.exec("import syds");
}
}
@Test
public void givenPythonScript_whenPythonProcessExecuted_thenSuccess() throws ExecuteException, IOException {
String line = "python " + resolvePythonScriptPath("hello.py");
CommandLine cmdLine = CommandLine.parse(line);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(streamHandler);
int exitCode = executor.execute(cmdLine);
assertEquals("No errors should be detected", 0, exitCode);
assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", outputStream.toString()
.trim());
}
private List<String> readProcessOutput(InputStream inputStream) throws IOException {
try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) {
return output.lines()
.collect(Collectors.toList());
}
}
private String resolvePythonScriptPath(String filename) {
File file = new File("src/test/resources/" + filename);
return file.getAbsolutePath();
}
}

View File

@ -0,0 +1 @@
print("Hello Baeldung Readers!!")

View File

@ -11,3 +11,4 @@ This module contains articles about JEE 7.
- [Introduction to Testing with Arquillian](https://www.baeldung.com/arquillian)
- [Java EE 7 Batch Processing](https://www.baeldung.com/java-ee-7-batch-processing)
- [The Difference Between CDI and EJB Singleton](https://www.baeldung.com/jee-cdi-vs-ejb-singleton)
- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service)

View File

@ -4,6 +4,7 @@ This module contains articles about jsoup.
### Relevant Articles:
- [Parsing HTML in Java with Jsoup](https://www.baeldung.com/java-with-jsoup)
- [How to add proxy support to Jsoup?](https://www.baeldung.com/java-jsoup-proxy)
### Build the Project

View File

@ -7,7 +7,7 @@ import java.net.Proxy;
import org.jsoup.Jsoup;
import org.junit.Test;
public class JsoupProxyIntegrationTest {
public class JsoupProxyLiveTest {
@Test
public void whenUsingHostAndPort_thenConnect() throws IOException {

3
kaniko/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [An Introduction to Kaniko](https://www.baeldung.com/ops/kaniko)

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

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