Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
6ebf7d0449
@ -4,11 +4,13 @@ import java.lang.reflect.Array;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntPredicate;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
@ -194,4 +196,16 @@ public class ArrayOperations {
|
||||
public static <T> T getRandomFromObjectArray(T[] array) {
|
||||
return array[new Random().nextInt(array.length)];
|
||||
}
|
||||
|
||||
public static Integer[] intersectionSimple(final Integer[] a, final Integer[] b){
|
||||
return Stream.of(a).filter(Arrays.asList(b)::contains).toArray(Integer[]::new);
|
||||
}
|
||||
|
||||
public static Integer[] intersectionSet(final Integer[] a, final Integer[] b){
|
||||
return Stream.of(a).filter(Arrays.asList(b)::contains).distinct().toArray(Integer[]::new);
|
||||
}
|
||||
|
||||
public static Integer[] intersectionMultiSet(final Integer[] a, final Integer[] b){
|
||||
return Stream.of(a).filter(new LinkedList<>(Arrays.asList(b))::remove).toArray(Integer[]::new);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,66 @@
|
||||
package com.baeldung.array.operations;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static com.baeldung.array.operations.ArrayOperations.intersectionMultiSet;
|
||||
import static com.baeldung.array.operations.ArrayOperations.intersectionSet;
|
||||
import static com.baeldung.array.operations.ArrayOperations.intersectionSimple;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class IntersectionUnitTest {
|
||||
private static final Integer[] a = { 1, 3, 2 };
|
||||
private static final Integer[] b = { 4, 3, 2, 4, 2, 3, 4, 4, 3 };
|
||||
private static final Integer[] c = { 1, 3, 2, 3, 3, 2 };
|
||||
|
||||
@Test
|
||||
void whenIntersectionSimpleIsUsed_thenCommonEntriesAreInTheResult() {
|
||||
assertThat(intersectionSimple(a, b)).isEqualTo(new Integer[] { 3, 2 });
|
||||
assertThat(intersectionSimple(b, a)).isEqualTo(new Integer[] { 3, 2, 2, 3, 3 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSimpleIsUsedWithAnArrayAndItself_thenTheResultIsTheIdentity() {
|
||||
assertThat(intersectionSimple(b, b)).isEqualTo(b);
|
||||
assertThat(intersectionSimple(a, a)).isEqualTo(a);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSetIsUsed_thenCommonEntriesAreInTheResult() {
|
||||
assertThat(intersectionSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSetIsUsed_thenTheNumberOfEntriesDoesNotChangeWithTheParameterOrder() {
|
||||
assertThat(intersectionSet(a, b)).isEqualTo(new Integer[] { 3, 2 });
|
||||
assertThat(intersectionSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSetIsUsedWithAnArrayAndWithItself_andTheInputHasNoDuplicateEntries_ThenTheResultIsTheIdentity() {
|
||||
assertThat(intersectionSet(a, a)).isEqualTo(a);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSetIsUsedWithAnArrayAndWithItself_andTheInputHasDuplicateEntries_ThenTheResultIsNotTheIdentity() {
|
||||
assertThat(intersectionSet(b, b)).isNotEqualTo(b);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMultiSetIsUsed_thenCommonEntriesAreInTheResult() {
|
||||
assertThat(intersectionMultiSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionMultiSetIsUsed_thenTheNumberOfEntriesDoesNotChangeWithTheParameterOrder() {
|
||||
assertThat(intersectionMultiSet(a, b)).isEqualTo(new Integer[] { 3, 2 });
|
||||
assertThat(intersectionMultiSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
|
||||
assertThat(intersectionMultiSet(b, c)).isEqualTo(new Integer[] { 3, 2, 2, 3, 3 });
|
||||
assertThat(intersectionMultiSet(c, b)).isEqualTo(new Integer[] { 3, 2, 3, 3, 2 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionMultiSetIsUsedWithAnArrayAndWithItself_ThenTheResultIsTheIdentity() {
|
||||
assertThat(intersectionMultiSet(b, b)).isEqualTo(b);
|
||||
assertThat(intersectionMultiSet(a, a)).isEqualTo(a);
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package com.baeldung.constructors;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
class BankAccount {
|
||||
String name;
|
||||
LocalDateTime opened;
|
||||
double balance;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s, %s, %f", this.name, this.opened.toString(), this.balance);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public LocalDateTime getOpened() {
|
||||
return opened;
|
||||
}
|
||||
|
||||
public double getBalance() {
|
||||
return this.balance;
|
||||
}
|
||||
}
|
||||
|
||||
class BankAccountEmptyConstructor extends BankAccount {
|
||||
public BankAccountEmptyConstructor() {
|
||||
this.name = "";
|
||||
this.opened = LocalDateTime.now();
|
||||
this.balance = 0.0d;
|
||||
}
|
||||
}
|
||||
|
||||
class BankAccountParameterizedConstructor extends BankAccount {
|
||||
public BankAccountParameterizedConstructor(String name, LocalDateTime opened, double balance) {
|
||||
this.name = name;
|
||||
this.opened = opened;
|
||||
this.balance = balance;
|
||||
}
|
||||
}
|
||||
|
||||
class BankAccountCopyConstructor extends BankAccount {
|
||||
public BankAccountCopyConstructor(String name, LocalDateTime opened, double balance) {
|
||||
this.name = name;
|
||||
this.opened = opened;
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
public BankAccountCopyConstructor(BankAccount other) {
|
||||
this.name = other.name;
|
||||
this.opened = LocalDateTime.now();
|
||||
this.balance = 0.0f;
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.constructors;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
class Transaction {
|
||||
final BankAccountEmptyConstructor bankAccount;
|
||||
final LocalDateTime date;
|
||||
final double amount;
|
||||
|
||||
public Transaction(BankAccountEmptyConstructor account, LocalDateTime date, double amount) {
|
||||
this.bankAccount = account;
|
||||
this.date = date;
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
/*
|
||||
* Compilation Error :'(, all final variables must be explicitly initialised.
|
||||
* public Transaction() {
|
||||
* }
|
||||
*/
|
||||
|
||||
public void invalidMethod() {
|
||||
// this.amount = 102.03; // Results in a compiler error. You cannot change the value of a final variable.
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.baeldung.constructors;
|
||||
|
||||
import com.baeldung.constructors.*;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Month;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
public class ConstructorUnitTest {
|
||||
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
|
||||
|
||||
@Test
|
||||
public void givenNoExplicitContructor_whenUsed_thenFails() {
|
||||
BankAccount account = new BankAccount();
|
||||
assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNoArgumentConstructor_whenUsed_thenSucceeds() {
|
||||
BankAccountEmptyConstructor account = new BankAccountEmptyConstructor();
|
||||
assertThatCode(() -> {
|
||||
account.toString();
|
||||
}).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParameterisedConstructor_whenUsed_thenSucceeds() {
|
||||
LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
|
||||
BankAccountParameterizedConstructor account =
|
||||
new BankAccountParameterizedConstructor("Tom", opened, 1000.0f);
|
||||
|
||||
assertThatCode(() -> {
|
||||
account.toString();
|
||||
}).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCopyContructor_whenUser_thenMaintainsLogic() {
|
||||
LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
|
||||
BankAccountCopyConstructor account = new BankAccountCopyConstructor("Tim", opened, 1000.0f);
|
||||
BankAccountCopyConstructor newAccount = new BankAccountCopyConstructor(account);
|
||||
|
||||
assertThat(account.getName()).isEqualTo(newAccount.getName());
|
||||
assertThat(account.getOpened()).isNotEqualTo(newAccount.getOpened());
|
||||
|
||||
assertThat(newAccount.getBalance()).isEqualTo(0.0f);
|
||||
}
|
||||
}
|
@ -0,0 +1,83 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class StringReplaceAndRemoveUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenReplace_thenProcessedString() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
String processed = master.replace(target, replacement);
|
||||
assertTrue(processed.contains(replacement));
|
||||
assertFalse(processed.contains(target));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenReplaceAll_thenProcessedString() {
|
||||
|
||||
String master2 = "Welcome to Baeldung, Hello World Baeldung";
|
||||
String regexTarget= "(Baeldung)$";
|
||||
String replacement = "Java";
|
||||
String processed2 = master2.replaceAll(regexTarget, replacement);
|
||||
assertTrue(processed2.endsWith("Java"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenStringBuilderMethods_thenProcessedString() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
|
||||
int startIndex = master.indexOf(target);
|
||||
int stopIndex = startIndex + target.length();
|
||||
|
||||
StringBuilder builder = new StringBuilder(master);
|
||||
|
||||
|
||||
builder.delete(startIndex, stopIndex);
|
||||
assertFalse(builder.toString().contains(target));
|
||||
|
||||
|
||||
builder.replace(startIndex, stopIndex, replacement);
|
||||
assertTrue(builder.toString().contains(replacement));
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
|
||||
String processed = StringUtils.replace(master, target, replacement);
|
||||
assertTrue(processed.contains(replacement));
|
||||
|
||||
String master2 = "Hello World Baeldung!";
|
||||
String target2 = "baeldung";
|
||||
String processed2 = StringUtils.replaceIgnoreCase(master2, target2, replacement);
|
||||
assertFalse(processed2.contains(target));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.timestamp;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public class StringToTimestampConverterUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDatePattern_whenParsing_thenTimestampIsCorrect() {
|
||||
String pattern = "MMM dd, yyyy HH:mm:ss.SSSSSSSS";
|
||||
String timestampAsString = "Nov 12, 2018 13:02:56.12345678";
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
|
||||
LocalDateTime localDateTime = LocalDateTime.from(formatter.parse(timestampAsString));
|
||||
|
||||
Timestamp timestamp = Timestamp.valueOf(localDateTime);
|
||||
Assert.assertEquals("2018-11-12 13:02:56.12345678", timestamp.toString());
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.baeldung.timestamp;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public class TimestampToStringConverterTest {
|
||||
|
||||
@Test
|
||||
public void givenDatePattern_whenFormatting_thenResultingStringIsCorrect() {
|
||||
Timestamp timestamp = Timestamp.valueOf("2018-12-12 01:02:03.123456789");
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
|
||||
|
||||
String timestampAsString = formatter.format(timestamp.toLocalDateTime());
|
||||
Assert.assertEquals("2018-12-12T01:02:03.123456789", timestampAsString);
|
||||
}
|
||||
}
|
@ -87,6 +87,13 @@
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2database.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/io.arrow-kt/arrow-core -->
|
||||
<dependency>
|
||||
<groupId>io.arrow-kt</groupId>
|
||||
<artifactId>arrow-core</artifactId>
|
||||
<version>0.7.3</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
@ -0,0 +1,54 @@
|
||||
package com.baeldung.kotlin.arrow
|
||||
|
||||
import arrow.core.Either
|
||||
import arrow.core.filterOrElse
|
||||
import kotlin.math.sqrt
|
||||
|
||||
class FunctionalErrorHandlingWithEither {
|
||||
|
||||
sealed class ComputeProblem {
|
||||
object OddNumber : ComputeProblem()
|
||||
object NotANumber : ComputeProblem()
|
||||
}
|
||||
|
||||
fun parseInput(s : String) : Either<ComputeProblem, Int> = Either.cond(s.toIntOrNull() != null, {-> s.toInt()}, {->ComputeProblem.NotANumber} )
|
||||
|
||||
fun isEven(x : Int) : Boolean = x % 2 == 0
|
||||
|
||||
fun biggestDivisor(x: Int) : Int = biggestDivisor(x, 2)
|
||||
|
||||
fun biggestDivisor(x : Int, y : Int) : Int {
|
||||
if(x == y){
|
||||
return 1;
|
||||
}
|
||||
if(x % y == 0){
|
||||
return x / y;
|
||||
}
|
||||
return biggestDivisor(x, y+1)
|
||||
}
|
||||
|
||||
fun isSquareNumber(x : Int) : Boolean {
|
||||
val sqrt: Double = sqrt(x.toDouble())
|
||||
return sqrt % 1.0 == 0.0
|
||||
}
|
||||
|
||||
fun computeWithEither(input : String) : Either<ComputeProblem, Boolean> {
|
||||
return parseInput(input)
|
||||
.filterOrElse(::isEven) {->ComputeProblem.OddNumber}
|
||||
.map (::biggestDivisor)
|
||||
.map (::isSquareNumber)
|
||||
}
|
||||
|
||||
fun computeWithEitherClient(input : String) {
|
||||
val computeWithEither = computeWithEither(input)
|
||||
|
||||
when(computeWithEither){
|
||||
is Either.Right -> "The greatest divisor is square number: ${computeWithEither.b}"
|
||||
is Either.Left -> when(computeWithEither.a){
|
||||
is ComputeProblem.NotANumber -> "Wrong input! Not a number!"
|
||||
is ComputeProblem.OddNumber -> "It is an odd number!"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
package com.baeldung.kotlin.arrow
|
||||
|
||||
import arrow.core.None
|
||||
import arrow.core.Option
|
||||
import arrow.core.Some
|
||||
import kotlin.math.sqrt
|
||||
|
||||
class FunctionalErrorHandlingWithOption {
|
||||
|
||||
fun parseInput(s : String) : Option<Int> = Option.fromNullable(s.toIntOrNull())
|
||||
|
||||
fun isEven(x : Int) : Boolean = x % 2 == 0
|
||||
|
||||
fun biggestDivisor(x: Int) : Int = biggestDivisor(x, 2)
|
||||
|
||||
fun biggestDivisor(x : Int, y : Int) : Int {
|
||||
if(x == y){
|
||||
return 1;
|
||||
}
|
||||
if(x % y == 0){
|
||||
return x / y;
|
||||
}
|
||||
return biggestDivisor(x, y+1)
|
||||
}
|
||||
|
||||
fun isSquareNumber(x : Int) : Boolean {
|
||||
val sqrt: Double = sqrt(x.toDouble())
|
||||
return sqrt % 1.0 == 0.0
|
||||
}
|
||||
|
||||
fun computeWithOption(input : String) : Option<Boolean> {
|
||||
return parseInput(input)
|
||||
.filter(::isEven)
|
||||
.map(::biggestDivisor)
|
||||
.map(::isSquareNumber)
|
||||
}
|
||||
|
||||
fun computeWithOptionClient(input : String) : String{
|
||||
val computeOption = computeWithOption(input)
|
||||
|
||||
return when(computeOption){
|
||||
is None -> "Not an even number!"
|
||||
is Some -> "The greatest divisor is square number: ${computeOption.t}"
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,143 @@
|
||||
package com.baeldung.kotlin.arrow
|
||||
|
||||
import arrow.core.*
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class FunctionalDataTypes {
|
||||
|
||||
@Test
|
||||
fun whenIdCreated_thanValueIsPresent(){
|
||||
val id = Id("foo")
|
||||
val justId = Id.just("foo");
|
||||
|
||||
Assert.assertEquals("foo", id.extract())
|
||||
Assert.assertEquals(justId, id)
|
||||
}
|
||||
|
||||
fun length(s : String) : Int = s.length
|
||||
|
||||
fun isBigEnough(i : Int) : Boolean = i > 10
|
||||
|
||||
@Test
|
||||
fun whenIdCreated_thanMapIsAssociative(){
|
||||
val foo = Id("foo")
|
||||
|
||||
val map1 = foo.map(::length)
|
||||
.map(::isBigEnough)
|
||||
val map2 = foo.map { s -> isBigEnough(length(s)) }
|
||||
|
||||
Assert.assertEquals(map1, map2)
|
||||
}
|
||||
|
||||
fun lengthId(s : String) : Id<Int> = Id.just(length(s))
|
||||
|
||||
fun isBigEnoughId(i : Int) : Id<Boolean> = Id.just(isBigEnough(i))
|
||||
|
||||
@Test
|
||||
fun whenIdCreated_thanFlatMapIsAssociative(){
|
||||
val bar = Id("bar")
|
||||
|
||||
val flatMap = bar.flatMap(::lengthId)
|
||||
.flatMap(::isBigEnoughId)
|
||||
val flatMap1 = bar.flatMap { s -> lengthId(s).flatMap(::isBigEnoughId) }
|
||||
|
||||
Assert.assertEquals(flatMap, flatMap1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenOptionCreated_thanValueIsPresent(){
|
||||
val factory = Option.just(42)
|
||||
val constructor = Option(42)
|
||||
val emptyOptional = Option.empty<Integer>()
|
||||
val fromNullable = Option.fromNullable(null)
|
||||
|
||||
Assert.assertEquals(42, factory.getOrElse { -1 })
|
||||
Assert.assertEquals(factory, constructor)
|
||||
Assert.assertEquals(emptyOptional, fromNullable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenOptionCreated_thanConstructorDifferFromFactory(){
|
||||
val constructor : Option<String?> = Option(null)
|
||||
val fromNullable : Option<String?> = Option.fromNullable(null)
|
||||
|
||||
try{
|
||||
constructor.map { s -> s!!.length }
|
||||
Assert.fail()
|
||||
} catch (e : KotlinNullPointerException){
|
||||
fromNullable.map { s->s!!.length }
|
||||
}
|
||||
Assert.assertNotEquals(constructor, fromNullable)
|
||||
}
|
||||
|
||||
fun wrapper(x : Integer?) : Option<Int> = if (x == null) Option.just(-1) else Option.just(x.toInt())
|
||||
|
||||
@Test
|
||||
fun whenOptionFromNullableCreated_thanItBreaksLeftIdentity(){
|
||||
val optionFromNull = Option.fromNullable(null)
|
||||
|
||||
Assert.assertNotEquals(optionFromNull.flatMap(::wrapper), wrapper(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenEitherCreated_thanOneValueIsPresent(){
|
||||
val rightOnly : Either<String,Int> = Either.right(42)
|
||||
val leftOnly : Either<String,Int> = Either.left("foo")
|
||||
|
||||
Assert.assertTrue(rightOnly.isRight())
|
||||
Assert.assertTrue(leftOnly.isLeft())
|
||||
Assert.assertEquals(42, rightOnly.getOrElse { -1 })
|
||||
Assert.assertEquals(-1, leftOnly.getOrElse { -1 })
|
||||
|
||||
Assert.assertEquals(0, rightOnly.map { it % 2 }.getOrElse { -1 })
|
||||
Assert.assertEquals(-1, leftOnly.map { it % 2 }.getOrElse { -1 })
|
||||
Assert.assertTrue(rightOnly.flatMap { Either.Right(it % 2) }.isRight())
|
||||
Assert.assertTrue(leftOnly.flatMap { Either.Right(it % 2) }.isLeft())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenEvalNowUsed_thenMapEvaluatedLazily(){
|
||||
val now = Eval.now(1)
|
||||
Assert.assertEquals(1, now.value())
|
||||
|
||||
var counter : Int = 0
|
||||
val map = now.map { x -> counter++; x+1 }
|
||||
Assert.assertEquals(0, counter)
|
||||
|
||||
val value = map.value()
|
||||
Assert.assertEquals(2, value)
|
||||
Assert.assertEquals(1, counter)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenEvalLaterUsed_theResultIsMemoized(){
|
||||
var counter : Int = 0
|
||||
val later = Eval.later { counter++; counter }
|
||||
Assert.assertEquals(0, counter)
|
||||
|
||||
val firstValue = later.value()
|
||||
Assert.assertEquals(1, firstValue)
|
||||
Assert.assertEquals(1, counter)
|
||||
|
||||
val secondValue = later.value()
|
||||
Assert.assertEquals(1, secondValue)
|
||||
Assert.assertEquals(1, counter)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenEvalAlwaysUsed_theResultIsNotMemoized(){
|
||||
var counter : Int = 0
|
||||
val later = Eval.always { counter++; counter }
|
||||
Assert.assertEquals(0, counter)
|
||||
|
||||
val firstValue = later.value()
|
||||
Assert.assertEquals(1, firstValue)
|
||||
Assert.assertEquals(1, counter)
|
||||
|
||||
val secondValue = later.value()
|
||||
Assert.assertEquals(2, secondValue)
|
||||
Assert.assertEquals(2, counter)
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package com.baeldung.kotlin.arrow
|
||||
|
||||
import arrow.core.Either
|
||||
import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.NotANumber
|
||||
import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.OddNumber
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class FunctionalErrorHandlingWithEitherTest {
|
||||
|
||||
val operator = FunctionalErrorHandlingWithEither()
|
||||
|
||||
@Test
|
||||
fun givenInvalidInput_whenComputeInvoked_NotANumberIsPresent(){
|
||||
val computeWithEither = operator.computeWithEither("bar")
|
||||
|
||||
Assert.assertTrue(computeWithEither.isLeft())
|
||||
when(computeWithEither){
|
||||
is Either.Left -> when(computeWithEither.a){
|
||||
NotANumber -> "Ok."
|
||||
else -> Assert.fail()
|
||||
}
|
||||
else -> Assert.fail()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenOddNumberInput_whenComputeInvoked_OddNumberIsPresent(){
|
||||
val computeWithEither = operator.computeWithEither("121")
|
||||
|
||||
Assert.assertTrue(computeWithEither.isLeft())
|
||||
when(computeWithEither){
|
||||
is Either.Left -> when(computeWithEither.a){
|
||||
OddNumber -> "Ok."
|
||||
else -> Assert.fail()
|
||||
}
|
||||
else -> Assert.fail()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenEvenNumberWithoutSquare_whenComputeInvoked_OddNumberIsPresent(){
|
||||
val computeWithEither = operator.computeWithEither("100")
|
||||
|
||||
Assert.assertTrue(computeWithEither.isRight())
|
||||
when(computeWithEither){
|
||||
is Either.Right -> when(computeWithEither.b){
|
||||
false -> "Ok."
|
||||
else -> Assert.fail()
|
||||
}
|
||||
else -> Assert.fail()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenEvenNumberWithSquare_whenComputeInvoked_OddNumberIsPresent(){
|
||||
val computeWithEither = operator.computeWithEither("98")
|
||||
|
||||
Assert.assertTrue(computeWithEither.isRight())
|
||||
when(computeWithEither){
|
||||
is Either.Right -> when(computeWithEither.b){
|
||||
true -> "Ok."
|
||||
else -> Assert.fail()
|
||||
}
|
||||
else -> Assert.fail()
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package com.baeldung.kotlin.arrow
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class FunctionalErrorHandlingWithOptionTest {
|
||||
|
||||
val operator = FunctionalErrorHandlingWithOption()
|
||||
|
||||
@Test
|
||||
fun givenInvalidInput_thenErrorMessageIsPresent(){
|
||||
val useComputeOption = operator.computeWithOptionClient("foo")
|
||||
Assert.assertEquals("Not an even number!", useComputeOption)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenOddNumberInput_thenErrorMessageIsPresent(){
|
||||
val useComputeOption = operator.computeWithOptionClient("539")
|
||||
Assert.assertEquals("Not an even number!",useComputeOption)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenEvenNumberInputWithNonSquareNum_thenFalseMessageIsPresent(){
|
||||
val useComputeOption = operator.computeWithOptionClient("100")
|
||||
Assert.assertEquals("The greatest divisor is square number: false",useComputeOption)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenEvenNumberInputWithSquareNum_thenTrueMessageIsPresent(){
|
||||
val useComputeOption = operator.computeWithOptionClient("242")
|
||||
Assert.assertEquals("The greatest divisor is square number: true",useComputeOption)
|
||||
}
|
||||
|
||||
}
|
@ -3,13 +3,12 @@ package com.baeldung.jpa.stringcast;
|
||||
import javax.persistence.*;
|
||||
|
||||
@SqlResultSetMapping(name = "textQueryMapping", classes = {
|
||||
@ConstructorResult(targetClass = DummyEntity.class, columns = {
|
||||
@ConstructorResult(targetClass = Message.class, columns = {
|
||||
@ColumnResult(name = "text")
|
||||
})
|
||||
})
|
||||
@Entity
|
||||
@Table(name = "dummy")
|
||||
public class DummyEntity {
|
||||
public class Message {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@ -17,11 +16,11 @@ public class DummyEntity {
|
||||
|
||||
private String text;
|
||||
|
||||
public DummyEntity() {
|
||||
public Message() {
|
||||
|
||||
}
|
||||
|
||||
public DummyEntity(String text) {
|
||||
public Message(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
@ -23,7 +23,7 @@
|
||||
|
||||
<persistence-unit name="jpa-h2">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.stringcast.DummyEntity</class>
|
||||
<class>com.baeldung.jpa.stringcast.Message</class>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
|
||||
|
@ -3,10 +3,7 @@ package com.baeldung.jpa.stringcast;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.EntityTransaction;
|
||||
import javax.persistence.Persistence;
|
||||
import javax.persistence.*;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
@ -22,18 +19,18 @@ public class SpringCastUnitTest {
|
||||
em = emFactory.createEntityManager();
|
||||
|
||||
// insert an object into the db
|
||||
DummyEntity dummyEntity = new DummyEntity();
|
||||
dummyEntity.setText("text");
|
||||
Message message = new Message();
|
||||
message.setText("text");
|
||||
|
||||
EntityTransaction tr = em.getTransaction();
|
||||
tr.begin();
|
||||
em.persist(dummyEntity);
|
||||
em.persist(message);
|
||||
tr.commit();
|
||||
}
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void givenExecutorNoCastCheck_whenQueryReturnsOneColumn_thenClassCastThrown() {
|
||||
List<String[]> results = QueryExecutor.executeNativeQueryNoCastCheck("select text from dummy", em);
|
||||
List<String[]> results = QueryExecutor.executeNativeQueryNoCastCheck("select text from message", em);
|
||||
|
||||
// fails
|
||||
for (String[] row : results) {
|
||||
@ -43,13 +40,13 @@ public class SpringCastUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenExecutorWithCastCheck_whenQueryReturnsOneColumn_thenNoClassCastThrown() {
|
||||
List<String[]> results = QueryExecutor.executeNativeQueryWithCastCheck("select text from dummy", em);
|
||||
List<String[]> results = QueryExecutor.executeNativeQueryWithCastCheck("select text from message", em);
|
||||
assertEquals("text", results.get(0)[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExecutorGeneric_whenQueryReturnsOneColumn_thenNoClassCastThrown() {
|
||||
List<DummyEntity> results = QueryExecutor.executeNativeQueryGeneric("select text from dummy", "textQueryMapping", em);
|
||||
List<Message> results = QueryExecutor.executeNativeQueryGeneric("select text from message", "textQueryMapping", em);
|
||||
assertEquals("text", results.get(0).getText());
|
||||
}
|
||||
|
||||
|
@ -20,7 +20,7 @@
|
||||
|
||||
<persistence-unit name="jpa-h2">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.stringcast.DummyEntity</class>
|
||||
<class>com.baeldung.jpa.stringcast.Message</class>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
|
||||
|
1
spring-boot/src/main/resources/META-INF/spring.factories
Normal file
1
spring-boot/src/main/resources/META-INF/spring.factories
Normal file
@ -0,0 +1 @@
|
||||
org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer
|
@ -0,0 +1,47 @@
|
||||
package com.baeldung.failureanalyzer;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.BeanCreationException;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
|
||||
import com.baeldung.failureanalyzer.utils.ListAppender;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
|
||||
public class FailureAnalyzerAppIntegrationTest {
|
||||
|
||||
private static final String EXPECTED_ANALYSIS_DESCRIPTION_TITLE = "Description:";
|
||||
private static final String EXPECTED_ANALYSIS_DESCRIPTION_CONTENT = "The bean myDAO could not be injected as com.baeldung.failureanalyzer.MyDAO because it is of type com.baeldung.failureanalyzer.MySecondDAO";
|
||||
private static final String EXPECTED_ANALYSIS_ACTION_TITLE = "Action:";
|
||||
private static final String EXPECTED_ANALYSIS_ACTION_CONTENT = "Consider creating a bean with name myDAO of type com.baeldung.failureanalyzer.MyDAO";
|
||||
|
||||
@BeforeEach
|
||||
public void clearLogList() {
|
||||
ListAppender.clearEventList();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBeanCreationErrorInContext_whenContextLoaded_thenFailureAnalyzerLogsReport() {
|
||||
try {
|
||||
SpringApplication.run(FailureAnalyzerApplication.class);
|
||||
} catch (BeanCreationException e) {
|
||||
Collection<String> allLoggedEntries = ListAppender.getEvents()
|
||||
.stream()
|
||||
.map(ILoggingEvent::getFormattedMessage)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(allLoggedEntries).anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_DESCRIPTION_TITLE))
|
||||
.anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_DESCRIPTION_CONTENT))
|
||||
.anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_ACTION_TITLE))
|
||||
.anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_ACTION_CONTENT));
|
||||
return;
|
||||
}
|
||||
throw new IllegalStateException("Context load should be failing due to a BeanCreationException!");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.failureanalyzer.utils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.AppenderBase;
|
||||
|
||||
public class ListAppender extends AppenderBase<ILoggingEvent> {
|
||||
|
||||
static private List<ILoggingEvent> events = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
protected void append(ILoggingEvent eventObject) {
|
||||
events.add(eventObject);
|
||||
}
|
||||
|
||||
public static List<ILoggingEvent> getEvents() {
|
||||
return events;
|
||||
}
|
||||
|
||||
public static void clearEventList() {
|
||||
events.clear();
|
||||
}
|
||||
}
|
15
spring-boot/src/test/resources/logback-test.xml
Normal file
15
spring-boot/src/test/resources/logback-test.xml
Normal file
@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<include
|
||||
resource="org/springframework/boot/logging/logback/base.xml" />
|
||||
<appender name="LISTAPPENDER"
|
||||
class="com.baeldung.failureanalyzer.utils.ListAppender">
|
||||
</appender>
|
||||
<logger
|
||||
name="org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter">
|
||||
<appender-ref ref="LISTAPPENDER" />
|
||||
</logger>
|
||||
<root level="info">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
</root>
|
||||
</configuration>
|
@ -0,0 +1,57 @@
|
||||
package com.baeldung.subflows.discardflow;
|
||||
|
||||
import java.util.Collection;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.integration.annotation.Gateway;
|
||||
import org.springframework.integration.annotation.IntegrationComponentScan;
|
||||
import org.springframework.integration.annotation.MessagingGateway;
|
||||
import org.springframework.integration.channel.QueueChannel;
|
||||
import org.springframework.integration.config.EnableIntegration;
|
||||
import org.springframework.integration.dsl.IntegrationFlow;
|
||||
|
||||
@EnableIntegration
|
||||
@IntegrationComponentScan
|
||||
public class FilterExample {
|
||||
@MessagingGateway
|
||||
public interface NumbersClassifier {
|
||||
@Gateway(requestChannel = "classify.input")
|
||||
void classify(Collection<Integer> numbers);
|
||||
}
|
||||
|
||||
@Bean
|
||||
QueueChannel multipleofThreeChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
QueueChannel remainderIsOneChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
QueueChannel remainderIsTwoChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
boolean isMultipleOfThree(Integer number) {
|
||||
return number % 3 == 0;
|
||||
}
|
||||
|
||||
boolean isRemainderOne(Integer number) {
|
||||
return number % 3 == 1;
|
||||
}
|
||||
|
||||
boolean isRemainderTwo(Integer number) {
|
||||
return number % 3 == 2;
|
||||
}
|
||||
@Bean
|
||||
public IntegrationFlow classify() {
|
||||
return flow -> flow.split()
|
||||
.<Integer> filter(this::isMultipleOfThree, notMultiple -> notMultiple
|
||||
.discardFlow(oneflow -> oneflow
|
||||
.<Integer> filter(this::isRemainderOne,
|
||||
twoflow -> twoflow .discardChannel("remainderIsTwoChannel"))
|
||||
.channel("remainderIsOneChannel")))
|
||||
.channel("multipleofThreeChannel");
|
||||
}
|
||||
|
||||
}
|
@ -1,15 +1,13 @@
|
||||
package com.baeldung.subflows.publishsubscribechannel;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.integration.annotation.Gateway;
|
||||
import org.springframework.integration.annotation.IntegrationComponentScan;
|
||||
import org.springframework.integration.annotation.MessagingGateway;
|
||||
import org.springframework.integration.channel.DirectChannel;
|
||||
|
||||
import org.springframework.integration.channel.QueueChannel;
|
||||
import org.springframework.integration.config.EnableIntegration;
|
||||
import org.springframework.integration.dsl.IntegrationFlow;
|
||||
|
||||
@ -18,46 +16,45 @@ import org.springframework.integration.dsl.IntegrationFlow;
|
||||
public class PublishSubscibeChannelExample {
|
||||
@MessagingGateway
|
||||
public interface NumbersClassifier {
|
||||
@Gateway(requestChannel = "flow.input")
|
||||
void flow(Collection<Integer> numbers);
|
||||
@Gateway(requestChannel = "classify.input")
|
||||
void classify(Collection<Integer> numbers);
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel multipleof3Channel() {
|
||||
return new DirectChannel();
|
||||
QueueChannel multipleofThreeChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel remainderIs1Channel() {
|
||||
return new DirectChannel();
|
||||
QueueChannel remainderIsOneChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel remainderIs2Channel() {
|
||||
return new DirectChannel();
|
||||
QueueChannel remainderIsTwoChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
boolean isMultipleOfThree(Integer number) {
|
||||
return number % 3 == 0;
|
||||
}
|
||||
|
||||
boolean isRemainderOne(Integer number) {
|
||||
return number % 3 == 1;
|
||||
}
|
||||
|
||||
boolean isRemainderTwo(Integer number) {
|
||||
return number % 3 == 2;
|
||||
}
|
||||
@Bean
|
||||
public IntegrationFlow flow() {
|
||||
public IntegrationFlow classify() {
|
||||
return flow -> flow.split()
|
||||
.publishSubscribeChannel(s -> s.subscribe(f -> f.<Integer> filter(p -> p % 3 == 0)
|
||||
.channel("multipleof3Channel"))
|
||||
.subscribe(f -> f.<Integer> filter(p -> p % 3 == 1)
|
||||
.channel("remainderIs1Channel"))
|
||||
.subscribe(f -> f.<Integer> filter(p -> p % 3 == 2)
|
||||
.channel("remainderIs2Channel")));
|
||||
.publishSubscribeChannel(subscription -> subscription.subscribe(subflow -> subflow.<Integer> filter(this::isMultipleOfThree)
|
||||
.channel("multipleofThreeChannel"))
|
||||
.subscribe(subflow -> subflow.<Integer> filter(this::isRemainderOne)
|
||||
.channel("remainderIsOneChannel"))
|
||||
.subscribe(subflow -> subflow.<Integer> filter(this::isRemainderTwo)
|
||||
.channel("remainderIsTwoChannel")));
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
final ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(PublishSubscibeChannelExample.class);
|
||||
DirectChannel multipleof3Channel = ctx.getBean("multipleof3Channel", DirectChannel.class);
|
||||
multipleof3Channel.subscribe(x -> System.out.println("multipleof3Channel: " + x));
|
||||
DirectChannel remainderIs1Channel = ctx.getBean("remainderIs1Channel", DirectChannel.class);
|
||||
remainderIs1Channel.subscribe(x -> System.out.println("remainderIs1Channel: " + x));
|
||||
DirectChannel remainderIs2Channel = ctx.getBean("remainderIs2Channel", DirectChannel.class);
|
||||
remainderIs2Channel.subscribe(x -> System.out.println("remainderIs2Channel: " + x));
|
||||
ctx.getBean(NumbersClassifier.class)
|
||||
.flow(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
ctx.close();
|
||||
}
|
||||
}
|
||||
|
@ -1,15 +1,12 @@
|
||||
package com.baeldung.subflows.routeToRecipients;
|
||||
package com.baeldung.subflows.routetorecipients;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.integration.annotation.Gateway;
|
||||
import org.springframework.integration.annotation.IntegrationComponentScan;
|
||||
import org.springframework.integration.annotation.MessagingGateway;
|
||||
import org.springframework.integration.channel.DirectChannel;
|
||||
import org.springframework.integration.channel.QueueChannel;
|
||||
import org.springframework.integration.config.EnableIntegration;
|
||||
import org.springframework.integration.dsl.IntegrationFlow;
|
||||
|
||||
@ -18,44 +15,46 @@ import org.springframework.integration.dsl.IntegrationFlow;
|
||||
public class RouteToRecipientsExample {
|
||||
@MessagingGateway
|
||||
public interface NumbersClassifier {
|
||||
@Gateway(requestChannel = "flow.input")
|
||||
void flow(Collection<Integer> numbers);
|
||||
@Gateway(requestChannel = "classify.input")
|
||||
void classify(Collection<Integer> numbers);
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel multipleof3Channel() {
|
||||
return new DirectChannel();
|
||||
QueueChannel multipleofThreeChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel remainderIs1Channel() {
|
||||
return new DirectChannel();
|
||||
QueueChannel remainderIsOneChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel remainderIs2Channel() {
|
||||
return new DirectChannel();
|
||||
QueueChannel remainderIsTwoChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
boolean isMultipleOfThree(Integer number) {
|
||||
return number % 3 == 0;
|
||||
}
|
||||
|
||||
boolean isRemainderOne(Integer number) {
|
||||
return number % 3 == 1;
|
||||
}
|
||||
|
||||
boolean isRemainderTwo(Integer number) {
|
||||
return number % 3 == 2;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IntegrationFlow flow() {
|
||||
public IntegrationFlow classify() {
|
||||
return flow -> flow.split()
|
||||
.routeToRecipients(r -> r.<Integer> recipient("multipleof3Channel", p -> p % 3 == 0)// filter
|
||||
.<Integer> recipient("remainderIs1Channel", p -> p % 3 == 1)
|
||||
.recipientFlow(sf -> sf.<Integer> filter(p -> p % 3 == 2)
|
||||
.channel("remainderIs2Channel")));
|
||||
.routeToRecipients(route -> route
|
||||
.recipientFlow(subflow -> subflow
|
||||
.<Integer> filter(this::isMultipleOfThree)
|
||||
.channel("multipleofThreeChannel"))
|
||||
.<Integer> recipient("remainderIsOneChannel",this::isRemainderOne)
|
||||
.<Integer> recipient("remainderIsTwoChannel",this::isRemainderTwo));
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
final ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(RouteToRecipientsExample.class);
|
||||
DirectChannel multipleof3Channel = ctx.getBean("multipleof3Channel", DirectChannel.class);
|
||||
multipleof3Channel.subscribe(x -> System.out.println("multipleof3Channel: " + x));
|
||||
DirectChannel remainderIs1Channel = ctx.getBean("remainderIs1Channel", DirectChannel.class);
|
||||
remainderIs1Channel.subscribe(x -> System.out.println("remainderIs1Channel: " + x));
|
||||
DirectChannel remainderIs2Channel = ctx.getBean("remainderIs2Channel", DirectChannel.class);
|
||||
remainderIs2Channel.subscribe(x -> System.out.println("remainderIs2Channel: " + x));
|
||||
ctx.getBean(NumbersClassifier.class)
|
||||
.flow(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
ctx.close();
|
||||
}
|
||||
}
|
@ -1,15 +1,13 @@
|
||||
package com.baeldung.subflows.separateflows;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.integration.annotation.Gateway;
|
||||
import org.springframework.integration.annotation.IntegrationComponentScan;
|
||||
import org.springframework.integration.annotation.MessagingGateway;
|
||||
import org.springframework.integration.channel.DirectChannel;
|
||||
|
||||
import org.springframework.integration.channel.QueueChannel;
|
||||
import org.springframework.integration.config.EnableIntegration;
|
||||
import org.springframework.integration.dsl.IntegrationFlow;
|
||||
|
||||
@ -18,66 +16,62 @@ import org.springframework.integration.dsl.IntegrationFlow;
|
||||
public class SeparateFlowsExample {
|
||||
@MessagingGateway
|
||||
public interface NumbersClassifier {
|
||||
@Gateway(requestChannel = "multipleof3Flow.input")
|
||||
void multipleof3(Collection<Integer> is);
|
||||
@Gateway(requestChannel = "multipleOfThreeFlow.input")
|
||||
void multipleofThree(Collection<Integer> numbers);
|
||||
|
||||
@Gateway(requestChannel = "remainderIs1Flow.input")
|
||||
void remainderIs1(Collection<Integer> is);
|
||||
@Gateway(requestChannel = "remainderIsOneFlow.input")
|
||||
void remainderIsOne(Collection<Integer> numbers);
|
||||
|
||||
@Gateway(requestChannel = "remainderIs2Flow.input")
|
||||
void remainderIs2(Collection<Integer> numbers);
|
||||
@Gateway(requestChannel = "remainderIsTwoFlow.input")
|
||||
void remainderIsTwo(Collection<Integer> numbers);
|
||||
}
|
||||
|
||||
@Bean
|
||||
QueueChannel multipleOfThreeChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
QueueChannel remainderIsOneChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
QueueChannel remainderIsTwoChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
|
||||
boolean isMultipleOfThree(Integer number) {
|
||||
return number % 3 == 0;
|
||||
}
|
||||
|
||||
boolean isRemainderOne(Integer number) {
|
||||
return number % 3 == 1;
|
||||
}
|
||||
|
||||
boolean isRemainderTwo(Integer number) {
|
||||
return number % 3 == 2;
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel multipleof3Channel() {
|
||||
return new DirectChannel();
|
||||
public IntegrationFlow multipleOfThreeFlow() {
|
||||
return flow -> flow.split()
|
||||
.<Integer> filter(this::isMultipleOfThree)
|
||||
.channel("multipleOfThreeChannel");
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel remainderIs1Channel() {
|
||||
return new DirectChannel();
|
||||
public IntegrationFlow remainderIsOneFlow() {
|
||||
return flow -> flow.split()
|
||||
.<Integer> filter(this::isRemainderOne)
|
||||
.channel("remainderIsOneChannel");
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel remainderIs2Channel() {
|
||||
return new DirectChannel();
|
||||
public IntegrationFlow remainderIsTwoFlow() {
|
||||
return flow -> flow.split()
|
||||
.<Integer> filter(this::isRemainderTwo)
|
||||
.channel("remainderIsTwoChannel");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IntegrationFlow multipleof3Flow() {
|
||||
return f -> f.split()
|
||||
.<Integer> filter(p -> p % 3 == 0)
|
||||
.channel("multipleof3Channel");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IntegrationFlow remainderIs1Flow() {
|
||||
return f -> f.split()
|
||||
.<Integer> filter(p -> p % 3 == 1)
|
||||
.channel("remainderIs1Channel");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IntegrationFlow remainderIs2Flow() {
|
||||
return f -> f.split()
|
||||
.<Integer> filter(p -> p % 3 == 2)
|
||||
.channel("remainderIs2Channel");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
final ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SeparateFlowsExample.class);
|
||||
DirectChannel multipleof3Channel = ctx.getBean("multipleof3Channel", DirectChannel.class);
|
||||
multipleof3Channel.subscribe(x -> System.out.println("multipleof3Channel: " + x));
|
||||
DirectChannel remainderIs1Channel = ctx.getBean("remainderIs1Channel", DirectChannel.class);
|
||||
remainderIs1Channel.subscribe(x -> System.out.println("remainderIs1Channel: " + x));
|
||||
DirectChannel remainderIs2Channel = ctx.getBean("remainderIs2Channel", DirectChannel.class);
|
||||
remainderIs2Channel.subscribe(x -> System.out.println("remainderIs2Channel: " + x));
|
||||
ctx.getBean(NumbersClassifier.class)
|
||||
.multipleof3(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
ctx.getBean(NumbersClassifier.class)
|
||||
.remainderIs1(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
ctx.getBean(NumbersClassifier.class)
|
||||
.remainderIs2(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
ctx.close();
|
||||
}
|
||||
}
|
@ -1,60 +0,0 @@
|
||||
package com.baeldung.subflows.subflowchannel;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.integration.annotation.Gateway;
|
||||
import org.springframework.integration.annotation.IntegrationComponentScan;
|
||||
import org.springframework.integration.annotation.MessagingGateway;
|
||||
import org.springframework.integration.channel.DirectChannel;
|
||||
import org.springframework.integration.config.EnableIntegration;
|
||||
import org.springframework.integration.dsl.IntegrationFlow;
|
||||
|
||||
@EnableIntegration
|
||||
@IntegrationComponentScan
|
||||
public class FilterExample {
|
||||
@MessagingGateway
|
||||
public interface NumbersClassifier {
|
||||
@Gateway(requestChannel = "flow.input")
|
||||
void flow(Collection<Integer> numbers);
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel multipleof3Channel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel remainderIs1Channel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel remainderIs2Channel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IntegrationFlow flow() {
|
||||
return flow -> flow.split()
|
||||
.<Integer> filter(x -> x % 3 == 0, sf -> sf.discardFlow(subf -> subf.<Integer> filter(x -> x % 3 == 1, ssf -> ssf.discardChannel("remainderIs2Channel"))
|
||||
.channel("remainderIs1Channel")))
|
||||
.channel("multipleof3Channel");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
final ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(FilterExample.class);
|
||||
DirectChannel multipleof3Channel = ctx.getBean("multipleof3Channel", DirectChannel.class);
|
||||
multipleof3Channel.subscribe(x -> System.out.println("multipleof3Channel: " + x));
|
||||
DirectChannel remainderIs1Channel = ctx.getBean("remainderIs1Channel", DirectChannel.class);
|
||||
remainderIs1Channel.subscribe(x -> System.out.println("remainderIs1Channel: " + x));
|
||||
DirectChannel remainderIs2Channel = ctx.getBean("remainderIs2Channel", DirectChannel.class);
|
||||
remainderIs2Channel.subscribe(x -> System.out.println("remainderIs2Channel: " + x));
|
||||
ctx.getBean(NumbersClassifier.class)
|
||||
.flow(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
ctx.close();
|
||||
}
|
||||
}
|
@ -1,15 +1,11 @@
|
||||
package com.baeldung.subflows.subflowmapping;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.integration.annotation.Gateway;
|
||||
import org.springframework.integration.annotation.IntegrationComponentScan;
|
||||
import org.springframework.integration.annotation.MessagingGateway;
|
||||
import org.springframework.integration.channel.DirectChannel;
|
||||
import org.springframework.integration.channel.QueueChannel;
|
||||
import org.springframework.integration.config.EnableIntegration;
|
||||
import org.springframework.integration.dsl.IntegrationFlow;
|
||||
|
||||
@ -18,44 +14,49 @@ import org.springframework.integration.dsl.IntegrationFlow;
|
||||
public class RouterExample {
|
||||
@MessagingGateway
|
||||
public interface NumbersClassifier {
|
||||
@Gateway(requestChannel = "flow.input")
|
||||
void flow(Collection<Integer> numbers);
|
||||
@Gateway(requestChannel = "classify.input")
|
||||
void classify(Collection<Integer> numbers);
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel multipleof3Channel() {
|
||||
return new DirectChannel();
|
||||
QueueChannel multipleofThreeChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel remainderIs1Channel() {
|
||||
return new DirectChannel();
|
||||
QueueChannel remainderIsOneChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
|
||||
@Bean
|
||||
DirectChannel remainderIs2Channel() {
|
||||
return new DirectChannel();
|
||||
QueueChannel remainderIsTwoChannel() {
|
||||
return new QueueChannel();
|
||||
}
|
||||
|
||||
boolean isMultipleOfThree(Integer number) {
|
||||
return number % 3 == 0;
|
||||
}
|
||||
|
||||
boolean isRemainderOne(Integer number) {
|
||||
return number % 3 == 1;
|
||||
}
|
||||
|
||||
boolean isRemainderTwo(Integer number) {
|
||||
return number % 3 == 2;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IntegrationFlow flow() {
|
||||
return f -> f.split()
|
||||
.<Integer, Integer> route(p -> p % 3, m -> m.channelMapping(0, "multipleof3Channel")
|
||||
.subFlowMapping(1, sf -> sf.channel("remainderIs1Channel"))
|
||||
.subFlowMapping(2, sf -> sf.<Integer> handle((p, h) -> p)))
|
||||
.channel("remainderIs2Channel");
|
||||
public IntegrationFlow classify() {
|
||||
return flow -> flow.split()
|
||||
.<Integer, Integer> route(number -> number % 3,
|
||||
mapping -> mapping
|
||||
.channelMapping(0, "multipleofThreeChannel")
|
||||
.subFlowMapping(1, subflow -> subflow.channel("remainderIsOneChannel"))
|
||||
.subFlowMapping(2, subflow -> subflow
|
||||
.<Integer> handle((payload, headers) -> {
|
||||
// do extra work on the payload
|
||||
return payload;
|
||||
}))).channel("remainderIsTwoChannel");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
final ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(RouterExample.class);
|
||||
DirectChannel multipleof3Channel = ctx.getBean("multipleof3Channel", DirectChannel.class);
|
||||
multipleof3Channel.subscribe(x -> System.out.println("multipleof3Channel: " + x));
|
||||
DirectChannel remainderIs1Channel = ctx.getBean("remainderIs1Channel", DirectChannel.class);
|
||||
remainderIs1Channel.subscribe(x -> System.out.println("remainderIs1Channel: " + x));
|
||||
DirectChannel remainderIs2Channel = ctx.getBean("remainderIs2Channel", DirectChannel.class);
|
||||
remainderIs2Channel.subscribe(x -> System.out.println("remainderIs2Channel: " + x));
|
||||
ctx.getBean(NumbersClassifier.class)
|
||||
.flow(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
ctx.close();
|
||||
}
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
package com.baeldung.subflows.discardflow;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.integration.channel.QueueChannel;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.baeldung.subflows.discardflow.FilterExample.NumbersClassifier;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { FilterExample.class })
|
||||
public class FilterUnitTest {
|
||||
@Autowired
|
||||
private QueueChannel multipleofThreeChannel;
|
||||
|
||||
@Autowired
|
||||
private QueueChannel remainderIsOneChannel;
|
||||
|
||||
@Autowired
|
||||
private QueueChannel remainderIsTwoChannel;
|
||||
|
||||
@Autowired
|
||||
private NumbersClassifier numbersClassifier;
|
||||
|
||||
@Test
|
||||
public void whenSendMessagesToFlow_thenNumbersAreClassified() {
|
||||
|
||||
numbersClassifier.classify(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
|
||||
Message<?> outMessage = multipleofThreeChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 3);
|
||||
|
||||
outMessage = multipleofThreeChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 6);
|
||||
|
||||
outMessage = remainderIsOneChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 1);
|
||||
outMessage = remainderIsOneChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 4);
|
||||
|
||||
outMessage = remainderIsTwoChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 2);
|
||||
|
||||
outMessage = remainderIsTwoChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 5);
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
package com.baeldung.subflows.publishsubscribechannel;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.integration.channel.QueueChannel;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.baeldung.subflows.publishsubscribechannel.PublishSubscibeChannelExample.NumbersClassifier;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { PublishSubscibeChannelExample.class })
|
||||
public class PublishSubscribeChannelUnitTest {
|
||||
@Autowired
|
||||
private QueueChannel multipleofThreeChannel;
|
||||
|
||||
@Autowired
|
||||
private QueueChannel remainderIsOneChannel;
|
||||
|
||||
@Autowired
|
||||
private QueueChannel remainderIsTwoChannel;
|
||||
|
||||
@Autowired
|
||||
private NumbersClassifier numbersClassifier;
|
||||
|
||||
@Test
|
||||
public void whenSendMessagesToFlow_thenNumbersAreClassified() {
|
||||
|
||||
numbersClassifier.classify(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
|
||||
Message<?> outMessage = multipleofThreeChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 3);
|
||||
|
||||
outMessage = multipleofThreeChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 6);
|
||||
|
||||
outMessage = remainderIsOneChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 1);
|
||||
outMessage = remainderIsOneChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 4);
|
||||
|
||||
outMessage = remainderIsTwoChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 2);
|
||||
|
||||
outMessage = remainderIsTwoChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 5);
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,63 @@
|
||||
package com.baeldung.subflows.routetorecipients;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.integration.channel.QueueChannel;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.baeldung.subflows.routetorecipients.RouteToRecipientsExample;
|
||||
import com.baeldung.subflows.routetorecipients.RouteToRecipientsExample.NumbersClassifier;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { RouteToRecipientsExample.class })
|
||||
public class RouteToRecipientsUnitTest {
|
||||
@Autowired
|
||||
private QueueChannel multipleofThreeChannel;
|
||||
|
||||
@Autowired
|
||||
private QueueChannel remainderIsOneChannel;
|
||||
|
||||
@Autowired
|
||||
private QueueChannel remainderIsTwoChannel;
|
||||
|
||||
@Autowired
|
||||
private NumbersClassifier numbersClassifier;
|
||||
|
||||
@Test
|
||||
public void whenSendMessagesToFlow_thenNumbersAreClassified() {
|
||||
|
||||
numbersClassifier.classify(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
|
||||
Message<?> outMessage = multipleofThreeChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 3);
|
||||
|
||||
outMessage = multipleofThreeChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 6);
|
||||
|
||||
outMessage = remainderIsOneChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 1);
|
||||
outMessage = remainderIsOneChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 4);
|
||||
|
||||
outMessage = remainderIsTwoChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 2);
|
||||
|
||||
outMessage = remainderIsTwoChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 5);
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
package com.baeldung.subflows.separateflows;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.integration.channel.QueueChannel;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import com.baeldung.subflows.separateflows.SeparateFlowsExample.NumbersClassifier;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { SeparateFlowsExample.class })
|
||||
public class SeparateFlowsUnitTest {
|
||||
@Autowired
|
||||
private QueueChannel multipleOfThreeChannel;
|
||||
@Autowired
|
||||
private QueueChannel remainderIsOneChannel;
|
||||
@Autowired
|
||||
private QueueChannel remainderIsTwoChannel;
|
||||
|
||||
@Autowired
|
||||
private NumbersClassifier numbersClassifier;
|
||||
|
||||
@Test
|
||||
public void whenSendMessagesToMultipleOf3Flow_thenOutputMultiplesOf3() {
|
||||
|
||||
numbersClassifier.multipleofThree(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
|
||||
Message<?> outMessage = multipleOfThreeChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 3);
|
||||
|
||||
outMessage = multipleOfThreeChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 6);
|
||||
outMessage = multipleOfThreeChannel.receive(0);
|
||||
assertNull(outMessage);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendMessagesToRemainderIs1Flow_thenOutputRemainderIs1() {
|
||||
|
||||
numbersClassifier.remainderIsOne(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
|
||||
Message<?> outMessage = remainderIsOneChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 1);
|
||||
|
||||
outMessage = remainderIsOneChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 4);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendMessagesToRemainderIs2Flow_thenOutputRemainderIs2() {
|
||||
|
||||
numbersClassifier.remainderIsTwo(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
|
||||
Message<?> outMessage = remainderIsTwoChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 2);
|
||||
|
||||
outMessage = remainderIsTwoChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 5);
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
package com.baeldung.subflows.subflowmapping;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.integration.channel.QueueChannel;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.baeldung.subflows.subflowmapping.RouterExample.NumbersClassifier;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { RouterExample.class })
|
||||
public class RouterUnitTest {
|
||||
@Autowired
|
||||
private QueueChannel multipleofThreeChannel;
|
||||
|
||||
@Autowired
|
||||
private QueueChannel remainderIsOneChannel;
|
||||
|
||||
@Autowired
|
||||
private QueueChannel remainderIsTwoChannel;
|
||||
|
||||
@Autowired
|
||||
private NumbersClassifier numbersClassifier;
|
||||
|
||||
@Test
|
||||
public void whenSendMessagesToFlow_thenNumbersAreClassified() {
|
||||
|
||||
numbersClassifier.classify(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
|
||||
Message<?> outMessage = multipleofThreeChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 3);
|
||||
|
||||
outMessage = multipleofThreeChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 6);
|
||||
|
||||
outMessage = remainderIsOneChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 1);
|
||||
outMessage = remainderIsOneChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 4);
|
||||
|
||||
outMessage = remainderIsTwoChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 2);
|
||||
|
||||
outMessage = remainderIsTwoChannel.receive(0);
|
||||
|
||||
assertEquals(outMessage.getPayload(), 5);
|
||||
|
||||
}
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user