diff --git a/core-java-arrays/src/main/java/com/baeldung/array/operations/ArrayOperations.java b/core-java-arrays/src/main/java/com/baeldung/array/operations/ArrayOperations.java index 98155ed952..d8cc0afd61 100644 --- a/core-java-arrays/src/main/java/com/baeldung/array/operations/ArrayOperations.java +++ b/core-java-arrays/src/main/java/com/baeldung/array/operations/ArrayOperations.java @@ -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 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); + } } diff --git a/core-java-arrays/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java b/core-java-arrays/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java new file mode 100644 index 0000000000..3c61060ea8 --- /dev/null +++ b/core-java-arrays/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java @@ -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); + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/constructors/BankAccount.java b/core-java/src/main/java/com/baeldung/constructors/BankAccount.java new file mode 100644 index 0000000000..3d50e85245 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/constructors/BankAccount.java @@ -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; + } +} diff --git a/core-java/src/main/java/com/baeldung/constructors/Transaction.java b/core-java/src/main/java/com/baeldung/constructors/Transaction.java new file mode 100644 index 0000000000..14704f507a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/constructors/Transaction.java @@ -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. + } +} diff --git a/core-java/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java b/core-java/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java new file mode 100644 index 0000000000..2cd8832fbf --- /dev/null +++ b/core-java/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java @@ -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); + } +} diff --git a/core-java/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java b/core-java/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java new file mode 100644 index 0000000000..d952d2383b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java @@ -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)); + + } + + + + + + + +} diff --git a/java-dates/src/test/java/com/baeldung/timestamp/StringToTimestampConverterUnitTest.java b/java-dates/src/test/java/com/baeldung/timestamp/StringToTimestampConverterUnitTest.java new file mode 100644 index 0000000000..2be646eb51 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/timestamp/StringToTimestampConverterUnitTest.java @@ -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()); + } +} \ No newline at end of file diff --git a/java-dates/src/test/java/com/baeldung/timestamp/TimestampToStringConverterTest.java b/java-dates/src/test/java/com/baeldung/timestamp/TimestampToStringConverterTest.java new file mode 100644 index 0000000000..b25ff2edb3 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/timestamp/TimestampToStringConverterTest.java @@ -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); + } +} \ No newline at end of file diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml index c5b7fed951..92a643e458 100644 --- a/kotlin-libraries/pom.xml +++ b/kotlin-libraries/pom.xml @@ -87,6 +87,13 @@ h2 ${h2database.version} + + + io.arrow-kt + arrow-core + 0.7.3 + + diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEither.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEither.kt new file mode 100644 index 0000000000..75dfb9a2a4 --- /dev/null +++ b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEither.kt @@ -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 = 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 { + 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!" + } + } + } + +} \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOption.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOption.kt new file mode 100644 index 0000000000..5fddd1d88e --- /dev/null +++ b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOption.kt @@ -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 = 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 { + 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}" + } + } +} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalDataTypes.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalDataTypes.kt new file mode 100644 index 0000000000..692425ee07 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalDataTypes.kt @@ -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 = Id.just(length(s)) + + fun isBigEnoughId(i : Int) : Id = 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() + 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 = Option(null) + val fromNullable : Option = 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 = 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 = Either.right(42) + val leftOnly : Either = 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) + } + +} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEitherTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEitherTest.kt new file mode 100644 index 0000000000..47fbf825a0 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEitherTest.kt @@ -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() + } + } +} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOptionTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOptionTest.kt new file mode 100644 index 0000000000..3ca4cd033f --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOptionTest.kt @@ -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) + } + +} \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/DummyEntity.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/Message.java similarity index 76% rename from persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/DummyEntity.java rename to persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/Message.java index 12b57ff112..fb521cfea6 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/DummyEntity.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/Message.java @@ -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; } diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml index 6345e7f364..3fdc8ce27c 100644 --- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -23,7 +23,7 @@ org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.stringcast.DummyEntity + com.baeldung.jpa.stringcast.Message diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/stringcast/SpringCastUnitTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/stringcast/SpringCastUnitTest.java index d9c3adef26..0a11725fc3 100644 --- a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/stringcast/SpringCastUnitTest.java +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/stringcast/SpringCastUnitTest.java @@ -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 results = QueryExecutor.executeNativeQueryNoCastCheck("select text from dummy", em); + List 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 results = QueryExecutor.executeNativeQueryWithCastCheck("select text from dummy", em); + List results = QueryExecutor.executeNativeQueryWithCastCheck("select text from message", em); assertEquals("text", results.get(0)[0]); } @Test public void givenExecutorGeneric_whenQueryReturnsOneColumn_thenNoClassCastThrown() { - List results = QueryExecutor.executeNativeQueryGeneric("select text from dummy", "textQueryMapping", em); + List results = QueryExecutor.executeNativeQueryGeneric("select text from message", "textQueryMapping", em); assertEquals("text", results.get(0).getText()); } diff --git a/persistence-modules/java-jpa/src/test/resources/persistence.xml b/persistence-modules/java-jpa/src/test/resources/persistence.xml index b6cc51c3b3..c902e0a320 100644 --- a/persistence-modules/java-jpa/src/test/resources/persistence.xml +++ b/persistence-modules/java-jpa/src/test/resources/persistence.xml @@ -20,7 +20,7 @@ org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.stringcast.DummyEntity + com.baeldung.jpa.stringcast.Message diff --git a/spring-boot/src/main/resources/META-INF/spring.factories b/spring-boot/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..e3d3aa4c8e --- /dev/null +++ b/spring-boot/src/main/resources/META-INF/spring.factories @@ -0,0 +1 @@ +org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java new file mode 100644 index 0000000000..b3555f55da --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java @@ -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 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!"); + } + +} diff --git a/spring-boot/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java b/spring-boot/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java new file mode 100644 index 0000000000..a298f49ff5 --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java @@ -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 { + + static private List events = new ArrayList<>(); + + @Override + protected void append(ILoggingEvent eventObject) { + events.add(eventObject); + } + + public static List getEvents() { + return events; + } + + public static void clearEventList() { + events.clear(); + } +} \ No newline at end of file diff --git a/spring-boot/src/test/resources/logback-test.xml b/spring-boot/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..9e0f4e221f --- /dev/null +++ b/spring-boot/src/test/resources/logback-test.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-integration/src/main/java/com/baeldung/subflows/discardflow/FilterExample.java b/spring-integration/src/main/java/com/baeldung/subflows/discardflow/FilterExample.java new file mode 100644 index 0000000000..f0e12f9333 --- /dev/null +++ b/spring-integration/src/main/java/com/baeldung/subflows/discardflow/FilterExample.java @@ -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 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() + . filter(this::isMultipleOfThree, notMultiple -> notMultiple + .discardFlow(oneflow -> oneflow + . filter(this::isRemainderOne, + twoflow -> twoflow .discardChannel("remainderIsTwoChannel")) + .channel("remainderIsOneChannel"))) + .channel("multipleofThreeChannel"); + } + +} \ No newline at end of file diff --git a/spring-integration/src/main/java/com/baeldung/subflows/publishsubscribechannel/PublishSubscibeChannelExample.java b/spring-integration/src/main/java/com/baeldung/subflows/publishsubscribechannel/PublishSubscibeChannelExample.java index e26f938632..a1a448fc03 100644 --- a/spring-integration/src/main/java/com/baeldung/subflows/publishsubscribechannel/PublishSubscibeChannelExample.java +++ b/spring-integration/src/main/java/com/baeldung/subflows/publishsubscribechannel/PublishSubscibeChannelExample.java @@ -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 numbers); + @Gateway(requestChannel = "classify.input") + void classify(Collection 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. filter(p -> p % 3 == 0) - .channel("multipleof3Channel")) - .subscribe(f -> f. filter(p -> p % 3 == 1) - .channel("remainderIs1Channel")) - .subscribe(f -> f. filter(p -> p % 3 == 2) - .channel("remainderIs2Channel"))); + .publishSubscribeChannel(subscription -> subscription.subscribe(subflow -> subflow. filter(this::isMultipleOfThree) + .channel("multipleofThreeChannel")) + .subscribe(subflow -> subflow. filter(this::isRemainderOne) + .channel("remainderIsOneChannel")) + .subscribe(subflow -> subflow. 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(); - } } diff --git a/spring-integration/src/main/java/com/baeldung/subflows/routeToRecipients/RouteToRecipientsExample.java b/spring-integration/src/main/java/com/baeldung/subflows/routeToRecipients/RouteToRecipientsExample.java index 04fdb87dfa..e0b4841736 100644 --- a/spring-integration/src/main/java/com/baeldung/subflows/routeToRecipients/RouteToRecipientsExample.java +++ b/spring-integration/src/main/java/com/baeldung/subflows/routeToRecipients/RouteToRecipientsExample.java @@ -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 numbers); + @Gateway(requestChannel = "classify.input") + void classify(Collection 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. recipient("multipleof3Channel", p -> p % 3 == 0)// filter - . recipient("remainderIs1Channel", p -> p % 3 == 1) - .recipientFlow(sf -> sf. filter(p -> p % 3 == 2) - .channel("remainderIs2Channel"))); + .routeToRecipients(route -> route + .recipientFlow(subflow -> subflow + . filter(this::isMultipleOfThree) + .channel("multipleofThreeChannel")) + . recipient("remainderIsOneChannel",this::isRemainderOne) + . 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(); - } } \ No newline at end of file diff --git a/spring-integration/src/main/java/com/baeldung/subflows/separateflows/SeparateFlowsExample.java b/spring-integration/src/main/java/com/baeldung/subflows/separateflows/SeparateFlowsExample.java index 8ed46ead87..457b8045c5 100644 --- a/spring-integration/src/main/java/com/baeldung/subflows/separateflows/SeparateFlowsExample.java +++ b/spring-integration/src/main/java/com/baeldung/subflows/separateflows/SeparateFlowsExample.java @@ -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 is); + @Gateway(requestChannel = "multipleOfThreeFlow.input") + void multipleofThree(Collection numbers); - @Gateway(requestChannel = "remainderIs1Flow.input") - void remainderIs1(Collection is); + @Gateway(requestChannel = "remainderIsOneFlow.input") + void remainderIsOne(Collection numbers); - @Gateway(requestChannel = "remainderIs2Flow.input") - void remainderIs2(Collection numbers); + @Gateway(requestChannel = "remainderIsTwoFlow.input") + void remainderIsTwo(Collection 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() + . filter(this::isMultipleOfThree) + .channel("multipleOfThreeChannel"); } @Bean - DirectChannel remainderIs1Channel() { - return new DirectChannel(); + public IntegrationFlow remainderIsOneFlow() { + return flow -> flow.split() + . filter(this::isRemainderOne) + .channel("remainderIsOneChannel"); } @Bean - DirectChannel remainderIs2Channel() { - return new DirectChannel(); + public IntegrationFlow remainderIsTwoFlow() { + return flow -> flow.split() + . filter(this::isRemainderTwo) + .channel("remainderIsTwoChannel"); } - @Bean - public IntegrationFlow multipleof3Flow() { - return f -> f.split() - . filter(p -> p % 3 == 0) - .channel("multipleof3Channel"); - } - - @Bean - public IntegrationFlow remainderIs1Flow() { - return f -> f.split() - . filter(p -> p % 3 == 1) - .channel("remainderIs1Channel"); - } - - @Bean - public IntegrationFlow remainderIs2Flow() { - return f -> f.split() - . 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(); - } } \ No newline at end of file diff --git a/spring-integration/src/main/java/com/baeldung/subflows/subflowchannel/FilterExample.java b/spring-integration/src/main/java/com/baeldung/subflows/subflowchannel/FilterExample.java deleted file mode 100644 index 6db3741523..0000000000 --- a/spring-integration/src/main/java/com/baeldung/subflows/subflowchannel/FilterExample.java +++ /dev/null @@ -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 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() - . filter(x -> x % 3 == 0, sf -> sf.discardFlow(subf -> subf. 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(); - } -} \ No newline at end of file diff --git a/spring-integration/src/main/java/com/baeldung/subflows/subflowmapping/RouterExample.java b/spring-integration/src/main/java/com/baeldung/subflows/subflowmapping/RouterExample.java index de1f11cf70..c0e902e739 100644 --- a/spring-integration/src/main/java/com/baeldung/subflows/subflowmapping/RouterExample.java +++ b/spring-integration/src/main/java/com/baeldung/subflows/subflowmapping/RouterExample.java @@ -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 numbers); + @Gateway(requestChannel = "classify.input") + void classify(Collection 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() - . route(p -> p % 3, m -> m.channelMapping(0, "multipleof3Channel") - .subFlowMapping(1, sf -> sf.channel("remainderIs1Channel")) - .subFlowMapping(2, sf -> sf. handle((p, h) -> p))) - .channel("remainderIs2Channel"); + public IntegrationFlow classify() { + return flow -> flow.split() + . route(number -> number % 3, + mapping -> mapping + .channelMapping(0, "multipleofThreeChannel") + .subFlowMapping(1, subflow -> subflow.channel("remainderIsOneChannel")) + .subFlowMapping(2, subflow -> subflow + . 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(); - } } \ No newline at end of file diff --git a/spring-integration/src/test/java/com/baeldung/subflows/discardflow/FilterUnitTest.java b/spring-integration/src/test/java/com/baeldung/subflows/discardflow/FilterUnitTest.java new file mode 100644 index 0000000000..3b3106212b --- /dev/null +++ b/spring-integration/src/test/java/com/baeldung/subflows/discardflow/FilterUnitTest.java @@ -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); + + } + +} diff --git a/spring-integration/src/test/java/com/baeldung/subflows/publishsubscribechannel/PublishSubscribeChannelUnitTest.java b/spring-integration/src/test/java/com/baeldung/subflows/publishsubscribechannel/PublishSubscribeChannelUnitTest.java new file mode 100644 index 0000000000..91bf38c626 --- /dev/null +++ b/spring-integration/src/test/java/com/baeldung/subflows/publishsubscribechannel/PublishSubscribeChannelUnitTest.java @@ -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); + + } + +} diff --git a/spring-integration/src/test/java/com/baeldung/subflows/routetorecipients/RouteToRecipientsUnitTest.java b/spring-integration/src/test/java/com/baeldung/subflows/routetorecipients/RouteToRecipientsUnitTest.java new file mode 100644 index 0000000000..d7a768dcd9 --- /dev/null +++ b/spring-integration/src/test/java/com/baeldung/subflows/routetorecipients/RouteToRecipientsUnitTest.java @@ -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); + + } + +} diff --git a/spring-integration/src/test/java/com/baeldung/subflows/separateflows/SeparateFlowsUnitTest.java b/spring-integration/src/test/java/com/baeldung/subflows/separateflows/SeparateFlowsUnitTest.java new file mode 100644 index 0000000000..c02badcb1a --- /dev/null +++ b/spring-integration/src/test/java/com/baeldung/subflows/separateflows/SeparateFlowsUnitTest.java @@ -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); + + } + +} diff --git a/spring-integration/src/test/java/com/baeldung/subflows/subflowmapping/RouterUnitTest.java b/spring-integration/src/test/java/com/baeldung/subflows/subflowmapping/RouterUnitTest.java new file mode 100644 index 0000000000..9ecbb22a9b --- /dev/null +++ b/spring-integration/src/test/java/com/baeldung/subflows/subflowmapping/RouterUnitTest.java @@ -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); + + } + +}