[Java 11502] (#12625)

* [JAVA-11502] Added vavr-modules (parent)

* [JAVA-11502] Added vavr(submodule) to vavr-modules(parent)

* [JAVA-11502] Added vavr-2(submodule) to vavr-modules(parent)

* [JAVA-11502] Added java-vavr-stream(submodule) to vavr-modules(parent)

* [JAVA-11502] deleted modules that were moved + cleanup

Co-authored-by: panagiotiskakos <[email protected]>
Co-authored-by: Dhawal Kapil <[email protected]>
This commit is contained in:
panos-kakos
2022-08-25 21:17:55 +05:30
committed by GitHub
co-authored by panagiotiskakos Dhawal Kapil
parent 18d1cb40dc
commit 3ce04cafd5
40 changed files with 239 additions and 206 deletions
+3
View File
@@ -0,0 +1,3 @@
## VAVR
This module contains modules about vavr.
+8
View File
@@ -0,0 +1,8 @@
## Vavr Streams
This module contains articles about streams in Vavr.
### Relevant Articles:
- [Java Streams vs Vavr Streams](https://www.baeldung.com/vavr-java-streams)
+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.samples</groupId>
<artifactId>java-vavr-stream</artifactId>
<version>1.0</version>
<name>java-vavr-stream</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>vavr-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${io.vavr.version}</version>
</dependency>
</dependencies>
<properties>
<io.vavr.version>0.9.2</io.vavr.version>
</properties>
</project>
@@ -0,0 +1,98 @@
package com.baeldung.samples.java.vavr;
import io.vavr.collection.Stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
/**
*
* @author baeldung
*/
public class VavrSampler {
static int[] intArray = new int[]{1, 2, 4};
static List<Integer> intList = new ArrayList<Integer>();
static int[][] intOfInts = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
public static void main(String[] args) {
vavrStreamElementAccess();
System.out.println("====================================");
vavrParallelStreamAccess();
System.out.println("====================================");
jdkFlatMapping();
System.out.println("====================================");
vavrStreamManipulation();
System.out.println("====================================");
vavrStreamDistinct();
}
public static void vavrStreamElementAccess() {
System.out.println("Vavr Element Access");
System.out.println("====================================");
Stream<Integer> vavredStream = Stream.ofAll(intArray);
System.out.println("Vavr index access: " + vavredStream.get(2));
System.out.println("Vavr head element access: " + vavredStream.get());
Stream<String> vavredStringStream = Stream.of("foo", "bar", "baz");
System.out.println("Find foo " + vavredStringStream.indexOf("foo"));
}
public static void vavrParallelStreamAccess() {
try {
System.out.println("Vavr Stream Concurrent Modification");
System.out.println("====================================");
Stream<Integer> vavrStream = Stream.ofAll(intList);
intList.add(5);
vavrStream.forEach(i -> System.out.println("in a Vavr Stream: " + i));
} catch (Exception ex) {
ex.printStackTrace();
}
Stream<Integer> wrapped = Stream.ofAll(intArray);
intArray[2] = 5;
wrapped.forEach(i -> System.out.println("Vavr looped " + i));
}
public static void jdkFlatMapping() {
System.out.println("JDK FlatMap -> Uncomment line 68 to test");
System.out.println("====================================");
int[][] intOfInts = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
IntStream mapToInt = Arrays.stream(intOfInts)
.map(intArr -> Arrays.stream(intArr))
.flatMapToInt(val -> val.map(n -> {
return n * n;
}))
.peek(n -> System.out.println("Peeking at " + n));
//Uncomment to execute pipeline
//mapToInt.forEach(n -> System.out.println("FlatMapped Result "+n));
}
public static void vavrStreamManipulation() {
System.out.println("Vavr Stream Manipulation");
System.out.println("====================================");
List<String> stringList = new ArrayList<>();
stringList.add("foo");
stringList.add("bar");
stringList.add("baz");
Stream<String> vavredStream = Stream.ofAll(stringList);
vavredStream.forEach(item -> System.out.println("Vavr Stream item: " + item));
Stream<String> vavredStream2 = vavredStream.insert(2, "buzz");
vavredStream2.forEach(item -> System.out.println("Vavr Stream item after stream addition: " + item));
stringList.forEach(item -> System.out.println("List item after stream addition: " + item));
Stream<String> deletionStream = vavredStream.remove("bar");
deletionStream.forEach(item -> System.out.println("Vavr Stream item after stream item deletion: " + item));
}
public static void vavrStreamDistinct() {
Stream<String> vavredStream = Stream.of("foo", "bar", "baz", "buxx", "bar", "bar", "foo");
Stream<String> distinctVavrStream = vavredStream.distinctBy((y, z) -> {
return y.compareTo(z);
});
distinctVavrStream.forEach(item -> System.out.println("Vavr Stream item after distinct query " + item));
}
}
@@ -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>
+33
View File
@@ -0,0 +1,33 @@
<?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>vavr-modules</artifactId>
<name>vavr-modules</name>
<packaging>pom</packaging>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>vavr</module>
<module>vavr-2</module>
<module>java-vavr-stream</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
+8
View File
@@ -0,0 +1,8 @@
## Vavr
This module contains articles about Vavr.
### Relevant Articles:
- [Introduction to Vavr’s Either](https://www.baeldung.com/vavr-either)
- [Interoperability Between Java and Vavr](https://www.baeldung.com/java-vavr)
- [[<-- prev]](/vavr)
+27
View File
@@ -0,0 +1,27 @@
<?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>vavr-2</artifactId>
<name>vavr-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>vavr-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr-test</artifactId>
<version>${vavr.version}</version>
</dependency>
</dependencies>
<properties>
<vavr.version>0.9.1</vavr.version>
</properties>
</project>
@@ -0,0 +1,37 @@
package com.baeldung.vavr.either;
import java.util.HashMap;
import java.util.Map;
import io.vavr.control.Either;
public class EitherDemo {
public static Object[] computeWithoutEitherUsingArray(int marks) {
Object[] results = new Object[2];
if (marks < 85) {
results[0] = "Marks not acceptable";
} else {
results[1] = marks;
}
return results;
}
public static Map<String, Object> computeWithoutEitherUsingMap(int marks) {
Map<String, Object> results = new HashMap<>();
if (marks < 85) {
results.put("FAILURE", "Marks not acceptable");
} else {
results.put("SUCCESS", marks);
}
return results;
}
static Either<String, Integer> computeWithEither(int marks) {
if (marks < 85) {
return Either.left("Marks not acceptable");
} else {
return Either.right(marks);
}
}
}
@@ -0,0 +1,38 @@
package com.baeldung.vavr.either;
import io.vavr.control.Either;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class EitherUnitTest {
@Test
public void givenMarks_whenPassNumber_thenExpectNumber() {
Either<String, Integer> result = EitherDemo.computeWithEither(100);
int marks = result.right()
.getOrElseThrow(x -> new IllegalStateException());
assertEquals(100, marks);
}
@Test
public void givenMarks_whenFailNumber_thenExpectErrorMesssage() {
Either<String, Integer> result = EitherDemo.computeWithEither(50);
String error = result.left()
.getOrNull();
assertEquals("Marks not acceptable", error);
}
@Test
public void givenPassMarks_whenModified_thenExpectNumber() {
Either<String, Integer> result = EitherDemo.computeWithEither(90);
int marks = result.right()
.map(x -> x * 2)
.get();
assertEquals(180, marks);
}
}
@@ -0,0 +1,93 @@
package com.baeldung.vavr.interoperability;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Optional;
import org.junit.Test;
import io.vavr.collection.HashMap;
import io.vavr.collection.LinkedHashSet;
import io.vavr.collection.List;
import io.vavr.collection.Map;
import io.vavr.collection.Set;
import io.vavr.collection.Stream;
public class CollectionsInteroperabilityUnitTest {
@Test
public void givenParams_whenVavrList_thenReturnJavaList() {
List<String> vavrStringList = List.of("JAVA", "Javascript", "Scala");
java.util.List<String> javaStringList = vavrStringList.toJavaList();
assertTrue(javaStringList instanceof java.util.List);
}
@Test
public void givenParams_whenVavrStream_thenReturnJavaStream() {
Stream<String> vavrStream = Stream.of("JAVA", "Javascript", "Scala");
java.util.stream.Stream<String> javaParallelStream = vavrStream.toJavaParallelStream();
assertTrue(javaParallelStream instanceof java.util.stream.Stream);
java.util.List<String> javaStringList = vavrStream.toJavaList();
assertTrue(javaStringList instanceof java.util.List);
}
@Test
public void givenParams_whenVavrMap_thenReturnJavaMap() {
Map<String, String> vavrMap = HashMap.of("1", "a", "2", "b", "3", "c");
java.util.Map<String, String> javaMap = vavrMap.toJavaMap();
assertTrue(javaMap instanceof java.util.Map);
}
@Test
public void givenParams_whenJavaList_thenReturnVavrListUsingOfAll() {
java.util.List<String> javaList = Arrays.asList("Java", "Haskell", "Scala");
List<String> vavrList = List.ofAll(javaList);
assertTrue(vavrList instanceof io.vavr.collection.List);
}
@Test
public void givenParams_whenJavaStream_thenReturnVavrListUsingOfAll() {
java.util.stream.Stream<String> javaStream = Arrays.asList("Java", "Haskell", "Scala")
.stream();
Stream<String> vavrStream = Stream.ofAll(javaStream);
assertTrue(vavrStream instanceof io.vavr.collection.Stream);
}
@Test(expected = UnsupportedOperationException.class)
public void givenParams_whenVavrListConverted_thenException() {
java.util.List<String> javaList = List.of("Java", "Haskell", "Scala")
.asJava();
javaList.add("Python");
assertEquals(4, javaList.size());
}
@Test
public void givenParams_whenVavrListConvertedToMutable_thenRetunMutableList() {
java.util.List<String> javaList = List.of("Java", "Haskell", "Scala")
.asJavaMutable();
javaList.add("Python");
assertEquals(4, javaList.size());
}
@Test
public void givenParams_WhenVavarListConvertedToLinkedSet_thenReturnLinkedSet() {
List<String> vavrList = List.of("Java", "Haskell", "Scala", "Java");
Set<String> linkedSet = vavrList.toLinkedSet();
assertEquals(3, linkedSet.size());
assertTrue(linkedSet instanceof LinkedHashSet);
}
@Test
public void givenParams_WhenVavrList_thenReturnJavaOptional() {
List<String> vavrList = List.of("Java");
Optional<String> optional = vavrList.toJavaOptional();
assertEquals("Java", optional.get());
}
}
+16
View File
@@ -0,0 +1,16 @@
## Vavr
This module contains articles about Vavr.
### Relevant Articles:
- [Introduction to Vavr](https://www.baeldung.com/vavr)
- [Guide to Try in Vavr](https://www.baeldung.com/vavr-try)
- [Guide to Pattern Matching in Vavr](https://www.baeldung.com/vavr-pattern-matching)
- [Property Testing Example With Vavr](https://www.baeldung.com/vavr-property-testing)
- [Exceptions in Lambda Expression Using Vavr](https://www.baeldung.com/exceptions-using-vavr)
- [Vavr Support in Spring Data](https://www.baeldung.com/spring-vavr)
- [Introduction to Vavr’s Validation API](https://www.baeldung.com/vavr-validation-api)
- [Guide to Collections API in Vavr](https://www.baeldung.com/vavr-collections)
- [Collection Factory Methods for Vavr](https://www.baeldung.com/vavr-collection-factory-methods)
- [Introduction to Future in Vavr](https://www.baeldung.com/vavr-future)
- [[next -->]](/vavr-2)
+49
View File
@@ -0,0 +1,49 @@
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>vavr</artifactId>
<version>1.0</version>
<name>vavr</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr-test</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<vavr.version>0.9.1</vavr.version>
<awaitility.version>3.0.0</awaitility.version>
</properties>
</project>
@@ -0,0 +1,11 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@@ -0,0 +1,18 @@
package com.baeldung.repositories;
import org.springframework.data.repository.Repository;
import com.baeldung.vavr.User;
import io.vavr.collection.Seq;
import io.vavr.control.Option;
public interface VavrUserRepository extends Repository<User, Long> {
Option<User> findById(long id);
Seq<User> findByName(String name);
User save(User user);
}
@@ -0,0 +1,99 @@
package com.baeldung.samples.java.vavr;
import java.util.ArrayList;
import java.util.List;
import io.vavr.collection.Stream;
/**
*
* @author baeldung
*/
public class VavrSampler {
static int[] intArray = new int[] { 1, 2, 4 };
static List<Integer> intList = new ArrayList<>();
static int[][] intOfInts = new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
public static void main(String[] args) {
vavrStreamElementAccess();
System.out.println("====================================");
vavrParallelStreamAccess();
System.out.println("====================================");
vavrFlatMapping();
System.out.println("====================================");
vavrStreamManipulation();
System.out.println("====================================");
vavrStreamDistinct();
}
public static void vavrStreamElementAccess() {
System.out.println("Vavr Element Access");
System.out.println("====================================");
Stream<Integer> vavredStream = Stream.ofAll(intArray);
System.out.println("Vavr index access: " + vavredStream.get(2));
System.out.println("Vavr head element access: " + vavredStream.get());
Stream<String> vavredStringStream = Stream.of("foo", "bar", "baz");
System.out.println("Find foo " + vavredStringStream.indexOf("foo"));
}
public static void vavrParallelStreamAccess() {
System.out.println("Vavr Stream Concurrent Modification");
System.out.println("====================================");
Stream<Integer> vavrStream = Stream.ofAll(intList);
// intList.add(5);
vavrStream.forEach(i -> System.out.println("in a Vavr Stream: " + i));
// Stream<Integer> wrapped = Stream.ofAll(intArray);
// intArray[2] = 5;
// wrapped.forEach(i -> System.out.println("Vavr looped " + i));
}
public static void jdkFlatMapping() {
System.out.println("Java flatMapping");
System.out.println("====================================");
java.util.stream.Stream.of(42).flatMap(i -> java.util.stream.Stream.generate(() -> {
System.out.println("nested call");
return 42;
})).findAny();
}
public static void vavrFlatMapping() {
System.out.println("Vavr flatMapping");
System.out.println("====================================");
Stream.of(42)
.flatMap(i -> Stream.continually(() -> {
System.out.println("nested call");
return 42;
}))
.get(0);
}
public static void vavrStreamManipulation() {
System.out.println("Vavr Stream Manipulation");
System.out.println("====================================");
List<String> stringList = new ArrayList<>();
stringList.add("foo");
stringList.add("bar");
stringList.add("baz");
Stream<String> vavredStream = Stream.ofAll(stringList);
vavredStream.forEach(item -> System.out.println("Vavr Stream item: " + item));
Stream<String> vavredStream2 = vavredStream.insert(2, "buzz");
vavredStream2.forEach(item -> System.out.println("Vavr Stream item after stream addition: " + item));
stringList.forEach(item -> System.out.println("List item after stream addition: " + item));
Stream<String> deletionStream = vavredStream.remove("bar");
deletionStream.forEach(item -> System.out.println("Vavr Stream item after stream item deletion: " + item));
}
public static void vavrStreamDistinct() {
Stream<String> vavredStream = Stream.of("foo", "bar", "baz", "buxx", "bar", "bar", "foo");
Stream<String> distinctVavrStream = vavredStream.distinctBy((y, z) -> {
return y.compareTo(z);
});
distinctVavrStream.forEach(item -> System.out.println("Vavr Stream item after distinct query " + item));
}
}
@@ -0,0 +1,38 @@
package com.baeldung.vavr;
public class Person {
private String name;
private int age;
Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
@@ -0,0 +1,22 @@
package com.baeldung.vavr;
import io.vavr.collection.Seq;
import io.vavr.control.Validation;
class PersonValidator {
private static final String NAME_ERR = "Invalid characters in name: ";
private static final String AGE_ERR = "Age must be at least 0";
Validation<Seq<String>, Person> validatePerson(String name, int age) {
return Validation.combine(validateName(name), validateAge(age)).ap(Person::new);
}
private Validation<String, String> validateName(String name) {
String invalidChars = name.replaceAll("[a-zA-Z ]", "");
return invalidChars.isEmpty() ? Validation.valid(name) : Validation.invalid(NAME_ERR + invalidChars);
}
private Validation<String, Integer> validateAge(int age) {
return age < 0 ? Validation.invalid(AGE_ERR) : Validation.valid(age);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.vavr;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.vavr.exception.handling;
import com.baeldung.vavr.exception.handling.client.ClientException;
import com.baeldung.vavr.exception.handling.client.HttpClient;
import com.baeldung.vavr.exception.handling.client.Response;
public class JavaTryCatch {
private HttpClient httpClient;
public JavaTryCatch(HttpClient httpClient) {
this.httpClient = httpClient;
}
public Response getResponse() {
try {
return httpClient.call();
} catch (ClientException e) {
return null;
}
}
}
@@ -0,0 +1,18 @@
package com.baeldung.vavr.exception.handling;
import com.baeldung.vavr.exception.handling.client.HttpClient;
import com.baeldung.vavr.exception.handling.client.Response;
import io.vavr.control.Try;
class VavrTry {
private final HttpClient httpClient;
VavrTry(HttpClient httpClient) {
this.httpClient = httpClient;
}
Try<Response> getResponse() {
return Try.of(httpClient::call);
}
}
@@ -0,0 +1,8 @@
package com.baeldung.vavr.exception.handling.client;
public class ClientException extends Exception {
public ClientException(String message) {
super(message);
}
}
@@ -0,0 +1,6 @@
package com.baeldung.vavr.exception.handling.client;
public interface HttpClient {
Response call() throws ClientException;
}
@@ -0,0 +1,9 @@
package com.baeldung.vavr.exception.handling.client;
public class Response {
public final String id;
public Response(String id) {
this.id = id;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.vavrvalidation.application;
import com.baeldung.vavrvalidation.model.User;
import com.baeldung.vavrvalidation.validator.UserValidator;
import io.vavr.collection.Seq;
import io.vavr.control.Validation;
public class Application {
public static void main(String[] args) {
UserValidator userValidator = new UserValidator();
Validation<Seq<String>, User> validation = userValidator.validateUser("John", "[email protected]");
// process validation results here
}
}
@@ -0,0 +1,18 @@
package com.baeldung.vavrvalidation.model;
public class User {
private String name;
private String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
@Override
public String toString() {
return "User [name=" + name + ", email=" + email + "]";
}
// standard setters and getters
}
@@ -0,0 +1,29 @@
package com.baeldung.vavrvalidation.validator;
import com.baeldung.vavrvalidation.model.User;
import io.vavr.collection.CharSeq;
import io.vavr.collection.Seq;
import io.vavr.control.Validation;
public class UserValidator {
private static final String NAME_PATTERN = "^[a-zA-Z0-9]+$";
private static final String NAME_ERROR = "Name contains invalid characters";
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private static final String EMAIL_ERROR = "Email must be a well-formed email address";
public Validation<Seq<String>, User> validateUser(String name, String email) {
return Validation
.combine(validateField(name, NAME_PATTERN, NAME_ERROR)
,validateField(email, EMAIL_PATTERN, EMAIL_ERROR))
.ap(User::new);
}
private Validation<String, String> validateField(String field, String pattern, String error) {
return CharSeq.of(field).replaceAll(pattern, "").transform(seq -> seq.isEmpty()
? Validation.valid(field)
: Validation.invalid(error));
}
}
@@ -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>
@@ -0,0 +1,116 @@
package com.baeldung.vavr;
import io.vavr.MatchError;
import io.vavr.control.Option;
import org.junit.Test;
import static io.vavr.API.$;
import static io.vavr.API.Case;
import static io.vavr.API.Match;
import static io.vavr.API.run;
import static io.vavr.Predicates.allOf;
import static io.vavr.Predicates.anyOf;
import static io.vavr.Predicates.instanceOf;
import static io.vavr.Predicates.is;
import static io.vavr.Predicates.isIn;
import static io.vavr.Predicates.isNotNull;
import static io.vavr.Predicates.isNull;
import static io.vavr.Predicates.noneOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class PatternMatchingUnitTest {
@Test
public void whenMatchesDefault_thenCorrect() {
int input = 5;
String output = Match(input).of(Case($(1), "one"), Case($(2), "two"), Case($(3), "three"), Case($(), "unknown"));
assertEquals("unknown", output);
}
@Test(expected = MatchError.class)
public void givenNoMatchAndNoDefault_whenThrows_thenCorrect() {
int input = 5;
Match(input).of(Case($(1), "one"), Case($(2), "two"));
}
@Test
public void whenMatchWorksWithOption_thenCorrect() {
int i = 10;
Option<String> s = Match(i).option(Case($(0), "zero"));
assertTrue(s.isEmpty());
assertEquals("None", s.toString());
}
@Test
public void whenMatchWorksWithPredicate_thenCorrect() {
int i = 3;
String s = Match(i).of(Case($(is(1)), "one"), Case($(is(2)), "two"), Case($(is(3)), "three"), Case($(), "?"));
assertEquals("three", s);
}
@Test
public void givenInput_whenMatchesClass_thenCorrect() {
Object obj = 5;
String s = Match(obj).of(Case($(instanceOf(String.class)), "string matched"), Case($(), "not string"));
assertEquals("not string", s);
}
@Test
public void givenInput_whenMatchesNull_thenCorrect() {
Object obj = 5;
String s = Match(obj).of(Case($(isNull()), "no value"), Case($(isNotNull()), "value found"));
assertEquals("value found", s);
}
@Test
public void givenInput_whenContainsWorks_thenCorrect() {
int i = 5;
String s = Match(i).of(Case($(isIn(2, 4, 6, 8)), "Even Single Digit"), Case($(isIn(1, 3, 5, 7, 9)), "Odd Single Digit"), Case($(), "Out of range"));
assertEquals("Odd Single Digit", s);
}
@Test
public void givenInput_whenMatchAllWorks_thenCorrect() {
Integer i = null;
String s = Match(i).of(Case($(allOf(isNotNull(), isIn(1, 2, 3, null))), "Number found"), Case($(), "Not found"));
assertEquals("Not found", s);
}
@Test
public void givenInput_whenMatchesAnyOfWorks_thenCorrect() {
Integer year = 1990;
String s = Match(year).of(Case($(anyOf(isIn(1990, 1991, 1992), is(1986))), "Age match"), Case($(), "No age match"));
assertEquals("Age match", s);
}
@Test
public void givenInput_whenMatchesNoneOfWorks_thenCorrect() {
Integer year = 1990;
String s = Match(year).of(Case($(noneOf(isIn(1990, 1991, 1992), is(1986))), "Age match"), Case($(), "No age match"));
assertEquals("No age match", s);
}
@Test
public void whenMatchWorksWithPredicate_thenCorrect2() {
int i = 5;
String s = Match(i).of(Case($(isIn(2, 4, 6, 8)), "Even Single Digit"), Case($(isIn(1, 3, 5, 7, 9)), "Odd Single Digit"), Case($(), "Out of range"));
assertEquals("Odd Single Digit", s);
}
@Test
public void whenMatchCreatesSideEffects_thenCorrect() {
int i = 4;
Match(i).of(Case($(isIn(2, 4, 6, 8)), o -> run(this::displayEven)), Case($(isIn(1, 3, 5, 7, 9)), o -> run(this::displayOdd)), Case($(), o -> run(() -> {
throw new IllegalArgumentException(String.valueOf(i));
})));
}
private void displayEven() {
System.out.println("Input is even");
}
private void displayOdd() {
System.out.println("Input is odd");
}
}
@@ -0,0 +1,73 @@
package com.baeldung.vavr;
import io.vavr.CheckedFunction1;
import io.vavr.collection.Stream;
import io.vavr.test.Arbitrary;
import io.vavr.test.CheckResult;
import io.vavr.test.Property;
import org.junit.Test;
import java.util.function.Predicate;
import static io.vavr.API.$;
import static io.vavr.API.Case;
import static io.vavr.API.Match;
public class PropertyBasedLongRunningUnitTest {
private static Predicate<Integer> divisibleByTwo = i -> i % 2 == 0;
private static Predicate<Integer> divisibleByFive = i -> i % 5 == 0;
private Stream<String> stringsSupplier() {
return Stream.from(0).map(i -> Match(i).of(
Case($(divisibleByFive.and(divisibleByTwo)), "DividedByTwoAndFiveWithoutRemainder"),
Case($(divisibleByFive), "DividedByFiveWithoutRemainder"),
Case($(divisibleByTwo), "DividedByTwoWithoutRemainder"),
Case($(), "")));
}
@Test
public void givenArbitrarySeq_whenCheckThatEverySecondElementIsEqualToString_thenTestPass() {
//given
Arbitrary<Integer> multiplesOf2 = Arbitrary
.integer()
.filter(i -> i > 0)
.filter(i -> i % 2 == 0 && i % 5 != 0);
//when
CheckedFunction1<Integer, Boolean> mustEquals = i -> stringsSupplier()
.get(i)
.equals("DividedByTwoWithoutRemainder");
//then
CheckResult result = Property
.def("Every second element must equal to DividedByTwoWithoutRemainder")
.forAll(multiplesOf2)
.suchThat(mustEquals)
.check(10_000, 100);
result.assertIsSatisfied();
}
@Test
public void givenArbitrarySeq_whenCheckThatEveryFifthElementIsEqualToString_thenTestPass() {
//given
Arbitrary<Integer> multiplesOf5 = Arbitrary
.integer()
.filter(i -> i > 0)
.filter(i -> i % 5 == 0 && i % 2 == 0);
//when
CheckedFunction1<Integer, Boolean> mustEquals = i -> stringsSupplier()
.get(i)
.endsWith("DividedByTwoAndFiveWithoutRemainder");
//then
Property
.def("Every fifth element must equal to DividedByTwoAndFiveWithoutRemainder")
.forAll(multiplesOf5)
.suchThat(mustEquals)
.check(10_000, 1_000)
.assertIsSatisfied();
}
}

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