diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameBoard.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameBoard.java new file mode 100644 index 0000000000..b10bd95a19 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameBoard.java @@ -0,0 +1,129 @@ +package com.baeldung.algorithms.connect4; + +import java.util.ArrayList; +import java.util.List; + +public class GameBoard { + private final List> columns; + + private final int rows; + + public GameBoard(int columns, int rows) { + this.rows = rows; + this.columns = new ArrayList<>(); + + for (int i = 0; i < columns; ++i) { + this.columns.add(new ArrayList<>()); + } + } + + public int getRows() { + return rows; + } + + public int getColumns() { + return columns.size(); + } + + public Piece getCell(int x, int y) { + assert(x >= 0 && x < getColumns()); + assert(y >= 0 && y < getRows()); + + List column = columns.get(x); + + if (column.size() > y) { + return column.get(y); + } else { + return null; + } + } + + public boolean move(int x, Piece player) { + assert(x >= 0 && x < getColumns()); + + List column = columns.get(x); + + if (column.size() >= this.rows) { + throw new IllegalArgumentException("That column is full"); + } + + column.add(player); + + return checkWin(x, column.size() - 1, player); + } + + private boolean checkWin(int x, int y, Piece player) { + // Vertical line + if (checkLine(x, y, 0, -1, player)) { + return true; + } + + for (int offset = 0; offset < 4; ++offset) { + // Horizontal line + if (checkLine(x - 3 + offset, y, 1, 0, player)) { + return true; + } + + // Leading diagonal + if (checkLine(x - 3 + offset, y + 3 - offset, 1, -1, player)) { + return true; + } + + // Trailing diagonal + if (checkLine(x - 3 + offset, y - 3 + offset, 1, 1, player)) { + return true; + } + } + + return false; + } + + private boolean checkLine(int x1, int y1, int xDiff, int yDiff, Piece player) { + for (int i = 0; i < 4; ++i) { + int x = x1 + (xDiff * i); + int y = y1 + (yDiff * i); + + if (x < 0 || x > columns.size() - 1) { + return false; + } + + if (y < 0 || y > rows - 1) { + return false; + } + + if (player != getCell(x, y)) { + return false; + } + } + + return true; + } + + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + + for (int y = getRows() - 1; y >= 0; --y) { + for (int x = 0; x < getColumns(); ++x) { + Piece piece = getCell(x, y); + + result.append("|"); + if (piece == null) { + result.append(" "); + } else if (piece == Piece.PLAYER_1) { + result.append("X"); + } else if (piece == Piece.PLAYER_2) { + result.append("O"); + } + } + + result.append("|\n"); + for (int i = 0; i < getColumns(); ++i) { + result.append("+-"); + } + result.append("+\n"); + } + + return result.toString(); + } +} diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameUnitTest.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameUnitTest.java new file mode 100644 index 0000000000..f340644950 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.algorithms.connect4; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class GameUnitTest { + @Test + public void blankGame() { + GameBoard gameBoard = new GameBoard(8, 6); + + System.out.println(gameBoard); + } + + @Test + public void playedGame() { + GameBoard gameBoard = new GameBoard(8, 6); + + assertFalse(gameBoard.move(3, Piece.PLAYER_1)); + assertFalse(gameBoard.move(2, Piece.PLAYER_2)); + + assertFalse(gameBoard.move(4, Piece.PLAYER_1)); + assertFalse(gameBoard.move(3, Piece.PLAYER_2)); + + assertFalse(gameBoard.move(5, Piece.PLAYER_1)); + assertFalse(gameBoard.move(6, Piece.PLAYER_2)); + + assertFalse(gameBoard.move(5, Piece.PLAYER_1)); + assertFalse(gameBoard.move(4, Piece.PLAYER_2)); + + assertFalse(gameBoard.move(5, Piece.PLAYER_1)); + assertFalse(gameBoard.move(5, Piece.PLAYER_2)); + + assertFalse(gameBoard.move(6, Piece.PLAYER_1)); + assertTrue(gameBoard.move(4, Piece.PLAYER_2)); + + System.out.println(gameBoard); + } +} diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/Piece.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/Piece.java new file mode 100644 index 0000000000..5a8724c09b --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/Piece.java @@ -0,0 +1,6 @@ +package com.baeldung.algorithms.connect4; + +public enum Piece { + PLAYER_1, + PLAYER_2 +} diff --git a/aws-modules/aws-miscellaneous/README.md b/aws-modules/aws-miscellaneous/README.md index 5be8e6a3f2..104c8719df 100644 --- a/aws-modules/aws-miscellaneous/README.md +++ b/aws-modules/aws-miscellaneous/README.md @@ -5,6 +5,5 @@ This module contains articles about various Amazon Web Services (AWS) such as EC ### Relevant articles - [Managing EC2 Instances in Java](https://www.baeldung.com/ec2-java) -- [Integration Testing with a Local DynamoDB Instance](https://www.baeldung.com/dynamodb-local-integration-tests) - [Managing Amazon SQS Queues in Java](https://www.baeldung.com/aws-queues-java) - [Guide to AWS Aurora RDS with Java](https://www.baeldung.com/aws-aurora-rds-java) diff --git a/core-java-modules/core-java-8/README.md b/core-java-modules/core-java-8/README.md index 6061f3318d..0921c1538a 100644 --- a/core-java-modules/core-java-8/README.md +++ b/core-java-modules/core-java-8/README.md @@ -11,5 +11,5 @@ This module contains articles about Java 8 core features - [Finding Min/Max in an Array with Java](https://www.baeldung.com/java-array-min-max) - [Internationalization and Localization in Java 8](https://www.baeldung.com/java-8-localization) - [Generalized Target-Type Inference in Java](https://www.baeldung.com/java-generalized-target-type-inference) -- [Monads in Java](https://www.baeldung.com/java-monads) +- [Monads in Java – Optional](https://www.baeldung.com/java-monads) - [[More -->]](/core-java-modules/core-java-8-2) diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/CustomSpliterator.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/CustomSpliterator.java new file mode 100644 index 0000000000..2f806cccda --- /dev/null +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/CustomSpliterator.java @@ -0,0 +1,48 @@ +package com.baeldung.spliterator; + +import java.util.List; +import java.util.Spliterator; +import java.util.function.Consumer; + +public class CustomSpliterator implements Spliterator { + private final List elements; + private int currentIndex; + + public CustomSpliterator(List elements) { + this.elements = elements; + this.currentIndex = 0; + } + + @Override + public boolean tryAdvance(Consumer action) { + if (currentIndex < elements.size()) { + action.accept(elements.get(currentIndex)); + currentIndex++; + return true; + } + return false; + } + + @Override + public Spliterator trySplit() { + int currentSize = elements.size() - currentIndex; + if (currentSize < 2) { + return null; + } + + int splitIndex = currentIndex + currentSize / 2; + CustomSpliterator newSpliterator = new CustomSpliterator(elements.subList(currentIndex, splitIndex)); + currentIndex = splitIndex; + return newSpliterator; + } + + @Override + public long estimateSize() { + return elements.size() - currentIndex; + } + + @Override + public int characteristics() { + return ORDERED | SIZED | SUBSIZED | NONNULL; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Executor.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Executor.java deleted file mode 100644 index 3dc2fa06bb..0000000000 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Executor.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.spliterator; - -import java.util.stream.Stream; - -public class Executor { - - public static int countAutors(Stream stream) { - RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true), - RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine); - return wordCounter.getCounter(); - } -} \ No newline at end of file diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorCounter.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorCounter.java deleted file mode 100644 index 8800eac55b..0000000000 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorCounter.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.spliterator; - -public class RelatedAuthorCounter { - private final int counter; - private final boolean isRelated; - - public RelatedAuthorCounter(int counter, boolean isRelated) { - this.counter = counter; - this.isRelated = isRelated; - } - - public RelatedAuthorCounter accumulate(Author author) { - if (author.getRelatedArticleId() == 0) { - return isRelated ? this : new RelatedAuthorCounter(counter, true); - } else { - return isRelated ? new RelatedAuthorCounter(counter + 1, false) : this; - } - } - - public RelatedAuthorCounter combine(RelatedAuthorCounter RelatedAuthorCounter) { - return new RelatedAuthorCounter(counter + RelatedAuthorCounter.counter, RelatedAuthorCounter.isRelated); - } - - public int getCounter() { - return counter; - } -} diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorSpliterator.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorSpliterator.java deleted file mode 100644 index 93c83b8127..0000000000 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorSpliterator.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.spliterator; - -import java.util.List; -import java.util.Spliterator; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; - -public class RelatedAuthorSpliterator implements Spliterator { - private final List list; - AtomicInteger current = new AtomicInteger(); - - public RelatedAuthorSpliterator(List list) { - this.list = list; - } - - @Override - public boolean tryAdvance(Consumer action) { - - action.accept(list.get(current.getAndIncrement())); - return current.get() < list.size(); - } - - @Override - public Spliterator trySplit() { - int currentSize = list.size() - current.get(); - if (currentSize < 10) { - return null; - } - for (int splitPos = currentSize / 2 + current.intValue(); splitPos < list.size(); splitPos++) { - if (list.get(splitPos).getRelatedArticleId() == 0) { - Spliterator spliterator = new RelatedAuthorSpliterator(list.subList(current.get(), splitPos)); - current.set(splitPos); - return spliterator; - } - } - return null; - } - - @Override - public long estimateSize() { - return list.size() - current.get(); - } - - @Override - public int characteristics() { - return CONCURRENT; - } - -} diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/spliterator/ExecutorUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/spliterator/ExecutorUnitTest.java index 4628f95481..30760ddf6f 100644 --- a/core-java-modules/core-java-8/src/test/java/com/baeldung/spliterator/ExecutorUnitTest.java +++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/spliterator/ExecutorUnitTest.java @@ -6,10 +6,10 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Spliterator; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; -import java.util.stream.StreamSupport; - import org.junit.Before; import org.junit.Test; @@ -18,22 +18,50 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class ExecutorUnitTest { Article article; - Stream stream; - Spliterator spliterator; @Before public void init() { article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0); - - spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors()); } @Test - public void givenAstreamOfAuthors_whenProcessedInParallelWithCustomSpliterator_coubtProducessRightOutput() { - Stream stream2 = StreamSupport.stream(spliterator, true); - assertThat(Executor.countAutors(stream2.parallel())).isEqualTo(9); + public void givenAStreamOfIntegers_whenProcessedSequentialCustomSpliterator_countProducesRightOutput() { + List numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + numbers.add(3); + numbers.add(4); + numbers.add(5); + + CustomSpliterator customSpliterator = new CustomSpliterator(numbers); + + AtomicInteger sum = new AtomicInteger(); + + customSpliterator.forEachRemaining(sum::addAndGet); + assertThat(sum.get()).isEqualTo(15); + } + + @Test + public void givenAStreamOfIntegers_whenProcessedInParallelWithCustomSpliterator_countProducesRightOutput() { + List numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + numbers.add(3); + numbers.add(4); + numbers.add(5); + + CustomSpliterator customSpliterator = new CustomSpliterator(numbers); + + // Create a ForkJoinPool for parallel processing + ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); + + AtomicInteger sum = new AtomicInteger(0); + + // Process elements in parallel using parallelStream + forkJoinPool.submit(() -> customSpliterator.forEachRemaining(sum::addAndGet)).join(); + assertThat(sum.get()).isEqualTo(15); } @Test @@ -43,9 +71,7 @@ public class ExecutorUnitTest { .collect(Collectors.toList()); Spliterator
spliterator = articles.spliterator(); - while (spliterator.tryAdvance(article -> article.setName(article.getName() - .concat("- published by Baeldung")))) - ; + while(spliterator.tryAdvance(article -> article.setName(article.getName().concat("- published by Baeldung")))); articles.forEach(article -> assertThat(article.getName()).isEqualTo("Java- published by Baeldung")); } diff --git a/core-java-modules/core-java-arrays-operations-advanced/pom.xml b/core-java-modules/core-java-arrays-operations-advanced/pom.xml index cbcd6ae440..52787cc0c9 100644 --- a/core-java-modules/core-java-arrays-operations-advanced/pom.xml +++ b/core-java-modules/core-java-arrays-operations-advanced/pom.xml @@ -57,5 +57,9 @@ + + + 11 + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ArraysCompareUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ArraysCompareUnitTest.java new file mode 100644 index 0000000000..828560d71c --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ArraysCompareUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.arraycompare; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; + +import org.junit.jupiter.api.Test; + +class ArraysCompareUnitTest { + + @Test + void givenSameContents_whenCompare_thenCorrect() { + String[] array1 = new String[] { "A", "B", "C" }; + String[] array2 = new String[] { "A", "B", "C" }; + + assertThat(Arrays.compare(array1, array2)).isEqualTo(0); + } + + @Test + void givenDifferentContents_whenCompare_thenDifferent() { + String[] array1 = new String[] { "A", "B", "C" }; + String[] array2 = new String[] { "A", "C", "B", "D" }; + + assertThat(Arrays.compare(array1, array2)).isLessThan(0); + assertThat(Arrays.compare(array2, array1)).isGreaterThan(0); + assertThat(Arrays.compare(array1, null)).isGreaterThan(0); + } + +} diff --git a/core-java-modules/core-java-arrays-operations-basic-2/README.md b/core-java-modules/core-java-arrays-operations-basic-2/README.md new file mode 100644 index 0000000000..07eb82ec68 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-basic-2/README.md @@ -0,0 +1,6 @@ +## Core Java Arrays - Basic Operations + +This module contains articles about Java array fundamentals. They assume no previous background knowledge on working with arrays. + +### Relevant Articles: +- [Arrays mismatch() Method in Java](https://www.baeldung.com/java-arrays-mismatch) diff --git a/core-java-modules/core-java-arrays-operations-basic-2/pom.xml b/core-java-modules/core-java-arrays-operations-basic-2/pom.xml new file mode 100644 index 0000000000..7257a39462 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-basic-2/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + core-java-arrays-operations-basic-2 + core-java-arrays-operations-basic-2 + jar + + + core-java-modules + com.baeldung.core-java-modules + 0.0.1-SNAPSHOT + + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-operations-basic-2/src/test/java/com/baeldung/array/mismatch/ArrayMismatchUnitTest.java b/core-java-modules/core-java-arrays-operations-basic-2/src/test/java/com/baeldung/array/mismatch/ArrayMismatchUnitTest.java new file mode 100644 index 0000000000..464221efd0 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-basic-2/src/test/java/com/baeldung/array/mismatch/ArrayMismatchUnitTest.java @@ -0,0 +1,269 @@ +package com.baeldung.array.mismatch; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.Arrays; +import java.util.Comparator; + +import org.junit.jupiter.api.Test; + +class ArrayMismatchUnitTest { + + @Test + void givenTwoArraysWithACommonPrefix_whenMismatch_thenIndexOfFirstMismatch() { + int[] firstArray = {1, 2, 3, 4, 5}; + int[] secondArray = {1, 2, 3, 5, 8}; + assertEquals(3, Arrays.mismatch(firstArray, secondArray)); + } + + @Test + void givenTwoIdenticalArrays_whenMismatch_thenMinusOne() { + int[] firstArray = {1, 2, 3, 4, 5}; + int[] secondArray = {1, 2, 3, 4, 5}; + assertEquals(-1, Arrays.mismatch(firstArray, secondArray)); + } + + @Test + void givenFirstArrayIsAPrefixOfTheSecond_whenMismatch_thenFirstArrayLength() { + int[] firstArray = {1, 2, 3, 4, 5}; + int[] secondArray = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + assertEquals(firstArray.length, Arrays.mismatch(firstArray, secondArray)); + } + + @Test + void givenNoCommonPrefix_whenMismatch_thenZero() { + int[] firstArray = {1, 2, 3, 4, 5}; + int[] secondArray = {9, 8, 7}; + assertEquals(0, Arrays.mismatch(firstArray, secondArray)); + } + + @Test + void givenAtLeastANullArray_whenMismatch_thenThrowsNullPointerException() { + int[] firstArray = null; + int[] secondArray = {1, 2, 3, 4, 5}; + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, secondArray)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, firstArray)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, firstArray)); + } + + @Test + void givenExactlyOneAnEmptyArray_whenMismatch_thenZero() { + int[] firstArray = {}; + int[] secondArray = {1, 2, 3}; + assertEquals(0, Arrays.mismatch(firstArray, secondArray)); + assertEquals(0, Arrays.mismatch(secondArray, firstArray)); + } + + @Test + void givenTwoEmptyArrays_whenMismatch_thenMinusOne() { + assertEquals(-1, Arrays.mismatch(new int[] {}, new int[] {})); + } + + @Test + void givenTwoSubArraysWithACommonPrefix_whenMismatch_thenIndexOfFirstMismatch() { + int[] firstArray = {1, 2, 3, 4, 5}; + int[] secondArray = {0, 1, 2, 3, 5, 8}; + assertEquals(3, Arrays.mismatch(firstArray, 0, 4, secondArray, 1, 6)); + } + + @Test + void givenTwoIdenticalSubArrays_whenMismatch_thenMinusOne() { + int[] firstArray = {0, 0, 1, 2}; + int[] secondArray = {0, 1, 2, 3, 4}; + assertEquals(-1, Arrays.mismatch(firstArray, 2, 4, secondArray, 1, 3)); + } + + @Test + void givenFirstSubArrayIsAPrefixOfTheSecond_whenMismatch_thenFirstArrayLength() { + int[] firstArray = {2, 3, 4, 5, 4, 3, 2}; + int[] secondArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + assertEquals(4, Arrays.mismatch(firstArray, 0, 4, secondArray, 2, 9)); + } + + @Test + void givenNoCommonPrefixForSubArrays_whenMismatch_thenZero() { + int[] firstArray = {0, 0, 0, 0, 0}; + int[] secondArray = {9, 8, 7, 6, 5}; + assertEquals(0, Arrays.mismatch(firstArray, 1, 2, secondArray, 1, 2)); + } + + @Test + void givenAtLeastANullSubArray_whenMismatch_thenThrowsNullPointerException() { + int[] firstArray = null; + int[] secondArray = {1, 2, 3, 4, 5}; + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, 0, 1, secondArray, 0, 1)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, 0, 1, firstArray, 0, 1)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, 0, 1, firstArray, 0, 1)); + } + + @Test + void givenExactlyOneEmptySubArray_whenMismatch_thenZero() { + int[] firstArray = {1}; + int[] secondArray = {1, 2, 3}; + assertEquals(0, Arrays.mismatch(firstArray, 0, 0, secondArray, 0, 2)); + assertEquals(0, Arrays.mismatch(firstArray, 0, 1, secondArray, 2, 2)); + } + + @Test + void givenTwoEmptySubArrays_whenMismatch_thenMinusOne() { + int[] firstArray = {1}; + int[] secondArray = {1, 2, 3}; + assertEquals(-1, Arrays.mismatch(firstArray, 0, 0, secondArray, 2, 2)); + } + + @Test + void givenToIndexGreaterThanFromIndex_whenMismatch_thenThrowsIllegalArgumentException() { + int[] firstArray = {2, 3, 4, 5, 4, 3, 2}; + int[] secondArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + assertThrows(IllegalArgumentException.class, () -> Arrays.mismatch(firstArray, 4, 2, secondArray, 0, 6)); + assertThrows(IllegalArgumentException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, 6, 0)); + } + + @Test + void givenIllegalIndexes_whenMismatch_thenThrowsArrayIndexOutOfBoundsException() { + int[] firstArray = {2, 3, 4, 5, 4, 3, 2}; + int[] secondArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, -1, 2, secondArray, 0, 6)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 0, 8, secondArray, 0, 6)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, -5, 0)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, 11, 12)); + } + + @Test + void givenTwoStringArraysAndAComparator_whenMismatch_thenIndexOfFirstMismatch() { + String[] firstArray = {"one", "two", "three"}; + String[] secondArray = {"ONE", "TWO", "FOUR"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(2, Arrays.mismatch(firstArray, secondArray, comparator)); + } + + @Test + void givenTwoIdenticalStringArraysForTheComparator_whenMismatch_thenMinusOne() { + String[] firstArray = {"one", "two", "three"}; + String[] secondArray = {"ONE", "TWO", "THREE"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(-1, Arrays.mismatch(firstArray, secondArray, comparator)); + } + + @Test + void givenFirstStringArrayIsAPrefixOfTheSecondForTheComparator_whenMismatch_thenFirstArrayLength() { + String[] firstArray = {"one", "two", "three"}; + String[] secondArray = {"ONE", "TWO", "THREE", "FOUR", "FIVE"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(firstArray.length, Arrays.mismatch(firstArray, secondArray, comparator)); + } + + @Test + void givenNoCommonPrefixForTheComparator_whenMismatch_thenZero() { + String[] firstArray = {"one", "two", "three"}; + String[] secondArray = {"six", "seven", "eight"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(0, Arrays.mismatch(firstArray, secondArray, comparator)); + } + + @Test + void givenAtLeastANullArrayOrNullComparator_whenMismatch_thenThrowsNullPointerException() { + String[] firstArray = null; + String[] secondArray = {"one"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, secondArray, comparator)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, firstArray, comparator)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, secondArray, null)); + } + + @Test + void givenExactlyOneAnEmptyArrayAndAComparator_whenMismatch_thenZero() { + String[] firstArray = {}; + String[] secondArray = {"one"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(0, Arrays.mismatch(firstArray, secondArray, comparator)); + assertEquals(0, Arrays.mismatch(secondArray, firstArray, comparator)); + } + + @Test + void givenTwoEmptyStringArraysForTheComparator_whenMismatch_thenMinusOne() { + assertEquals(-1, Arrays.mismatch(new String[] {}, new String[] {}, String.CASE_INSENSITIVE_ORDER)); + } + + @Test + void givenTwoStringSubarraysAndAComparator_whenMismatch_thenIndexOfFirstMismatch() { + String[] firstArray = {"one", "two", "three", "four"}; + String[] secondArray = {"ZERO", "ONE", "TWO", "FOUR", "EIGHT", "SIXTEEN"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(2, Arrays.mismatch(firstArray, 0, 4, secondArray, 1, 3, comparator)); + } + + @Test + void givenTwoIdenticalStringSubArraysForTheComparator_whenMismatch_thenMinusOne() { + String[] firstArray = {"zero", "zero", "one", "two"}; + String[] secondArray = {"zero", "one", "two", "three", "four"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(-1, Arrays.mismatch(firstArray, 2, 4, secondArray, 1, 3, comparator)); + } + + @Test + void givenFirstSubArrayIsAPrefixOfTheSecondForTheComparator_whenMismatch_thenFirstArrayLength() { + String[] firstArray = {"two", "three", "four", "five", "four", "three", "two"}; + String[] secondArray = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "EIGHT", "NINE", "TEN"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(4, Arrays.mismatch(firstArray, 0, 4, secondArray, 2, 9, comparator)); + } + + @Test + void givenNoCommonPrefixForSubArraysForTheComparator_whenMismatch_thenZero() { + String[] firstArray = {"zero", "one"}; + String[] secondArray = {"TEN", "ELEVEN", "TWELVE"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(0, Arrays.mismatch(firstArray, 1, 2, secondArray, 1, 2, comparator)); + } + + @Test + void givenAtLeastANullSubArrayOrNullComparator_whenMismatch_thenThrowsNullPointerException() { + String[] firstArray = null; + String[] secondArray = {"ONE", "TWO", "THREE", "FOUR", "FIVE"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, 0, 1, secondArray, 0, 1, comparator)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, 0, 1, firstArray, 0, 1, comparator)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, 0, 1, firstArray, 0, 1, comparator)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, 0, 1, secondArray, 0, 1, null)); + } + + @Test + void givenExactlyOneEmptySubArrayAndAComparator_whenMismatch_thenZero() { + String[] firstArray = {"one"}; + String[] secondArray = {"ONE", "TWO", "THREE"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(0, Arrays.mismatch(firstArray, 0, 0, secondArray, 0, 2, comparator)); + assertEquals(0, Arrays.mismatch(firstArray, 0, 1, secondArray, 2, 2, comparator)); + } + + @Test + void givenTwoEmptySubArraysAndAComparator_whenMismatch_thenMinusOne() { + String[] firstArray = {"one"}; + String[] secondArray = {"ONE", "TWO", "THREE"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(-1, Arrays.mismatch(firstArray, 0, 0, secondArray, 2, 2, comparator)); + } + + @Test + void givenToIndexGreaterThanFromIndexAndAComparator_whenMismatch_thenThrowsIllegalArgumentException() { + String[] firstArray = {"two", "three", "four", "five", "four", "three", "two"}; + String[] secondArray = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "EIGHT", "NINE", "TEN"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertThrows(IllegalArgumentException.class, () -> Arrays.mismatch(firstArray, 4, 2, secondArray, 0, 6, comparator)); + assertThrows(IllegalArgumentException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, 6, 0, comparator)); + } + + @Test + void givenIllegalIndexesAndAComparator_whenMismatch_thenThrowsArrayIndexOutOfBoundsException() { + String[] firstArray = {"two", "three", "four", "five", "four", "three", "two"}; + String[] secondArray = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "EIGHT", "NINE", "TEN"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, -1, 2, secondArray, 0, 6, comparator)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 0, 8, secondArray, 0, 6, comparator)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, -5, 0, comparator)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, 11, 12, comparator)); + } + +} diff --git a/core-java-modules/core-java-collections-5/README.md b/core-java-modules/core-java-collections-5/README.md index e478d87ad0..1939e5ca3f 100644 --- a/core-java-modules/core-java-collections-5/README.md +++ b/core-java-modules/core-java-collections-5/README.md @@ -7,4 +7,5 @@ - [Creating Custom Iterator in Java](https://www.baeldung.com/java-creating-custom-iterator) - [Difference Between Arrays.sort() and Collections.sort()](https://www.baeldung.com/java-arrays-collections-sort-methods) - [Skipping the First Iteration in Java](https://www.baeldung.com/java-skip-first-iteration) +- [Remove Elements From a Queue Using Loop](https://www.baeldung.com/java-remove-elements-queue) - More articles: [[<-- prev]](/core-java-modules/core-java-collections-4) diff --git a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java index 66cfade866..38fdc58099 100644 --- a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java +++ b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java @@ -12,7 +12,7 @@ public class RemoveQueueElementsUnitTest { @Test public void givenQueueWithEvenAndOddNumbers_whenRemovingEvenNumbers_thenOddNumbersRemain() { Queue queue = new LinkedList<>(); - Queue evenElementsQueue = new LinkedList<>(); + Queue oddElementsQueue = new LinkedList<>(); queue.add(1); queue.add(2); queue.add(3); @@ -22,14 +22,14 @@ public class RemoveQueueElementsUnitTest { while (queue.peek() != null) { int element = queue.remove(); if (element % 2 != 0) { - evenElementsQueue.add(element); + oddElementsQueue.add(element); } } - assertEquals(3, evenElementsQueue.size()); - assertTrue(evenElementsQueue.contains(1)); - assertTrue(evenElementsQueue.contains(3)); - assertTrue(evenElementsQueue.contains(5)); + assertEquals(3, oddElementsQueue.size()); + assertTrue(oddElementsQueue.contains(1)); + assertTrue(oddElementsQueue.contains(3)); + assertTrue(oddElementsQueue.contains(5)); } @Test diff --git a/core-java-modules/core-java-collections-maps-7/README.md b/core-java-modules/core-java-collections-maps-7/README.md index 2724df5695..5599187cd8 100644 --- a/core-java-modules/core-java-collections-maps-7/README.md +++ b/core-java-modules/core-java-collections-maps-7/README.md @@ -1,2 +1,3 @@ ## Relevant Articles - [Difference Between putIfAbsent() and computeIfAbsent() in Java’s Map](https://www.baeldung.com/java-map-putifabsent-computeifabsent) +- [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv) diff --git a/core-java-modules/core-java-concurrency-advanced-5/README.md b/core-java-modules/core-java-concurrency-advanced-5/README.md new file mode 100644 index 0000000000..ba845a7c4b --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-5/README.md @@ -0,0 +1,3 @@ + +### Relevant Articles: +- [Why wait() Requires Synchronization?](https://www.baeldung.com/java-wait-necessary-synchronization) diff --git a/core-java-modules/core-java-concurrency-basic-3/README.md b/core-java-modules/core-java-concurrency-basic-3/README.md index b9c66b279c..179a69495c 100644 --- a/core-java-modules/core-java-concurrency-basic-3/README.md +++ b/core-java-modules/core-java-concurrency-basic-3/README.md @@ -10,4 +10,5 @@ This module contains articles about basic Java concurrency. - [Returning a Value After Finishing Thread’s Job in Java](https://www.baeldung.com/java-return-value-after-thread-finish) - [CompletableFuture and ThreadPool in Java](https://www.baeldung.com/java-completablefuture-threadpool) - [CompletableFuture allOf().join() vs. CompletableFuture.join()](https://www.baeldung.com/java-completablefuture-allof-join) +- [Retry Logic with CompletableFuture](https://www.baeldung.com/java-completablefuture-retry-logic) - [[<-- Prev]](../core-java-concurrency-basic-2) diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java new file mode 100644 index 0000000000..a3df6b3624 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java @@ -0,0 +1,63 @@ +package com.baeldung.concurrent.completablefuture.retry; + +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; +import java.util.function.Supplier; + +public class RetryCompletableFuture { + public static CompletableFuture retryTask(Supplier supplier, int maxRetries) { + Supplier retryableSupplier = retryFunction(supplier, maxRetries); + return CompletableFuture.supplyAsync(retryableSupplier); + } + + static Supplier retryFunction(Supplier supplier, int maxRetries) { + return () -> { + int retries = 0; + while (retries < maxRetries) { + try { + return supplier.get(); + } catch (Exception e) { + retries++; + } + } + throw new IllegalStateException(String.format("Task failed after %s attempts", maxRetries)); + }; + } + + public static CompletableFuture retryUnsafe(Supplier supplier, int maxRetries) { + CompletableFuture cf = CompletableFuture.supplyAsync(supplier); + sleep(100l); + for (int i = 0; i < maxRetries; i++) { + cf = cf.exceptionally(__ -> supplier.get()); + } + return cf; + } + + public static CompletableFuture retryNesting(Supplier supplier, int maxRetries) { + CompletableFuture cf = CompletableFuture.supplyAsync(supplier); + sleep(100); + for (int i = 0; i < maxRetries; i++) { + cf = cf.thenApply(CompletableFuture::completedFuture) + .exceptionally(__ -> CompletableFuture.supplyAsync(supplier)) + .thenCompose(Function.identity()); + } + return cf; + } + + public static CompletableFuture retryExceptionallyAsync(Supplier supplier, int maxRetries) { + CompletableFuture cf = CompletableFuture.supplyAsync(supplier); + sleep(100); + for (int i = 0; i < maxRetries; i++) { + cf = cf.exceptionallyAsync(__ -> supplier.get()); + } + return cf; + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuturelist/Application.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuturelist/Application.java new file mode 100644 index 0000000000..be5d9e8479 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuturelist/Application.java @@ -0,0 +1,100 @@ +package com.baeldung.concurrent.completablefuturelist; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.stream.Collectors; + +public class Application { + + ScheduledExecutorService asyncOperationEmulation; + + Application initialize() { + asyncOperationEmulation = Executors.newScheduledThreadPool(10); + return this; + } + + CompletableFuture asyncOperation(String operationId) { + CompletableFuture cf = new CompletableFuture<>(); + asyncOperationEmulation.submit(() -> { + // The following lines simulate an exception happening on the 567th operation + // if (operationId.endsWith("567")) { + // cf.completeExceptionally(new Exception("Error on operation " + operationId)); + // return; + // } + try { + Thread.sleep(100); + cf.complete(operationId); + } catch (InterruptedException e) { + System.err.println("Thread interrupted error"); + cf.completeExceptionally(e); + } + }); + return cf; + } + + void startNaive() { + List> futures = new ArrayList<>(); + for (int i = 1; i <= 1000; i++) { + String operationId = "Naive-Operation-" + i; + futures.add(asyncOperation(operationId)); + } + + CompletableFuture> aggregate = CompletableFuture.completedFuture(new ArrayList<>()); + for (CompletableFuture future : futures) { + aggregate = aggregate.thenCompose(list -> { + try { + list.add(future.get()); + return CompletableFuture.completedFuture(list); + } catch (Exception e) { + final CompletableFuture> excFuture = new CompletableFuture<>(); + excFuture.completeExceptionally(e); + return excFuture; + } + }); + } + + try { + final List results = aggregate.join(); + System.out.println("Printing first 10 results"); + for (int i = 0; i < 10; i++) { + System.out.println("Finished " + results.get(i)); + } + } finally { + close(); + } + } + + void start() { + List> futures = new ArrayList<>(); + for (int i = 1; i <= 1000; i++) { + String operationId = "Operation-" + i; + futures.add(asyncOperation(operationId)); + } + CompletableFuture[] futuresArray = futures.toArray(new CompletableFuture[0]); + CompletableFuture> listFuture = CompletableFuture.allOf(futuresArray).thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList())); + try { + final List results = listFuture.join(); + System.out.println("Printing first 10 results"); + for (int i = 0; i < 10; i++) { + System.out.println("Finished " + results.get(i)); + } + } finally { + close(); + } + } + + void close() { + asyncOperationEmulation.shutdownNow(); + } + + public static void main(String[] args) { + new Application().initialize() + // Switch between .startNaive() and .start() to test both implementations + // .startNaive(); + .start(); + } + +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java new file mode 100644 index 0000000000..ea49f0fa08 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java @@ -0,0 +1,120 @@ +package com.baeldung.concurrent.completablefuture.retry; + +import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.retryExceptionallyAsync; +import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.retryNesting; +import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.retryTask; +import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.retryUnsafe; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class RetryCompletableFutureUnitTest { + private AtomicInteger retriesCounter = new AtomicInteger(0); + + @BeforeEach + void beforeEach() { + retriesCounter.set(0); + } + + @Test + void whenRetryingTask_thenReturnsCorrectlyAfterFourInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryTask(codeToRun, 10); + + assertThat(result.join()).isEqualTo(100); + assertThat(retriesCounter).hasValue(4); + } + + @Test + void whenRetryingTask_thenThrowsExceptionAfterThreeInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryTask(codeToRun, 3); + + assertThatThrownBy(result::join) + .isInstanceOf(CompletionException.class) + .hasMessageContaining("IllegalStateException: Task failed after 3 attempts"); + } + + @Test + void whenRetryingExceptionally_thenReturnsCorrectlyAfterFourInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryUnsafe(codeToRun, 10); + + assertThat(result.join()).isEqualTo(100); + assertThat(retriesCounter).hasValue(4); + } + + @Test + void whenRetryingExceptionally_thenThrowsExceptionAfterThreeInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryUnsafe(codeToRun, 3); + + assertThatThrownBy(result::join) + .isInstanceOf(CompletionException.class) + .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); + } + + @Test + void whenRetryingExceptionallyAsync_thenReturnsCorrectlyAfterFourInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryExceptionallyAsync(codeToRun, 10); + + assertThat(result.join()).isEqualTo(100); + assertThat(retriesCounter).hasValue(4); + } + + @Test + void whenRetryingExceptionallyAsync_thenThrowsExceptionAfterThreeInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryExceptionallyAsync(codeToRun, 3); + + assertThatThrownBy(result::join) + .isInstanceOf(CompletionException.class) + .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); + } + + @Test + void whenRetryingNesting_thenReturnsCorrectlyAfterFourInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryNesting(codeToRun, 10); + + assertThat(result.join()).isEqualTo(100); + assertThat(retriesCounter).hasValue(4); + } + + @Test + void whenRetryingNesting_thenThrowsExceptionAfterThreeInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryNesting(codeToRun, 3); + + assertThatThrownBy(result::join) + .isInstanceOf(CompletionException.class) + .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); + } + + int failFourTimesThenReturn(int returnValue) { + int retryNr = retriesCounter.get(); + System.out.println(String.format("invocation: %s, thread: %s", retryNr, Thread.currentThread().getName())); + if (retryNr < 4) { + retriesCounter.set(retryNr + 1); + throw new RuntimeException(String.format("task failed for %s time(s)", retryNr)); + } + return returnValue; + } + +} diff --git a/core-java-modules/core-java-concurrency-simple/README.md b/core-java-modules/core-java-concurrency-simple/README.md index 5cbfc67862..422d33e2c3 100644 --- a/core-java-modules/core-java-concurrency-simple/README.md +++ b/core-java-modules/core-java-concurrency-simple/README.md @@ -12,6 +12,7 @@ This module contains articles about Java Concurrency that are also part of an Eb - [Guide to the Volatile Keyword in Java](https://www.baeldung.com/java-volatile) - [A Guide to the Java ExecutorService](https://www.baeldung.com/java-executor-service-tutorial) - [Guide To CompletableFuture](https://www.baeldung.com/java-completablefuture) +- [How To Manage Timeout for CompletableFuture](https://www.baeldung.com/java-completablefuture-timeout) ### NOTE: diff --git a/core-java-modules/core-java-concurrency-simple/pom.xml b/core-java-modules/core-java-concurrency-simple/pom.xml index a16df4fc97..720ab5a0ed 100644 --- a/core-java-modules/core-java-concurrency-simple/pom.xml +++ b/core-java-modules/core-java-concurrency-simple/pom.xml @@ -12,6 +12,15 @@ 0.0.1-SNAPSHOT + + + org.wiremock + wiremock + 3.1.0 + test + + + core-java-concurrency-simple diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java new file mode 100644 index 0000000000..d04865026b --- /dev/null +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -0,0 +1,182 @@ +package com.baeldung.concurrent.completablefuture; + +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.concurrent.*; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class CompletableFutureTimeoutUnitTest { + private WireMockServer wireMockServer; + private ScheduledExecutorService executorService; + private static final int DEFAULT_TIMEOUT = 1000; //1 seconds + private static final String DEFAULT_PRODUCT = """ + { + "products": [ + { + "id": 2, + "title": "iPhone X", + "description": "SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...", + "price": 899, + "discountPercentage": 0.0, + "rating": 4.44, + "stock": 34, + "brand": "Apple", + "category": "smartphones" + }, + { + "id": 3, + "title": "Samsung Universe 9", + "description": "Samsung's new variant which goes beyond Galaxy to the Universe", + "price": 1249, + "discountPercentage": 0.0, + "rating": 4.09, + "stock": 36, + "brand": "Samsung", + "category": "smartphones" + } + ], + "total": 2 + }"""; + private static final String PRODUCT_OFFERS = """ + { + "products": [ + { + "id": 1, + "title": "iPhone 9", + "description": "An apple mobile which is nothing like apple", + "price": 549, + "discountPercentage": 12.96, + "rating": 4.69, + "stock": 94, + "brand": "Apple", + "category": "smartphones" + }, + { + "id": 2, + "title": "iPhone X", + "description": "SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...", + "price": 899, + "discountPercentage": 17.94, + "rating": 4.44, + "stock": 34, + "brand": "Apple", + "category": "smartphones" + }, + { + "id": 3, + "title": "Samsung Universe 9", + "description": "Samsung's new variant which goes beyond Galaxy to the Universe", + "price": 1249, + "discountPercentage": 15.46, + "rating": 4.09, + "stock": 36, + "brand": "Samsung", + "category": "smartphones" + }, + { + "id": 4, + "title": "OPPOF19", + "description": "OPPO F19 is officially announced on April 2021.", + "price": 280, + "discountPercentage": 17.91, + "rating": 4.3, + "stock": 123, + "brand": "OPPO", + "category": "smartphones" + }, + { + "id": 5, + "title": "Huawei P30", + "description": "Huawei’s re-badged P30 Pro New Edition was officially unveiled yesterday in Germany and now the device has made its way to the UK.", + "price": 499, + "discountPercentage": 10.58, + "rating": 4.09, + "stock": 32, + "brand": "Huawei", + "category": "smartphones" + } + ], + "total": 5 + }"""; + + @BeforeAll + void setUp() { + wireMockServer = new WireMockServer(8080); + wireMockServer.start(); + WireMock.configureFor("localhost", 8080); + + stubFor(get(urlEqualTo("/api/dummy")) + .willReturn(aResponse() + .withFixedDelay(5000) // must be > DEFAULT_TIMEOUT for a timeout to occur. + .withBody(PRODUCT_OFFERS))); + + executorService = Executors.newScheduledThreadPool(1); + } + + @AfterAll + void tearDown() { + executorService.shutdown(); + wireMockServer.stop(); + } + + private CompletableFuture fetchProductData() { + return CompletableFuture.supplyAsync(() -> { + try { + URL url = new URL("http://localhost:8080/api/dummy"); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + + try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String inputLine; + StringBuffer response = new StringBuffer(); + + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + + return response.toString(); + } finally { + connection.disconnect(); + } + } catch (IOException e) { + return ""; + } + }); + } + + + @Test + void whenorTimeout_thenGetThrow() { + CompletableFuture productDataFuture = fetchProductData(); + productDataFuture.orTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); + assertThrows(ExecutionException.class, productDataFuture::get); + } + + @Test + void whencompleteOnTimeout_thenReturnValue() throws ExecutionException, InterruptedException { + CompletableFuture productDataFuture = fetchProductData(); + productDataFuture.completeOnTimeout(DEFAULT_PRODUCT, DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); + assertEquals(DEFAULT_PRODUCT, productDataFuture.get()); + } + + @Test + void whencompleteExceptionally_thenGetThrow() { + CompletableFuture productDataFuture = fetchProductData(); + executorService.schedule(() -> productDataFuture + .completeExceptionally(new TimeoutException("Timeout occurred")), DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); + assertThrows(ExecutionException.class, productDataFuture::get); + } +} diff --git a/core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/firstdaymonth/FirstDayOfMonthUnitTest.java b/core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/firstdaymonth/FirstDayOfMonthUnitTest.java new file mode 100644 index 0000000000..9edc3e4a8d --- /dev/null +++ b/core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/firstdaymonth/FirstDayOfMonthUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.firstdaymonth; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.LocalDate; +import java.time.YearMonth; +import java.time.temporal.TemporalAdjusters; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import org.junit.jupiter.api.Test; + +public class FirstDayOfMonthUnitTest { + + @Test + void givenMonth_whenUsingCalendar_thenReturnFirstDay() { + Date currentDate = new GregorianCalendar(2023, Calendar.NOVEMBER, 23).getTime(); + Date expectedDate = new GregorianCalendar(2023, Calendar.NOVEMBER, 1).getTime(); + + Calendar cal = Calendar.getInstance(); + cal.setTime(currentDate); + cal.set(Calendar.DAY_OF_MONTH, 1); + + assertEquals(expectedDate, cal.getTime()); + } + + @Test + void givenMonth_whenUsingLocalDate_thenReturnFirstDay() { + LocalDate currentDate = LocalDate.of(2023, 9, 6); + LocalDate expectedDate = LocalDate.of(2023, 9, 1); + + assertEquals(expectedDate, currentDate.withDayOfMonth(1)); + } + + @Test + void givenMonth_whenUsingTemporalAdjusters_thenReturnFirstDay() { + LocalDate currentDate = LocalDate.of(2023, 7, 19); + LocalDate expectedDate = LocalDate.of(2023, 7, 1); + + assertEquals(expectedDate, currentDate.with(TemporalAdjusters.firstDayOfMonth())); + } + + @Test + void givenMonth_whenUsingYearMonth_thenReturnFirstDay() { + YearMonth currentDate = YearMonth.of(2023, 4); + LocalDate expectedDate = LocalDate.of(2023, 4, 1); + + assertEquals(expectedDate, currentDate.atDay(1)); + } + + @Test + void givenMonth_whenUsingJodaTime_thenReturnFirstDay() { + org.joda.time.LocalDate currentDate = org.joda.time.LocalDate.parse("2023-5-10"); + org.joda.time.LocalDate expectedDate = org.joda.time.LocalDate.parse("2023-5-1"); + + assertEquals(expectedDate, currentDate.dayOfMonth() + .withMinimumValue()); + } + +} diff --git a/core-java-modules/core-java-io-5/pom.xml b/core-java-modules/core-java-io-5/pom.xml index 11116b071c..5c987a82e1 100644 --- a/core-java-modules/core-java-io-5/pom.xml +++ b/core-java-modules/core-java-io-5/pom.xml @@ -35,6 +35,21 @@ simplemagic ${simplemagic.version} + + commons-io + commons-io + ${commons-io.version} + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + @@ -62,5 +77,6 @@ 0.1.5 6.2.1 1.17 + 1.37 \ No newline at end of file diff --git a/core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipBenchmark.java b/core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipBenchmark.java new file mode 100644 index 0000000000..30ec1522a2 --- /dev/null +++ b/core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipBenchmark.java @@ -0,0 +1,112 @@ +package com.baeldung.zip; + +import java.io.*; +import java.util.concurrent.TimeUnit; +import java.util.*; +import java.util.zip.*; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +@State(Scope.Benchmark) +@BenchmarkMode(Mode.AverageTime) +@Warmup(iterations = 1, time = 2, timeUnit = TimeUnit.SECONDS) +@Measurement(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Fork(value = 1) +public class ZipBenchmark { + + public static final int NUM_OF_FILES = 10; + public static final int DATA_SIZE = 204800; + + @State(Scope.Thread) + public static class SourceState { + + public File compressedFile; + + @Setup(Level.Trial) + public void setup() throws IOException { + ZipSampleFileStore sampleFileStore = new ZipSampleFileStore(NUM_OF_FILES, DATA_SIZE); + compressedFile = sampleFileStore.getFile(); + } + + @TearDown(Level.Trial) + public void cleanup() { + if (compressedFile.exists()) { + compressedFile.delete(); + } + } + } + + @Benchmark + public static void readAllEntriesByZipFile(SourceState sourceState, Blackhole blackhole) throws IOException { + + try (ZipFile zipFile = new ZipFile(sourceState.compressedFile)) { + Enumeration zipEntries = zipFile.entries(); + while (zipEntries.hasMoreElements()) { + ZipEntry zipEntry = zipEntries.nextElement(); + try (InputStream inputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry))) { + blackhole.consume(ZipSampleFileStore.getString(inputStream)); + } + } + } + } + + @Benchmark + public static void readAllEntriesByZipInputStream(SourceState sourceState, Blackhole blackhole) throws IOException { + + try ( + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceState.compressedFile)); + ZipInputStream zipInputStream = new ZipInputStream(bis) + ) { + ZipEntry entry; + while ((entry = zipInputStream.getNextEntry()) != null) { + blackhole.consume(ZipSampleFileStore.getString(zipInputStream)); + } + } + } + + @Benchmark + public static void readLastEntryByZipFile(SourceState sourceState, Blackhole blackhole) throws IOException { + + try (ZipFile zipFile = new ZipFile(sourceState.compressedFile)) { + ZipEntry zipEntry = zipFile.getEntry(getLastEntryName()); + try (InputStream inputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry))) { + blackhole.consume(ZipSampleFileStore.getString(inputStream)); + } + } + } + + @Benchmark + public static void readLastEntryByZipInputStream(SourceState sourceState, Blackhole blackhole) throws IOException { + + try ( + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceState.compressedFile)); + ZipInputStream zipInputStream = new ZipInputStream(bis) + ) { + ZipEntry entry; + while ((entry = zipInputStream.getNextEntry()) != null) { + if (Objects.equals(entry.getName(), getLastEntryName())){ + blackhole.consume(ZipSampleFileStore.getString(zipInputStream)); + } + } + } + } + + private static String getLastEntryName() { + return String.format(ZipSampleFileStore.ENTRY_NAME_PATTERN, NUM_OF_FILES); + } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(ZipBenchmark.class.getSimpleName()).threads(1) + .shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipSampleFileStore.java b/core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipSampleFileStore.java new file mode 100644 index 0000000000..389f082ff1 --- /dev/null +++ b/core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipSampleFileStore.java @@ -0,0 +1,70 @@ +package com.baeldung.zip; + +import java.io.*; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.apache.commons.io.IOUtils; + +public class ZipSampleFileStore { + + public static final String ENTRY_NAME_PATTERN = "str-data-%s.txt"; + private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; + + private final File file; + private final List dataList; + + public ZipSampleFileStore(int numOfFiles, int fileSize) throws IOException { + + dataList = new ArrayList<>(numOfFiles); + file = File.createTempFile("zip-sample", ""); + + try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file))) { + + for (int idx=0; idx<=numOfFiles; idx++) { + + byte[] data = createRandomStringInByte(fileSize); + dataList.add(new String(data, DEFAULT_ENCODING)); + + ZipEntry entry = new ZipEntry(String.format(ENTRY_NAME_PATTERN, idx)); + zos.putNextEntry(entry); + zos.write(data); + zos.closeEntry(); + } + } + } + + public static byte[] createRandomStringInByte(int size) { + Random random = new Random(); + byte[] data = new byte[size]; + for (int n = 0; n < data.length; n++) { + char randomChar; + int choice = random.nextInt(2); // 0 for uppercase, 1 for lowercase + if (choice == 0) { + randomChar = (char) ('A' + random.nextInt(26)); // 'A' to 'Z' + } else { + randomChar = (char) ('a' + random.nextInt(26)); // 'a' to 'z' + } + data[n] = (byte) randomChar; + } + return data; + } + + public File getFile() { + return file; + } + + public List getDataList() { + return dataList; + } + + public static String getString(InputStream inputStream) throws IOException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + IOUtils.copy(inputStream, byteArrayOutputStream); + return byteArrayOutputStream.toString(DEFAULT_ENCODING); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-5/src/test/java/com/baeldung/zip/ZipUnitTest.java b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/zip/ZipUnitTest.java new file mode 100644 index 0000000000..1d4d76dc41 --- /dev/null +++ b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/zip/ZipUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.zip; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.*; +import java.util.*; +import java.util.zip.*; + +import org.junit.*; + +public class ZipUnitTest { + + private static File compressedFile; + private static List dataList = new ArrayList<>(); + + @BeforeClass + public static void prepareData() throws IOException { + ZipSampleFileStore sampleFileStore = new ZipSampleFileStore(ZipBenchmark.NUM_OF_FILES, ZipBenchmark.DATA_SIZE); + compressedFile = sampleFileStore.getFile(); + dataList = sampleFileStore.getDataList(); + } + + @Test + public void whenCreateZipFile_thenCompressedSizeShouldBeLessThanOriginal() throws IOException { + byte[] data = ZipSampleFileStore.createRandomStringInByte(10240); + File file = File.createTempFile("zip-temp", ""); + + try ( + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); + ZipOutputStream zos = new ZipOutputStream(bos) + ) { + ZipEntry zipEntry = new ZipEntry("zip-entry.txt"); + zos.putNextEntry(zipEntry); + zos.write(data); + zos.closeEntry(); + + assertThat(file.length()).isLessThan(data.length); + } + finally { + file.delete(); + } + } + + @Test + public void whenReadAllEntriesViaZipFile_thenDataIsEqualtoTheSource() throws IOException { + + try (ZipFile zipFile = new ZipFile(compressedFile)) { + Enumeration entries = zipFile.entries(); + List entryList = Collections.list(entries); + + for (int idx=0; idx= 65 && codePoint <= 90) || - (codePoint >= 97 && codePoint <= 172) || + (codePoint >= 97 && codePoint <= 122) || (codePoint >= 48 && codePoint <= 57); } } diff --git a/core-java-modules/core-java-streams-5/README.md b/core-java-modules/core-java-streams-5/README.md index e7c58a0eb2..629d52f0a9 100644 --- a/core-java-modules/core-java-streams-5/README.md +++ b/core-java-modules/core-java-streams-5/README.md @@ -4,3 +4,4 @@ - [Aggregate Runtime Exceptions in Java Streams](https://www.baeldung.com/java-streams-aggregate-exceptions) - [Streams vs. Loops in Java](https://www.baeldung.com/java-streams-vs-loops) - [Partition a Stream in Java](https://www.baeldung.com/java-partition-stream) +- [Taking Every N-th Element from Finite and Infinite Streams in Java](https://www.baeldung.com/java-nth-element-finite-infinite-streams) diff --git a/core-java-modules/core-java-string-algorithms-3/README.md b/core-java-modules/core-java-string-algorithms-3/README.md index 3ef07129ed..abcac63ea4 100644 --- a/core-java-modules/core-java-string-algorithms-3/README.md +++ b/core-java-modules/core-java-string-algorithms-3/README.md @@ -13,3 +13,4 @@ This module contains articles about string-related algorithms. - [Find the Most Frequent Characters in a String](https://www.baeldung.com/java-string-find-most-frequent-characters) - [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring) - [Check if Letter Is Emoji With Java](https://www.baeldung.com/java-check-letter-emoji) +- [Wrapping a String After a Number of Characters Word-Wise](https://www.baeldung.com/java-wrap-string-number-characters-word-wise) diff --git a/core-java-modules/core-java-string-conversions-3/README.md b/core-java-modules/core-java-string-conversions-3/README.md index 4ec4771eea..ec169f71d2 100644 --- a/core-java-modules/core-java-string-conversions-3/README.md +++ b/core-java-modules/core-java-string-conversions-3/README.md @@ -3,3 +3,5 @@ - [Convert String to Int Using Encapsulation](https://www.baeldung.com/java-encapsulation-convert-string-to-int) - [HashMap with Multiple Values for the Same Key](https://www.baeldung.com/java-hashmap-multiple-values-per-key) - [Split Java String Into Key-Value Pairs](https://www.baeldung.com/java-split-string-map) +- [How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output) +- [How to Convert an Object to String](https://www.baeldung.com/java-object-string-representation) diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml index c6debc4f71..902e8f09b4 100644 --- a/core-java-modules/core-java-string-operations-2/pom.xml +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -54,6 +54,11 @@ commons-codec ${commons-codec.version} + + org.springframework + spring-core + ${spring-core.version} + @@ -95,6 +100,7 @@ 3.0.0 2.2.6 1.14 + 5.3.0 \ No newline at end of file diff --git a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java index d772c38341..9652e0e770 100644 --- a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java @@ -3,6 +3,7 @@ package com.baeldung.emptystrings; import com.google.common.base.Strings; import org.apache.commons.lang3.StringUtils; import org.junit.Test; +import org.springframework.util.ObjectUtils; import javax.validation.ConstraintViolation; import javax.validation.Validation; @@ -109,6 +110,24 @@ public class EmptyStringsUnitTest { assertFalse(Strings.isNullOrEmpty(blankString)); } + /* + * Spring Core ObjectUtils + */ + @Test + public void givenSomeEmptyString_thenObjectUtilsIsEmptyReturnsTrue() { + assertTrue(ObjectUtils.isEmpty(emptyString)); + } + + @Test + public void givenSomeNonEmptyString_thenObjectUtilsIsEmptyReturnsFalse() { + assertFalse(ObjectUtils.isEmpty(nonEmptyString)); + } + + @Test + public void givenSomeBlankString_thenObjectUtilsIsEmptyReturnsFalse() { + assertFalse(ObjectUtils.isEmpty(blankString)); + } + /* * Bean Validation */ diff --git a/core-java-modules/core-java-string-operations-6/README.md b/core-java-modules/core-java-string-operations-6/README.md index b4b78d1ad7..9d92552dd1 100644 --- a/core-java-modules/core-java-string-operations-6/README.md +++ b/core-java-modules/core-java-string-operations-6/README.md @@ -11,4 +11,4 @@ - [Check if a String Has All Unique Characters in Java](https://www.baeldung.com/java-check-string-all-unique-chars) - [Performance Comparison Between Different Java String Concatenation Methods](https://www.baeldung.com/java-string-concatenation-methods) - [Replacing Single Quote with \’ in Java String](https://www.baeldung.com/java-replacing-single-quote-string) - +- [Check if a String Contains a Number Value in Java](https://www.baeldung.com/java-string-number-presence) diff --git a/core-java-modules/core-java-string-operations-7/README.md b/core-java-modules/core-java-string-operations-7/README.md index 2dce44d217..6c4fab384b 100644 --- a/core-java-modules/core-java-string-operations-7/README.md +++ b/core-java-modules/core-java-string-operations-7/README.md @@ -1,2 +1,4 @@ ### Relevant Articles: +- [How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output) +- [Capitalize the First Letter of Each Word in a String](https://www.baeldung.com/java-string-initial-capital-letter-every-word) diff --git a/core-java-modules/core-java-string-operations-7/pom.xml b/core-java-modules/core-java-string-operations-7/pom.xml index 595f918fcd..a2c7036e34 100644 --- a/core-java-modules/core-java-string-operations-7/pom.xml +++ b/core-java-modules/core-java-string-operations-7/pom.xml @@ -1,72 +1,72 @@ - - - 4.0.0 - core-java-string-operations-7 - core-java-string-operations-7 - jar - - - com.baeldung.core-java-modules - core-java-modules - 0.0.1-SNAPSHOT - - - - - org.apache.commons - commons-lang3 - ${apache.commons.lang3.version} - - - org.apache.commons - commons-text - ${commons-text.version} - - - org.liquibase - liquibase-core - 4.9.1 - test - - - org.junit.jupiter - junit-jupiter - 5.8.1 - test - - - org.liquibase - liquibase-core - 4.9.1 - test - - - junit - junit - 4.13.2 - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - - - 11 - 11 - 3.12.0 - 1.10.0 - - + + + 4.0.0 + core-java-string-operations-7 + core-java-string-operations-7 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + org.apache.commons + commons-lang3 + ${apache.commons.lang3.version} + + + org.apache.commons + commons-text + ${commons-text.version} + + + org.liquibase + liquibase-core + 4.9.1 + test + + + org.junit.jupiter + junit-jupiter + 5.8.1 + test + + + org.liquibase + liquibase-core + 4.9.1 + test + + + junit + junit + 4.13.2 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 11 + 11 + 3.13.0 + 1.10.0 + + \ No newline at end of file diff --git a/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtils.java b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtils.java new file mode 100644 index 0000000000..cccc745499 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtils.java @@ -0,0 +1,40 @@ +package com.baeldung.capitalizefirstcharactereachword; + +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; + +class CapitalizeFirstCharacterEachWordUtils { + + static String usingCharacterToUpperCaseMethod(String input) { + if (input == null || input.isEmpty()) { + return null; + } + + return Arrays.stream(input.split("\\s+")) + .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1)) + .collect(Collectors.joining(" ")); + } + + static String usingStringToUpperCaseMethod(String input) { + if (input == null || input.isEmpty()) { + return null; + } + + return Arrays.stream(input.split("\\s+")) + .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1)) + .collect(Collectors.joining(" ")); + } + + static String usingStringUtilsClass(String input) { + if (input == null || input.isEmpty()) { + return null; + } + + return Arrays.stream(input.split("\\s+")) + .map(StringUtils::capitalize) + .collect(Collectors.joining(" ")); + } + +} diff --git a/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/strcontainsnumber/StrContainsNumberUtils.java b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/strcontainsnumber/StrContainsNumberUtils.java new file mode 100644 index 0000000000..a609b94cb8 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/strcontainsnumber/StrContainsNumberUtils.java @@ -0,0 +1,77 @@ +package com.baeldung.strcontainsnumber; + +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; + +import com.google.common.base.CharMatcher; + +public class StrContainsNumberUtils { + + static boolean checkUsingMatchesMethod(String input) { + if (input == null || input.isEmpty()) { + return false; + } + + return input.matches(".*\\d.*"); + } + + static boolean checkUsingPatternClass(String input) { + if (input == null || input.isEmpty()) { + return false; + } + + return Pattern.compile(".*\\d.*") + .matcher(input) + .matches(); + } + + static boolean checkUsingReplaceAllMethod(String input) { + if (input == null || input.isEmpty()) { + return false; + } + + String result = input.replaceAll("\\d", ""); + return result.length() != input.length(); + } + + static boolean checkUsingIsDigitMethod(String input) { + if (input == null || input.isEmpty()) { + return false; + } + + for (char c : input.toCharArray()) { + if (Character.isDigit(c)) { + return true; + } + } + + return false; + } + + static boolean checkUsingStreamApi(String input) { + if (input == null || input.isEmpty()) { + return false; + } + + return input.chars() + .anyMatch(Character::isDigit); + } + + static boolean checkUsingApacheCommonsLang(String input) { + String result = StringUtils.getDigits(input); + return result != null && !result.isEmpty(); + } + + static boolean checkUsingGuava(String input) { + if (input == null || input.isEmpty()) { + return false; + } + + String result = CharMatcher.forPredicate(Character::isDigit) + .retainFrom(input); + + return !result.isEmpty(); + } + +} diff --git a/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/unicode/UnicodeLetterChecker.java b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/unicode/UnicodeLetterChecker.java new file mode 100644 index 0000000000..8ac8671586 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/unicode/UnicodeLetterChecker.java @@ -0,0 +1,30 @@ +package com.baeldung.unicode; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.apache.commons.lang3.StringUtils; + +public class UnicodeLetterChecker { + public boolean characterClassCheck(String input) { + for (char c : input.toCharArray()) { + if (!Character.isLetter(c)) { + return false; + } + } + return true; + } + + public boolean regexCheck(String input) { + Pattern pattern = Pattern.compile("^\\p{L}+$"); + Matcher matcher = pattern.matcher(input); + return matcher.matches(); + } + + public boolean isAlphaCheck(String input) { + return StringUtils.isAlpha(input); + } + + public boolean StreamsCheck(String input) { + return input.codePoints().allMatch(Character::isLetter); + } +} diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtilsUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtilsUnitTest.java new file mode 100644 index 0000000000..27c7ddb4c4 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtilsUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.capitalizefirstcharactereachword; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.apache.commons.text.WordUtils; +import org.junit.jupiter.api.Test; + +class CapitalizeFirstCharacterEachWordUtilsUnitTest { + + @Test + void givenString_whenUsingCharacterToUpperCaseMethod_thenCapitalizeFirstCharacter() { + String input = "hello baeldung visitors"; + + assertEquals("Hello Baeldung Visitors", CapitalizeFirstCharacterEachWordUtils.usingCharacterToUpperCaseMethod(input)); + } + + @Test + void givenString_whenUsingSubstringMethod_thenCapitalizeFirstCharacter() { + String input = "Hi, my name is azhrioun"; + + assertEquals("Hi, My Name Is Azhrioun", CapitalizeFirstCharacterEachWordUtils.usingStringToUpperCaseMethod(input)); + } + + @Test + void givenString_whenUsingStringUtilsClass_thenCapitalizeFirstCharacter() { + String input = "life is short the world is wide"; + + assertEquals("Life Is Short The World Is Wide", CapitalizeFirstCharacterEachWordUtils.usingStringUtilsClass(input)); + } + + @Test + void givenString_whenUsingWordUtilsClass_thenCapitalizeFirstCharacter() { + String input = "smile sunshine is good for your teeth"; + + assertEquals("Smile Sunshine Is Good For Your Teeth", WordUtils.capitalizeFully(input)); + } + +} diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/strcontainsnumber/StrContainsNumberUtilsUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/strcontainsnumber/StrContainsNumberUtilsUnitTest.java new file mode 100644 index 0000000000..9a60a827e0 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/strcontainsnumber/StrContainsNumberUtilsUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.strcontainsnumber; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.junit.Test; + +public class StrContainsNumberUtilsUnitTest { + + private static final String INPUT_WITH_NUMBERS = "We hope 2024 will be great"; + private static final String INPUT_WITHOUT_NUMBERS = "Hello world"; + + @Test + public void givenInputString_whenUsingMatchesMethod_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingMatchesMethod(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingMatchesMethod(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingMatchesMethod("")); + assertFalse(StrContainsNumberUtils.checkUsingMatchesMethod(null)); + } + + @Test + public void givenInputString_whenUsingPatternClass_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingPatternClass(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingPatternClass(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingPatternClass("")); + assertFalse(StrContainsNumberUtils.checkUsingPatternClass(null)); + } + + @Test + public void givenInputString_whenUsingReplaceAllMethod_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingReplaceAllMethod(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingReplaceAllMethod(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingReplaceAllMethod("")); + assertFalse(StrContainsNumberUtils.checkUsingReplaceAllMethod(null)); + } + + @Test + public void givenInputString_whenUsingIsDigitMethod_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingIsDigitMethod(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingIsDigitMethod(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingIsDigitMethod("")); + assertFalse(StrContainsNumberUtils.checkUsingIsDigitMethod(null)); + } + + @Test + public void givenInputString_whenUsingStreamApi_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingStreamApi(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingStreamApi(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingStreamApi("")); + assertFalse(StrContainsNumberUtils.checkUsingStreamApi(null)); + } + + @Test + public void givenInputString_whenUsingApacheCommonsLang_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingApacheCommonsLang(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingApacheCommonsLang(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingApacheCommonsLang("")); + assertFalse(StrContainsNumberUtils.checkUsingApacheCommonsLang(null)); + } + + @Test + public void givenInputString_whenUsingGuava_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingGuava(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingGuava(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingGuava("")); + assertFalse(StrContainsNumberUtils.checkUsingGuava(null)); + } + +} diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/unicode/UnicodeLetterCheckerUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/unicode/UnicodeLetterCheckerUnitTest.java new file mode 100644 index 0000000000..a7ed9e5db9 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/unicode/UnicodeLetterCheckerUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.unicode; + +import org.junit.Test; +import static org.junit.Assert.assertTrue; + +public class UnicodeLetterCheckerUnitTest { + @Test + public void givenString_whenUsingIsLetter_thenReturnTrue() { + UnicodeLetterChecker checker = new UnicodeLetterChecker(); + + boolean isUnicodeLetter = checker.characterClassCheck("HelloWorld"); + assertTrue(isUnicodeLetter); + } + + @Test + public void givenString_whenUsingRegex_thenReturnTrue() { + UnicodeLetterChecker checker = new UnicodeLetterChecker(); + + boolean isUnicodeLetter = checker.regexCheck("HelloWorld"); + assertTrue(isUnicodeLetter); + } + + @Test + public void givenString_whenUsingIsAlpha_thenReturnTrue() { + UnicodeLetterChecker checker = new UnicodeLetterChecker(); + + boolean isUnicodeLetter = checker.isAlphaCheck("HelloWorld"); + assertTrue(isUnicodeLetter); + } + + @Test + public void givenString_whenUsingStreams_thenReturnTrue() { + UnicodeLetterChecker checker = new UnicodeLetterChecker(); + + boolean isUnicodeLetter = checker.StreamsCheck("HelloWorld"); + assertTrue(isUnicodeLetter); + } +} diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/Dummy.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/Dummy.java new file mode 100644 index 0000000000..27ebf8331f --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/Dummy.java @@ -0,0 +1,14 @@ +package com.baeldung.passstringbyreference; + +public class Dummy { + + String dummyString; + + public String getDummyString() { + return dummyString; + } + + public void setDummyString(String dummyString) { + this.dummyString = dummyString; + } +} diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/PassStringUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/PassStringUnitTest.java new file mode 100644 index 0000000000..e1b284a94e --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/PassStringUnitTest.java @@ -0,0 +1,85 @@ +package com.baeldung.passstringbyreference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.junit.jupiter.api.Test; + +class PassStringUnitTest { + + @Test + void givenAString_whenPassedToVoidMethod_thenStringIsNotModified() { + String s = "hello"; + concatStringWithNoReturn(s); + assertEquals("hello", s); + } + + void concatStringWithNoReturn(String input) { + input += " world"; + assertEquals("hello world", input); + } + + @Test + void givenAString_whenPassedToMethodAndReturnNewString_thenStringIsModified() { + String s = "hello"; + assertEquals("hello world", concatStringWithReturn(s)); + } + + String concatStringWithReturn(String input) { + return input + " world"; + } + + @Test + void givenAString_whenPassStringBuilderToVoidMethod_thenConcatNewStringOk() { + StringBuilder builder = new StringBuilder("hello"); + concatWithStringBuilder(builder); + + assertEquals("hello world", builder.toString()); + } + + void concatWithStringBuilder(StringBuilder input) { + input.append(" world"); + } + + @Test + void givenAString_whenPassStringBufferToVoidMethod_thenConcatNewStringOk() { + StringBuffer builder = new StringBuffer("hello"); + concatWithStringBuffer(builder); + + assertEquals("hello world", builder.toString()); + } + + void concatWithStringBuffer(StringBuffer input) { + input.append(" world"); + } + + @Test + void givenObjectWithStringField_whenSetDifferentValue_thenObjectIsModified() { + Dummy dummy = new Dummy(); + assertNull(dummy.getDummyString()); + modifyStringValueInInputObject(dummy, "hello world"); + assertEquals("hello world", dummy.getDummyString()); + } + + void modifyStringValueInInputObject(Dummy dummy, String dummyString) { + dummy.setDummyString(dummyString); + } + + @Test + void givenObjectWithStringField_whenSetDifferentValueWithStringBuilder_thenSetStringInNewObject() { + assertEquals("hello world", getDummy("hello", "world").getDummyString()); + } + + Dummy getDummy(String hello, String world) { + StringBuilder builder = new StringBuilder(); + + builder.append(hello) + .append(" ") + .append(world); + + Dummy dummy = new Dummy(); + dummy.setDummyString(builder.toString()); + + return dummy; + } +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 2152b90bcb..bf5b90cd32 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -73,6 +73,7 @@ core-java-arrays-multidimensional core-java-arrays-convert core-java-arrays-operations-basic + core-java-arrays-operations-basic-2 core-java-arrays-operations-advanced core-java-arrays-operations-advanced-2 core-java-booleans diff --git a/data-structures/src/main/java/com/baeldung/avltree/AVLTree.java b/data-structures/src/main/java/com/baeldung/avltree/AVLTree.java index ca0cfce7b4..117a35e028 100644 --- a/data-structures/src/main/java/com/baeldung/avltree/AVLTree.java +++ b/data-structures/src/main/java/com/baeldung/avltree/AVLTree.java @@ -42,17 +42,17 @@ public class AVLTree { return root == null ? -1 : root.height; } - private Node insert(Node node, int key) { - if (node == null) { + private Node insert(Node root, int key) { + if (root == null) { return new Node(key); - } else if (node.key > key) { - node.left = insert(node.left, key); - } else if (node.key < key) { - node.right = insert(node.right, key); + } else if (root.key > key) { + root.left = insert(root.left, key); + } else if (root.key < key) { + root.right = insert(root.right, key); } else { throw new RuntimeException("duplicate Key!"); } - return rebalance(node); + return rebalance(root); } private Node delete(Node node, int key) { diff --git a/gradle-modules/gradle/gradle-fat-jar/build.gradle b/gradle-modules/gradle/gradle-fat-jar/build.gradle index 6e2934194e..4c3d86d757 100644 --- a/gradle-modules/gradle/gradle-fat-jar/build.gradle +++ b/gradle-modules/gradle/gradle-fat-jar/build.gradle @@ -8,8 +8,10 @@ buildscript { } } -apply plugin: 'java' -apply plugin: 'com.github.johnrengelman.shadow' +plugins { + id 'com.github.johnrengelman.shadow' version '7.1.2' + id 'java' +} repositories { mavenCentral() @@ -30,7 +32,7 @@ task customFatJar(type: Jar) { manifest { attributes 'Main-Class': 'com.baeldung.fatjar.Application' } - baseName = 'all-in-one-jar' + archiveBaseName = 'all-in-one-jar' duplicatesStrategy = DuplicatesStrategy.EXCLUDE from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } } with jar diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml index d01c43dc90..3bf523bbfa 100644 --- a/jackson-simple/pom.xml +++ b/jackson-simple/pom.xml @@ -33,7 +33,7 @@ - 2.14.2 + 2.15.2 17 diff --git a/libraries-io/README.md b/libraries-io/README.md index 6cfe978d91..a9ca5df3d6 100644 --- a/libraries-io/README.md +++ b/libraries-io/README.md @@ -3,4 +3,4 @@ - [Transferring a File Through SFTP in Java](https://www.baeldung.com/java-file-sftp) - [How to Create Password-Protected Zip Files and Unzip Them in Java](https://www.baeldung.com/java-password-protected-zip-unzip) - +- [How to Create CSV File from POJO with Custom Column Headers and Positions](https://www.baeldung.com/java-create-csv-pojo-customize-columns) diff --git a/libraries-llms/pom.xml b/libraries-llms/pom.xml new file mode 100644 index 0000000000..3d5ed6830e --- /dev/null +++ b/libraries-llms/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + libraries-llms + libraries-llms + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + dev.langchain4j + langchain4j + ${langchain4j.version} + + + dev.langchain4j + langchain4j-embeddings + ${langchain4j.version} + + + dev.langchain4j + langchain4j-open-ai + ${langchain4j.version} + + + dev.langchain4j + langchain4j-embeddings-all-minilm-l6-v2 + ${langchain4j.version} + + + + + 0.23.0 + + + \ No newline at end of file diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java new file mode 100644 index 0000000000..39746ce810 --- /dev/null +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java @@ -0,0 +1,65 @@ +package com.baeldung.langchain; + +import static dev.langchain4j.data.document.FileSystemDocumentLoader.loadDocument; +import static java.time.Duration.ofSeconds; +import static org.junit.Assert.assertNotNull; + +import java.nio.file.Paths; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import dev.langchain4j.chain.ConversationalRetrievalChain; +import dev.langchain4j.data.document.Document; +import dev.langchain4j.data.document.splitter.DocumentSplitters; +import dev.langchain4j.data.segment.TextSegment; +import dev.langchain4j.memory.chat.MessageWindowChatMemory; +import dev.langchain4j.model.chat.ChatLanguageModel; +import dev.langchain4j.model.embedding.AllMiniLmL6V2EmbeddingModel; +import dev.langchain4j.model.embedding.EmbeddingModel; +import dev.langchain4j.model.input.PromptTemplate; +import dev.langchain4j.model.openai.OpenAiChatModel; +import dev.langchain4j.retriever.EmbeddingStoreRetriever; +import dev.langchain4j.store.embedding.EmbeddingStore; +import dev.langchain4j.store.embedding.EmbeddingStoreIngestor; +import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore; + +public class ChainWithDocumentLiveTest { + + private static final Logger logger = LoggerFactory.getLogger(ChainWithDocumentLiveTest.class); + + @Test + public void givenChainWithDocument_whenPrompted_thenValidResponse() { + EmbeddingModel embeddingModel = new AllMiniLmL6V2EmbeddingModel(); + + EmbeddingStore embeddingStore = new InMemoryEmbeddingStore<>(); + + EmbeddingStoreIngestor ingestor = EmbeddingStoreIngestor.builder() + .documentSplitter(DocumentSplitters.recursive(500, 0)) + .embeddingModel(embeddingModel) + .embeddingStore(embeddingStore) + .build(); + + Document document = loadDocument(Paths.get("src/test/resources/example-files/simpson's_adventures.txt")); + ingestor.ingest(document); + + ChatLanguageModel chatModel = OpenAiChatModel.builder() + .apiKey(Constants.OPENAI_API_KEY) + .timeout(ofSeconds(60)) + .build(); + + ConversationalRetrievalChain chain = ConversationalRetrievalChain.builder() + .chatLanguageModel(chatModel) + .retriever(EmbeddingStoreRetriever.from(embeddingStore, embeddingModel)) + .chatMemory(MessageWindowChatMemory.withMaxMessages(10)) + .promptTemplate(PromptTemplate.from("Answer the following question to the best of your ability: {{question}}\n\nBase your answer on the following information:\n{{information}}")) + .build(); + + String answer = chain.execute("Who is Simpson?"); + + logger.info(answer); + assertNotNull(answer); + } + +} diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java new file mode 100644 index 0000000000..41540f4888 --- /dev/null +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java @@ -0,0 +1,81 @@ +package com.baeldung.langchain; + +import static dev.langchain4j.data.document.FileSystemDocumentLoader.loadDocument; +import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; +import static java.time.Duration.ofSeconds; +import static java.util.stream.Collectors.joining; +import static org.junit.Assert.assertNotNull; + +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import dev.langchain4j.data.document.Document; +import dev.langchain4j.data.document.DocumentSplitter; +import dev.langchain4j.data.document.splitter.DocumentSplitters; +import dev.langchain4j.data.embedding.Embedding; +import dev.langchain4j.data.message.AiMessage; +import dev.langchain4j.data.segment.TextSegment; +import dev.langchain4j.model.chat.ChatLanguageModel; +import dev.langchain4j.model.embedding.AllMiniLmL6V2EmbeddingModel; +import dev.langchain4j.model.embedding.EmbeddingModel; +import dev.langchain4j.model.input.Prompt; +import dev.langchain4j.model.input.PromptTemplate; +import dev.langchain4j.model.openai.OpenAiChatModel; +import dev.langchain4j.model.openai.OpenAiTokenizer; +import dev.langchain4j.store.embedding.EmbeddingMatch; +import dev.langchain4j.store.embedding.EmbeddingStore; +import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore; + +public class ChatWithDocumentLiveTest { + + private static final Logger logger = LoggerFactory.getLogger(ChatWithDocumentLiveTest.class); + + @Test + public void givenDocument_whenPrompted_thenValidResponse() { + Document document = loadDocument(Paths.get("src/test/resources/example-files/simpson's_adventures.txt")); + DocumentSplitter splitter = DocumentSplitters.recursive(100, 0, new OpenAiTokenizer(GPT_3_5_TURBO)); + List segments = splitter.split(document); + + EmbeddingModel embeddingModel = new AllMiniLmL6V2EmbeddingModel(); + List embeddings = embeddingModel.embedAll(segments) + .content(); + EmbeddingStore embeddingStore = new InMemoryEmbeddingStore<>(); + embeddingStore.addAll(embeddings, segments); + + String question = "Who is Simpson?"; + Embedding questionEmbedding = embeddingModel.embed(question) + .content(); + int maxResults = 3; + double minScore = 0.7; + List> relevantEmbeddings = embeddingStore.findRelevant(questionEmbedding, maxResults, minScore); + + PromptTemplate promptTemplate = PromptTemplate.from("Answer the following question to the best of your ability:\n" + "\n" + "Question:\n" + "{{question}}\n" + "\n" + "Base your answer on the following information:\n" + "{{information}}"); + + String information = relevantEmbeddings.stream() + .map(match -> match.embedded() + .text()) + .collect(joining("\n\n")); + + Map variables = new HashMap<>(); + variables.put("question", question); + variables.put("information", information); + + Prompt prompt = promptTemplate.apply(variables); + ChatLanguageModel chatModel = OpenAiChatModel.builder() + .apiKey(Constants.OPENAI_API_KEY) + .timeout(ofSeconds(60)) + .build(); + AiMessage aiMessage = chatModel.generate(prompt.toUserMessage()) + .content(); + + logger.info(aiMessage.text()); + assertNotNull(aiMessage.text()); + } + +} diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java new file mode 100644 index 0000000000..3d265d3f3f --- /dev/null +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java @@ -0,0 +1,43 @@ +package com.baeldung.langchain; + +import static dev.langchain4j.data.message.UserMessage.userMessage; +import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import dev.langchain4j.data.message.AiMessage; +import dev.langchain4j.memory.ChatMemory; +import dev.langchain4j.memory.chat.TokenWindowChatMemory; +import dev.langchain4j.model.chat.ChatLanguageModel; +import dev.langchain4j.model.openai.OpenAiChatModel; +import dev.langchain4j.model.openai.OpenAiTokenizer; + +public class ChatWithMemoryLiveTest { + + private static final Logger logger = LoggerFactory.getLogger(ChatWithMemoryLiveTest.class); + + @Test + public void givenMemory_whenPrompted_thenValidResponse() { + ChatLanguageModel model = OpenAiChatModel.withApiKey(Constants.OPENAI_API_KEY); + ChatMemory chatMemory = TokenWindowChatMemory.withMaxTokens(300, new OpenAiTokenizer(GPT_3_5_TURBO)); + + chatMemory.add(userMessage("Hello, my name is Kumar")); + AiMessage answer = model.generate(chatMemory.messages()) + .content(); + logger.info(answer.text()); + chatMemory.add(answer); + assertNotNull(answer.text()); + + chatMemory.add(userMessage("What is my name?")); + AiMessage answerWithName = model.generate(chatMemory.messages()) + .content(); + logger.info(answerWithName.text()); + chatMemory.add(answerWithName); + assertThat(answerWithName.text()).contains("Kumar"); + } + +} diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java b/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java new file mode 100644 index 0000000000..380415bf9c --- /dev/null +++ b/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java @@ -0,0 +1,12 @@ +package com.baeldung.langchain; + +public class Constants { + + /** + * A limited access key for access to OpenAI language models can be generated by first + * registering for free at (https://platform.openai.com/signup) and then by navigating + * to "Create new secret key" page at (https://platform.openai.com/account/api-keys). + */ + public static String OPENAI_API_KEY = ""; + +} diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java new file mode 100644 index 0000000000..cd2ea642ed --- /dev/null +++ b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java @@ -0,0 +1,41 @@ +package com.baeldung.langchain; + +import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; +import static org.junit.Assert.assertNotNull; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import dev.langchain4j.model.chat.ChatLanguageModel; +import dev.langchain4j.model.input.Prompt; +import dev.langchain4j.model.input.PromptTemplate; +import dev.langchain4j.model.openai.OpenAiChatModel; + +public class PromptTemplatesLiveTest { + + private static final Logger logger = LoggerFactory.getLogger(PromptTemplatesLiveTest.class); + + @Test + public void givenPromptTemplate_whenSuppliedInput_thenValidResponse() { + PromptTemplate promptTemplate = PromptTemplate.from("Tell me a {{adjective}} joke about {{content}}.."); + Map variables = new HashMap<>(); + variables.put("adjective", "funny"); + variables.put("content", "humans"); + Prompt prompt = promptTemplate.apply(variables); + + ChatLanguageModel model = OpenAiChatModel.builder() + .apiKey(Constants.OPENAI_API_KEY) + .modelName(GPT_3_5_TURBO) + .temperature(0.3) + .build(); + + String response = model.generate(prompt.text()); + logger.info(response); + assertNotNull(response); + } + +} diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java new file mode 100644 index 0000000000..7ebfcba4df --- /dev/null +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java @@ -0,0 +1,49 @@ +package com.baeldung.langchain; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import dev.langchain4j.agent.tool.Tool; +import dev.langchain4j.memory.chat.MessageWindowChatMemory; +import dev.langchain4j.model.openai.OpenAiChatModel; +import dev.langchain4j.service.AiServices; + +public class ServiceWithToolsLiveTest { + + private static final Logger logger = LoggerFactory.getLogger(ServiceWithToolsLiveTest.class); + + static class Calculator { + @Tool("Calculates the length of a string") + int stringLength(String s) { + return s.length(); + } + + @Tool("Calculates the sum of two numbers") + int add(int a, int b) { + return a + b; + } + } + + interface Assistant { + String chat(String userMessage); + } + + @Test + public void givenServiceWithTools_whenPrompted_thenValidResponse() { + Assistant assistant = AiServices.builder(Assistant.class) + .chatLanguageModel(OpenAiChatModel.withApiKey(Constants.OPENAI_API_KEY)) + .tools(new Calculator()) + .chatMemory(MessageWindowChatMemory.withMaxMessages(10)) + .build(); + + String question = "What is the sum of the numbers of letters in the words \"language\" and \"model\"?"; + String answer = assistant.chat(question); + + logger.info(answer); + assertThat(answer).contains("13"); + } + +} diff --git a/libraries-llms/src/test/resources/example-files/simpson's_adventures.txt b/libraries-llms/src/test/resources/example-files/simpson's_adventures.txt new file mode 100644 index 0000000000..ae6de80be0 --- /dev/null +++ b/libraries-llms/src/test/resources/example-files/simpson's_adventures.txt @@ -0,0 +1,28 @@ +Once upon a time in the town of VeggieVille, there lived a cheerful carrot named Simpson. +Simpson was a radiant carrot, always beaming with joy and positivity. +His vibrant orange skin and lush green top were a sight to behold, but it was his infectious laughter and warm personality that really set him apart. + +Simpson had a diverse group of friends, each a vegetable with their own unique characteristics. +There was Bella the blushing beetroot, always ready with a riddle or two; Timmy the timid tomato, a gentle soul with a heart of gold; and Percy the prankster potato, whose jokes always brought a smile to everyone's faces. +Despite their differences, they shared a close bond, their friendship as robust as their natural goodness. + +Their lives were filled with delightful adventures, from playing hide-and-seek amidst the leafy lettuce to swimming in the dewy droplets that pooled on the cabbage leaves. +Their favorite place, though, was the sunlit corner of the vegetable patch, where they would bask in the warmth of the sun, share stories, and have hearty laughs. + +One day, a bunch of pesky caterpillars invaded VeggieVille. +The vegetables were terrified, fearing they would be nibbled to nothingness. +But Simpson, with his usual sunny disposition, had an idea. +He proposed they host a grand feast for the caterpillars, with the juiciest leaves from the outskirts of the town. +Simpson's optimism was contagious, and his friends eagerly joined in to prepare the feast. + +When the caterpillars arrived, they were pleasantly surprised. +They enjoyed the feast and were so impressed with the vegetables' hospitality that they promised not to trouble VeggieVille again. +In return, they agreed to help pollinate the flowers, contributing to a more lush and vibrant VeggieVille. + +Simpson's idea had saved the day, but he humbly attributed the success to their teamwork and friendship. +They celebrated their victory with a grand party, filled with laughter, dance, and merry games. +That night, under the twinkling stars, they made a pact to always stand by each other, come what may. + +From then on, the story of the happy carrot and his friends spread far and wide, a tale of friendship, unity, and positivity. +Simpson, Bella, Timmy, and Percy continued to live their joyful lives, their laughter echoing through VeggieVille. +And so, the tale of the happy carrot and his friends serves as a reminder that no matter the challenge, with optimism, teamwork, and a bit of creativity, anything is possible. \ No newline at end of file diff --git a/axon/README.md b/patterns-modules/axon/README.md similarity index 100% rename from axon/README.md rename to patterns-modules/axon/README.md diff --git a/axon/pom.xml b/patterns-modules/axon/pom.xml similarity index 98% rename from axon/pom.xml rename to patterns-modules/axon/pom.xml index 5eed742aab..473a1b0e15 100644 --- a/axon/pom.xml +++ b/patterns-modules/axon/pom.xml @@ -11,7 +11,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 diff --git a/axon/src/main/java/com/baeldung/axon/OrderApplication.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/OrderApplication.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/OrderApplication.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/OrderApplication.java diff --git a/axon/src/main/java/com/baeldung/axon/OrderApplicationConfiguration.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/OrderApplicationConfiguration.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/OrderApplicationConfiguration.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/OrderApplicationConfiguration.java diff --git a/axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderAggregate.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderAggregate.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderAggregate.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderAggregate.java diff --git a/axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderLine.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderLine.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderLine.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderLine.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/AddProductCommand.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/AddProductCommand.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/commands/AddProductCommand.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/AddProductCommand.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/CreateOrderCommand.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/CreateOrderCommand.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/commands/CreateOrderCommand.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/CreateOrderCommand.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/DecrementProductCountCommand.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/DecrementProductCountCommand.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/commands/DecrementProductCountCommand.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/DecrementProductCountCommand.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/IncrementProductCountCommand.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/IncrementProductCountCommand.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/commands/IncrementProductCountCommand.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/IncrementProductCountCommand.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderCreatedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderCreatedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/OrderCreatedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderCreatedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductAddedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductAddedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/ProductAddedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductAddedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountDecrementedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountDecrementedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountDecrementedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountDecrementedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountIncrementedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountIncrementedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountIncrementedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountIncrementedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductRemovedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductRemovedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/ProductRemovedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductRemovedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/DuplicateOrderLineException.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/DuplicateOrderLineException.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/exceptions/DuplicateOrderLineException.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/DuplicateOrderLineException.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/OrderAlreadyConfirmedException.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/OrderAlreadyConfirmedException.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/exceptions/OrderAlreadyConfirmedException.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/OrderAlreadyConfirmedException.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/Order.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/Order.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/queries/Order.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/Order.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderUpdatesQuery.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderUpdatesQuery.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderUpdatesQuery.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderUpdatesQuery.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/TotalProductsShippedQuery.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/TotalProductsShippedQuery.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/queries/TotalProductsShippedQuery.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/TotalProductsShippedQuery.java diff --git a/axon/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandler.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandler.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandler.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandler.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/LegacyQueryHandler.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/LegacyQueryHandler.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/LegacyQueryHandler.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/LegacyQueryHandler.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/MongoConfiguration.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/MongoConfiguration.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/MongoConfiguration.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/MongoConfiguration.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/MongoOrdersEventHandler.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/MongoOrdersEventHandler.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/MongoOrdersEventHandler.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/MongoOrdersEventHandler.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/OrderQueryService.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrderQueryService.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/OrderQueryService.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrderQueryService.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/OrderResponse.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrderResponse.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/OrderResponse.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrderResponse.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/OrderStatusResponse.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrderStatusResponse.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/OrderStatusResponse.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrderStatusResponse.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/OrdersEventHandler.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrdersEventHandler.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/OrdersEventHandler.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrdersEventHandler.java diff --git a/axon/src/main/resources/application-mongo.properties b/patterns-modules/axon/src/main/resources/application-mongo.properties similarity index 100% rename from axon/src/main/resources/application-mongo.properties rename to patterns-modules/axon/src/main/resources/application-mongo.properties diff --git a/axon/src/main/resources/application.properties b/patterns-modules/axon/src/main/resources/application.properties similarity index 100% rename from axon/src/main/resources/application.properties rename to patterns-modules/axon/src/main/resources/application.properties diff --git a/axon/src/main/resources/logback.xml b/patterns-modules/axon/src/main/resources/logback.xml similarity index 100% rename from axon/src/main/resources/logback.xml rename to patterns-modules/axon/src/main/resources/logback.xml diff --git a/axon/src/main/resources/order-api.http b/patterns-modules/axon/src/main/resources/order-api.http similarity index 100% rename from axon/src/main/resources/order-api.http rename to patterns-modules/axon/src/main/resources/order-api.http diff --git a/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java b/patterns-modules/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java similarity index 100% rename from axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java rename to patterns-modules/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java diff --git a/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java b/patterns-modules/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java similarity index 100% rename from axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java rename to patterns-modules/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java diff --git a/axon/src/test/java/com/baeldung/axon/querymodel/AbstractOrdersEventHandlerUnitTest.java b/patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/AbstractOrdersEventHandlerUnitTest.java similarity index 100% rename from axon/src/test/java/com/baeldung/axon/querymodel/AbstractOrdersEventHandlerUnitTest.java rename to patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/AbstractOrdersEventHandlerUnitTest.java diff --git a/axon/src/test/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandlerUnitTest.java b/patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandlerUnitTest.java similarity index 100% rename from axon/src/test/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandlerUnitTest.java rename to patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandlerUnitTest.java diff --git a/axon/src/test/java/com/baeldung/axon/querymodel/MongoOrdersEventHandlerUnitTest.java b/patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/MongoOrdersEventHandlerUnitTest.java similarity index 100% rename from axon/src/test/java/com/baeldung/axon/querymodel/MongoOrdersEventHandlerUnitTest.java rename to patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/MongoOrdersEventHandlerUnitTest.java diff --git a/axon/src/test/java/com/baeldung/axon/querymodel/OrderQueryServiceIntegrationTest.java b/patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/OrderQueryServiceIntegrationTest.java similarity index 100% rename from axon/src/test/java/com/baeldung/axon/querymodel/OrderQueryServiceIntegrationTest.java rename to patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/OrderQueryServiceIntegrationTest.java diff --git a/axon/src/test/resources/application.properties b/patterns-modules/axon/src/test/resources/application.properties similarity index 100% rename from axon/src/test/resources/application.properties rename to patterns-modules/axon/src/test/resources/application.properties diff --git a/axon/start_axon_server.sh b/patterns-modules/axon/start_axon_server.sh old mode 100755 new mode 100644 similarity index 100% rename from axon/start_axon_server.sh rename to patterns-modules/axon/start_axon_server.sh diff --git a/axon/start_mongo.sh b/patterns-modules/axon/start_mongo.sh old mode 100755 new mode 100644 similarity index 100% rename from axon/start_mongo.sh rename to patterns-modules/axon/start_mongo.sh diff --git a/ddd-contexts/README.md b/patterns-modules/ddd-contexts/README.md similarity index 100% rename from ddd-contexts/README.md rename to patterns-modules/ddd-contexts/README.md diff --git a/ddd-contexts/ddd-contexts-infrastructure/pom.xml b/patterns-modules/ddd-contexts/ddd-contexts-infrastructure/pom.xml similarity index 100% rename from ddd-contexts/ddd-contexts-infrastructure/pom.xml rename to patterns-modules/ddd-contexts/ddd-contexts-infrastructure/pom.xml diff --git a/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/db/InMemoryOrderStore.java b/patterns-modules/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/db/InMemoryOrderStore.java similarity index 100% rename from ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/db/InMemoryOrderStore.java rename to patterns-modules/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/db/InMemoryOrderStore.java diff --git a/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/events/SimpleEventBus.java b/patterns-modules/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/events/SimpleEventBus.java similarity index 100% rename from ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/events/SimpleEventBus.java rename to patterns-modules/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/events/SimpleEventBus.java diff --git a/ddd-contexts/ddd-contexts-infrastructure/src/main/java/module-info.java b/patterns-modules/ddd-contexts/ddd-contexts-infrastructure/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/ddd-contexts-infrastructure/src/main/java/module-info.java rename to patterns-modules/ddd-contexts/ddd-contexts-infrastructure/src/main/java/module-info.java diff --git a/ddd-contexts/ddd-contexts-mainapp/pom.xml b/patterns-modules/ddd-contexts/ddd-contexts-mainapp/pom.xml similarity index 100% rename from ddd-contexts/ddd-contexts-mainapp/pom.xml rename to patterns-modules/ddd-contexts/ddd-contexts-mainapp/pom.xml diff --git a/ddd-contexts/ddd-contexts-mainapp/src/main/java/com/baeldung/dddcontexts/mainapp/Application.java b/patterns-modules/ddd-contexts/ddd-contexts-mainapp/src/main/java/com/baeldung/dddcontexts/mainapp/Application.java similarity index 100% rename from ddd-contexts/ddd-contexts-mainapp/src/main/java/com/baeldung/dddcontexts/mainapp/Application.java rename to patterns-modules/ddd-contexts/ddd-contexts-mainapp/src/main/java/com/baeldung/dddcontexts/mainapp/Application.java diff --git a/ddd-contexts/ddd-contexts-mainapp/src/main/java/module-info.java b/patterns-modules/ddd-contexts/ddd-contexts-mainapp/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/ddd-contexts-mainapp/src/main/java/module-info.java rename to patterns-modules/ddd-contexts/ddd-contexts-mainapp/src/main/java/module-info.java diff --git a/ddd-contexts/ddd-contexts-ordercontext/pom.xml b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/pom.xml similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/pom.xml rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/pom.xml diff --git a/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/CustomerOrder.java b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/CustomerOrder.java similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/CustomerOrder.java rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/CustomerOrder.java diff --git a/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/OrderItem.java b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/OrderItem.java similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/OrderItem.java rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/OrderItem.java diff --git a/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/repository/CustomerOrderRepository.java b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/repository/CustomerOrderRepository.java similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/repository/CustomerOrderRepository.java rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/repository/CustomerOrderRepository.java diff --git a/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/CustomerOrderService.java b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/CustomerOrderService.java similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/CustomerOrderService.java rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/CustomerOrderService.java diff --git a/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/OrderService.java b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/OrderService.java similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/OrderService.java rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/OrderService.java diff --git a/ddd-contexts/ddd-contexts-ordercontext/src/main/java/module-info.java b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/src/main/java/module-info.java rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/module-info.java diff --git a/ddd-contexts/ddd-contexts-sharedkernel/pom.xml b/patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/pom.xml similarity index 100% rename from ddd-contexts/ddd-contexts-sharedkernel/pom.xml rename to patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/pom.xml diff --git a/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/ApplicationEvent.java b/patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/ApplicationEvent.java similarity index 100% rename from ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/ApplicationEvent.java rename to patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/ApplicationEvent.java diff --git a/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventBus.java b/patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventBus.java similarity index 100% rename from ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventBus.java rename to patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventBus.java diff --git a/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventSubscriber.java b/patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventSubscriber.java similarity index 100% rename from ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventSubscriber.java rename to patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventSubscriber.java diff --git a/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/service/ApplicationService.java b/patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/service/ApplicationService.java similarity index 100% rename from ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/service/ApplicationService.java rename to patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/service/ApplicationService.java diff --git a/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/module-info.java b/patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/ddd-contexts-sharedkernel/src/main/java/module-info.java rename to patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/module-info.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/pom.xml b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/pom.xml similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/pom.xml rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/pom.xml diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/PackageItem.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/PackageItem.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/PackageItem.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/PackageItem.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/Parcel.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/Parcel.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/Parcel.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/Parcel.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/ShippableOrder.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/ShippableOrder.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/ShippableOrder.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/ShippableOrder.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/repository/ShippingOrderRepository.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/repository/ShippingOrderRepository.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/repository/ShippingOrderRepository.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/repository/ShippingOrderRepository.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ParcelShippingService.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ParcelShippingService.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ParcelShippingService.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ParcelShippingService.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ShippingService.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ShippingService.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ShippingService.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ShippingService.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/module-info.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/module-info.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/module-info.java diff --git a/ddd-contexts/pom.xml b/patterns-modules/ddd-contexts/pom.xml similarity index 98% rename from ddd-contexts/pom.xml rename to patterns-modules/ddd-contexts/pom.xml index 961a1d1624..f43581b0c8 100644 --- a/ddd-contexts/pom.xml +++ b/patterns-modules/ddd-contexts/pom.xml @@ -11,7 +11,7 @@ com.baeldung - parent-modules + patterns-modules 1.0.0-SNAPSHOT diff --git a/ddd/README.md b/patterns-modules/ddd/README.md similarity index 100% rename from ddd/README.md rename to patterns-modules/ddd/README.md diff --git a/ddd/pom.xml b/patterns-modules/ddd/pom.xml similarity index 98% rename from ddd/pom.xml rename to patterns-modules/ddd/pom.xml index 443b2b5148..80147c29c6 100644 --- a/ddd/pom.xml +++ b/patterns-modules/ddd/pom.xml @@ -12,7 +12,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 diff --git a/ddd/src/main/java/com/baeldung/ddd/PersistingDddAggregatesApplication.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/PersistingDddAggregatesApplication.java similarity index 96% rename from ddd/src/main/java/com/baeldung/ddd/PersistingDddAggregatesApplication.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/PersistingDddAggregatesApplication.java index 3a52fd0440..2d671ff85e 100644 --- a/ddd/src/main/java/com/baeldung/ddd/PersistingDddAggregatesApplication.java +++ b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/PersistingDddAggregatesApplication.java @@ -1,12 +1,12 @@ -package com.baeldung.ddd; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication(scanBasePackages = "com.baeldung.ddd.order") -public class PersistingDddAggregatesApplication { - - public static void main(String[] args) { - SpringApplication.run(PersistingDddAggregatesApplication.class, args); - } -} +package com.baeldung.ddd; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication(scanBasePackages = "com.baeldung.ddd.order") +public class PersistingDddAggregatesApplication { + + public static void main(String[] args) { + SpringApplication.run(PersistingDddAggregatesApplication.class, args); + } +} diff --git a/ddd/src/main/java/com/baeldung/ddd/order/Order.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/Order.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/Order.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/Order.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/OrderLine.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/OrderLine.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/OrderLine.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/OrderLine.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/Product.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/Product.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/Product.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/Product.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/config/CustomMongoConfiguration.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/config/CustomMongoConfiguration.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/config/CustomMongoConfiguration.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/config/CustomMongoConfiguration.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/AmountBasedDiscountPolicy.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/AmountBasedDiscountPolicy.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/AmountBasedDiscountPolicy.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/AmountBasedDiscountPolicy.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/DiscountPolicy.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/DiscountPolicy.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/DiscountPolicy.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/DiscountPolicy.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/FlatDiscountPolicy.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/FlatDiscountPolicy.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/FlatDiscountPolicy.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/FlatDiscountPolicy.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/Order.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/Order.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/Order.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/Order.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialDiscountPolicy.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialDiscountPolicy.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialDiscountPolicy.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialDiscountPolicy.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialOrder.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialOrder.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialOrder.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialOrder.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/HtmlOrderViewCreator.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/HtmlOrderViewCreator.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/HtmlOrderViewCreator.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/HtmlOrderViewCreator.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/OrderVisitor.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/OrderVisitor.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/OrderVisitor.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/OrderVisitor.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/Visitable.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/Visitable.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/Visitable.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/Visitable.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderLine.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderLine.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderLine.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderLine.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderRepository.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/mongo/OrderMongoRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/mongo/OrderMongoRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/mongo/OrderMongoRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/mongo/OrderMongoRepository.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/DomainLayerApplication.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/DomainLayerApplication.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/DomainLayerApplication.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/DomainLayerApplication.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/cli/CliOrderController.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/cli/CliOrderController.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/application/cli/CliOrderController.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/cli/CliOrderController.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/AddProductRequest.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/AddProductRequest.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/AddProductRequest.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/AddProductRequest.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/CreateOrderRequest.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/CreateOrderRequest.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/CreateOrderRequest.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/CreateOrderRequest.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/response/CreateOrderResponse.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/response/CreateOrderResponse.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/application/response/CreateOrderResponse.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/response/CreateOrderResponse.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/rest/OrderController.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/rest/OrderController.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/application/rest/OrderController.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/rest/OrderController.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/DomainException.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/DomainException.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/DomainException.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/DomainException.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Order.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Order.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Order.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Order.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderItem.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderItem.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderItem.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderItem.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderStatus.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderStatus.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderStatus.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderStatus.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Product.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Product.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Product.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Product.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/repository/OrderRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/repository/OrderRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/repository/OrderRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/repository/OrderRepository.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderService.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderService.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderService.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderService.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/OrderService.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/OrderService.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/OrderService.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/OrderService.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/BeanConfiguration.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/BeanConfiguration.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/BeanConfiguration.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/BeanConfiguration.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/CassandraConfiguration.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/CassandraConfiguration.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/CassandraConfiguration.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/CassandraConfiguration.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/MongoDBConfiguration.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/MongoDBConfiguration.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/MongoDBConfiguration.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/MongoDBConfiguration.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/CassandraDbOrderRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/CassandraDbOrderRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/CassandraDbOrderRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/CassandraDbOrderRepository.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderEntity.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderEntity.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderEntity.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderEntity.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderItemEntity.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderItemEntity.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderItemEntity.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderItemEntity.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/SpringDataCassandraOrderRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/SpringDataCassandraOrderRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/SpringDataCassandraOrderRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/SpringDataCassandraOrderRepository.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/MongoDbOrderRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/MongoDbOrderRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/MongoDbOrderRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/MongoDbOrderRepository.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/SpringDataMongoOrderRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/SpringDataMongoOrderRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/SpringDataMongoOrderRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/SpringDataMongoOrderRepository.java diff --git a/ddd/src/main/resources/ddd-layers.properties b/patterns-modules/ddd/src/main/resources/ddd-layers.properties similarity index 100% rename from ddd/src/main/resources/ddd-layers.properties rename to patterns-modules/ddd/src/main/resources/ddd-layers.properties diff --git a/ddd/src/test/java/com/baeldung/ddd/order/OrderFixtureUtils.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/OrderFixtureUtils.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/OrderFixtureUtils.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/OrderFixtureUtils.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/OrderUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/OrderUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/OrderUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/OrderUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/DoubleDispatchDiscountPolicyUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/DoubleDispatchDiscountPolicyUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/DoubleDispatchDiscountPolicyUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/DoubleDispatchDiscountPolicyUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/HtmlOrderViewCreatorUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/HtmlOrderViewCreatorUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/HtmlOrderViewCreatorUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/HtmlOrderViewCreatorUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/MethodOverloadExampleUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/MethodOverloadExampleUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/MethodOverloadExampleUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/MethodOverloadExampleUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/SingleDispatchDiscountPolicyUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/SingleDispatchDiscountPolicyUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/SingleDispatchDiscountPolicyUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/SingleDispatchDiscountPolicyUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderLiveTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderLiveTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderLiveTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderLiveTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/jpa/ViolateOrderBusinessRulesUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/jpa/ViolateOrderBusinessRulesUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/jpa/ViolateOrderBusinessRulesUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/jpa/ViolateOrderBusinessRulesUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoLiveTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoLiveTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoLiveTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoLiveTest.java diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderProvider.java b/patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderProvider.java similarity index 100% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderProvider.java rename to patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderProvider.java diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderServiceUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderServiceUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderServiceUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderServiceUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryLiveTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryLiveTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryLiveTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryLiveTest.java diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryLiveTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryLiveTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryLiveTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryLiveTest.java diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryUnitTest.java diff --git a/ddd/src/test/resources/com/baeldung/dddhexagonalspring/README.md b/patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/README.md similarity index 100% rename from ddd/src/test/resources/com/baeldung/dddhexagonalspring/README.md rename to patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/README.md diff --git a/ddd/src/test/resources/com/baeldung/dddhexagonalspring/cassandra-init.cql b/patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/cassandra-init.cql similarity index 100% rename from ddd/src/test/resources/com/baeldung/dddhexagonalspring/cassandra-init.cql rename to patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/cassandra-init.cql diff --git a/ddd/src/test/resources/com/baeldung/dddhexagonalspring/docker-compose.yml b/patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/docker-compose.yml similarity index 100% rename from ddd/src/test/resources/com/baeldung/dddhexagonalspring/docker-compose.yml rename to patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/docker-compose.yml diff --git a/ddd/src/test/resources/com/baeldung/dddhexagonalspring/mongo-init.js b/patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/mongo-init.js similarity index 100% rename from ddd/src/test/resources/com/baeldung/dddhexagonalspring/mongo-init.js rename to patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/mongo-init.js diff --git a/ddd/src/test/resources/ddd-layers-test.properties b/patterns-modules/ddd/src/test/resources/ddd-layers-test.properties similarity index 100% rename from ddd/src/test/resources/ddd-layers-test.properties rename to patterns-modules/ddd/src/test/resources/ddd-layers-test.properties diff --git a/patterns-modules/pom.xml b/patterns-modules/pom.xml index add2b0475b..7dd26ac31c 100644 --- a/patterns-modules/pom.xml +++ b/patterns-modules/pom.xml @@ -14,6 +14,12 @@ + axon + clean-architecture + coupling + cqrs-es + ddd + ddd-contexts design-patterns-architectural design-patterns-behavioral design-patterns-behavioral-2 @@ -24,14 +30,11 @@ design-patterns-singleton design-patterns-structural dip - cqrs-es + enterprise-patterns front-controller + idd intercepting-filter solid - clean-architecture - enterprise-patterns - coupling - idd diff --git a/couchbase/.gitignore b/persistence-modules/couchbase/.gitignore similarity index 100% rename from couchbase/.gitignore rename to persistence-modules/couchbase/.gitignore diff --git a/couchbase/README.md b/persistence-modules/couchbase/README.md similarity index 100% rename from couchbase/README.md rename to persistence-modules/couchbase/README.md diff --git a/couchbase/mvnw b/persistence-modules/couchbase/mvnw similarity index 100% rename from couchbase/mvnw rename to persistence-modules/couchbase/mvnw diff --git a/couchbase/mvnw.cmd b/persistence-modules/couchbase/mvnw.cmd similarity index 100% rename from couchbase/mvnw.cmd rename to persistence-modules/couchbase/mvnw.cmd diff --git a/couchbase/pom.xml b/persistence-modules/couchbase/pom.xml similarity index 98% rename from couchbase/pom.xml rename to persistence-modules/couchbase/pom.xml index 823b33ee29..b98c0cc387 100644 --- a/couchbase/pom.xml +++ b/persistence-modules/couchbase/pom.xml @@ -10,7 +10,7 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/person/Person.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/Person.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/person/Person.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/Person.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/BucketService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/BucketService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/BucketService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/BucketService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/CrudService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/CrudService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/CrudService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/CrudService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/DuplicateKeyException.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/DuplicateKeyException.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/DuplicateKeyException.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/DuplicateKeyException.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGrade.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGrade.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGrade.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGrade.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeKeyGenerator.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeKeyGenerator.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeKeyGenerator.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeKeyGenerator.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeQueryBuilder.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeQueryBuilder.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeQueryBuilder.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeQueryBuilder.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/person/Person.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/Person.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/person/Person.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/Person.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java diff --git a/couchbase/src/main/resources/application.properties b/persistence-modules/couchbase/src/main/resources/application.properties similarity index 100% rename from couchbase/src/main/resources/application.properties rename to persistence-modules/couchbase/src/main/resources/application.properties diff --git a/couchbase/src/main/resources/logback.xml b/persistence-modules/couchbase/src/main/resources/logback.xml similarity index 100% rename from couchbase/src/main/resources/logback.xml rename to persistence-modules/couchbase/src/main/resources/logback.xml diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java diff --git a/couchbase/src/test/resources/logback.xml b/persistence-modules/couchbase/src/test/resources/logback.xml similarity index 100% rename from couchbase/src/test/resources/logback.xml rename to persistence-modules/couchbase/src/test/resources/logback.xml diff --git a/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java index d7fd49d917..3903e272de 100644 --- a/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java +++ b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java @@ -22,6 +22,7 @@ public class EditorUnitTest { loadAndVerifyTestData(entityManagerFactory, editor); } */ + @Test public void givenNeo4j_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-neo4j"); diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index a99a180390..eb4b212771 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -21,6 +21,7 @@ blaze-persistence core-java-persistence core-java-persistence-2 + couchbase elasticsearch flyway flyway-repair @@ -105,6 +106,7 @@ spring-jpa spring-jpa-2 spring-jdbc + spring-jdbc-2 spring-jooq spring-mybatis spring-persistence-simple diff --git a/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/cassandra/inquery/ProductRepositoryNestedLiveTest.java b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/cassandra/inquery/ProductRepositoryNestedLiveTest.java index 3592c8b80d..3d99782afd 100644 --- a/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/cassandra/inquery/ProductRepositoryNestedLiveTest.java +++ b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/cassandra/inquery/ProductRepositoryNestedLiveTest.java @@ -20,7 +20,9 @@ import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; - +/** + * This live test requires a running Docker instance so that a Cassandra container can be created + */ @Testcontainers @SpringBootTest class ProductRepositoryNestedLiveTest { diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java index 14d5403cb5..7b5a307b81 100644 --- a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java @@ -12,6 +12,9 @@ interface PassengerRepository extends JpaRepository, CustomPass Passenger findTopByOrderBySeatNumberAsc(); List findByOrderBySeatNumberAsc(); + + //The Limit type is a new feature in Spring Data JPA version 3.2 + //List findByOrderBySeatNumberAsc(Limit limit); List findByFirstNameIgnoreCase(String firstName); diff --git a/persistence-modules/spring-jdbc-2/pom.xml b/persistence-modules/spring-jdbc-2/pom.xml new file mode 100644 index 0000000000..ce79c1c615 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + + org.example + spring-jdbc-2 + 1.0-SNAPSHOT + spring-jdbc-2 + Demo project for Spring Jdbc + + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 + + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + + 3.2.0-SNAPSHOT + 5.10.0 + UTF-8 + + + \ No newline at end of file diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/JdbcClientDemoApplication.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/JdbcClientDemoApplication.java new file mode 100644 index 0000000000..d10124fdef --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/JdbcClientDemoApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.jdbcclient; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = "com.baledung.jdbcclient") +public class JdbcClientDemoApplication { + + public static void main(String[] args) { + SpringApplication.run(JdbcClientDemoApplication.class, args); + } +} diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/dao/StudentDao.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/dao/StudentDao.java new file mode 100644 index 0000000000..ba5bfcee11 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/dao/StudentDao.java @@ -0,0 +1,95 @@ +package com.baeldung.jdbcclient.dao; + +import com.baeldung.jdbcclient.model.Student; +import com.baeldung.jdbcclient.model.StudentResultExtractor; +import com.baeldung.jdbcclient.model.StudentRowMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.RowCountCallbackHandler; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Repository; + +import java.sql.Types; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Repository +public class StudentDao { + + private static final Logger logger = LoggerFactory.getLogger(StudentDao.class); + @Autowired + private JdbcClient jdbcClient; + + public Integer insertWithSetParamWithNamedParamAndSqlType(Student student) { + String sql = "INSERT INTO student (student_name, age, grade, gender, state)" + + "VALUES (:name, :age, :grade, :gender, :state)"; + Integer noOfrowsAffected = this.jdbcClient.sql(sql) + .param("name", student.getStudentName(), Types.VARCHAR) + .param("age", student.getAge(), Types.INTEGER) + .param("grade", student.getGrade(), Types.INTEGER) + .param("gender", student.getStudentGender(), Types.VARCHAR) + .param("state", student.getState(), Types.VARCHAR) + .update(); + logger.info("No. of rows affected: " + noOfrowsAffected); + return noOfrowsAffected; + } + + public List getStudentsOfGradeStateAndGenderWithPositionalParams(int grade, String state, String gender) { + String sql = "select student_id, student_name, age, grade, gender, state from student" + + " where grade = ? and state = ? and gender = ?"; + return jdbcClient.sql(sql) + .param(grade) + .param(state) + .param(gender) + .query(new StudentRowMapper()).list(); + } + + public List getStudentsOfGradeStateAndGenderWithParamIndex(int grade, String state, String gender) { + String sql = "select student_id, student_name, age, grade, gender, state from student" + + " where grade = ? and state = ? and gender = ?"; + return jdbcClient.sql(sql) + .param(1,grade) + .param(2, state) + .param(3, gender) + .query(new StudentResultExtractor()); + } + + public Student getStudentsOfGradeStateAndGenderWithParamsInVarargs(int grade, String state, String gender) { + String sql = "select student_id, student_name, age, grade, gender, state from student" + + " where grade = ? and state = ? and gender = ? limit 1"; + return jdbcClient.sql(sql) + .params(grade, state, gender) + .query(new StudentRowMapper()).single(); + } + + public Optional getStudentsOfGradeStateAndGenderWithParamsInList(List params) { + String sql = "select student_id, student_name, age, grade, gender, state from student" + + " where grade = ? and state = ? and gender = ? limit 1"; + return jdbcClient.sql(sql) + .params(params) + .query(new StudentRowMapper()).optional(); + } + + + public int getCountOfStudentsOfGradeStateAndGenderWithNamedParam(int grade, String state, String gender) { + String sql = "select student_id, student_name, age, grade, gender, state from student" + + " where grade = :grade and state = :state and gender = :gender"; + RowCountCallbackHandler countCallbackHandler = new RowCountCallbackHandler(); + jdbcClient.sql(sql) + .param("grade", grade) + .param("state", state) + .param("gender", gender) + .query(countCallbackHandler); + return countCallbackHandler.getRowCount(); + } + + public List getStudentsOfGradeStateAndGenderWithParamMap(Map paramMap) { + String sql = "select student_id, student_name, age, grade, gender, state from student" + + " where grade = :grade and state = :state and gender = :gender"; + return jdbcClient.sql(sql) + .params(paramMap) + .query(new StudentRowMapper()).list(); + } +} diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/Student.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/Student.java new file mode 100644 index 0000000000..3de8a6e1f9 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/Student.java @@ -0,0 +1,60 @@ +package com.baeldung.jdbcclient.model; + +public class Student { + private Integer studentId; + private String studentName; + private String studentGender; + private Integer age; + private Integer grade; + + public Integer getStudentId() { + return studentId; + } + + public void setStudentId(Integer studentId) { + this.studentId = studentId; + } + + public String getStudentName() { + return studentName; + } + + public void setStudentName(String studentName) { + this.studentName = studentName; + } + + public String getStudentGender() { + return studentGender; + } + + public void setStudentGender(String studentGender) { + this.studentGender = studentGender; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public Integer getGrade() { + return grade; + } + + public void setGrade(Integer grade) { + this.grade = grade; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + private String state; + +} diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/StudentResultExtractor.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/StudentResultExtractor.java new file mode 100644 index 0000000000..29cb60cee9 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/StudentResultExtractor.java @@ -0,0 +1,26 @@ +package com.baeldung.jdbcclient.model; + +import org.springframework.jdbc.core.ResultSetExtractor; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class StudentResultExtractor implements ResultSetExtractor> { + @Override + public List extractData(ResultSet rs) throws SQLException { + List students = new ArrayList(); + while(rs.next()) { + Student student = new Student(); + student.setStudentId(rs.getInt("student_id")); + student.setStudentName(rs.getString("student_name")); + student.setAge(rs.getInt("age")); + student.setStudentGender(rs.getString("gender")); + student.setGrade(rs.getInt("grade")); + student.setState(rs.getString("state")); + students.add(student); + } + return students; + } +} diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/StudentRowMapper.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/StudentRowMapper.java new file mode 100644 index 0000000000..c387a6c485 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/StudentRowMapper.java @@ -0,0 +1,20 @@ +package com.baeldung.jdbcclient.model; + +import org.springframework.jdbc.core.RowMapper; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class StudentRowMapper implements RowMapper { + @Override + public Student mapRow(ResultSet rs, int rowNum) throws SQLException { + Student student = new Student(); + student.setStudentId(rs.getInt("student_id")); + student.setStudentName(rs.getString("student_name")); + student.setAge(rs.getInt("age")); + student.setStudentGender(rs.getString("gender")); + student.setGrade(rs.getInt("grade")); + student.setState(rs.getString("state")); + return student; + } +} diff --git a/persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/application.properties b/persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/application.properties new file mode 100644 index 0000000000..04c963ebf4 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/application.properties @@ -0,0 +1,5 @@ +# DataSource Configuration +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=user +spring.datasource.password= # Leave this empty \ No newline at end of file diff --git a/persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/drop_student.sql b/persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/drop_student.sql new file mode 100644 index 0000000000..954545a862 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/drop_student.sql @@ -0,0 +1 @@ +DROP TABLE student; \ No newline at end of file diff --git a/persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/student.sql b/persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/student.sql new file mode 100644 index 0000000000..0e137f5445 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/student.sql @@ -0,0 +1,98 @@ + +CREATE TABLE student ( + student_id INT AUTO_INCREMENT PRIMARY KEY, + student_name VARCHAR(255) NOT NULL, + age INT, + grade INT NOT NULL, + gender VARCHAR(10) NOT NULL, + state VARCHAR(100) NOT NULL +); +-- Student 1 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('John Smith', 18, 3, 'Male', 'California'); + +-- Student 2 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Emily Johnson', 17, 2, 'Female', 'New York'); + +-- Student 3 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Michael Davis', 4, 1, 'Male', 'Texas'); + +-- Student 4 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Sophia Martinez', 2, 1, 'Female', 'Florida'); + +-- Student 5 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('William Brown', 5, 5, 'Male', 'California'); + +-- Student 6 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Olivia Garcia', 4, 2, 'Female', 'Texas'); + +-- Student 7 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Ethan Rodriguez', 3, 1, 'Male', 'New York'); + +-- Student 8 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Ava Hernandez', 2, 1, 'Female', 'Florida'); + +-- Student 9 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('James Wilson', 5, 4, 'Male', 'Texas'); + +-- Student 10 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Emma Miller', 3, 1, 'Female', 'California'); + +-- Student 11 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Benjamin Brown', 4, 1, 'Male', 'New York'); + +-- Student 12 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Mia Smith', 2, 1, 'Female', 'Florida'); + +-- Student 13 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Daniel Johnson', 5, 4, 'Male', 'California'); + +-- Student 14 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Ava Davis', 4, 2, 'Female', 'Texas'); + +-- Student 15 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Matthew Martinez', 3, 1, 'Male', 'New York'); + +-- Student 16 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Sophia Taylor', 2, 1, 'Female', 'Florida'); + +-- Student 17 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Alexander White', 5, 4, 'Male', 'California'); + +-- Student 18 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Olivia Johnson', 4, 2, 'Female', 'Texas'); + +-- Student 19 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Christopher Lee', 3, 1, 'Male', 'New York'); + +-- Student 20 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Emma Wilson', 2, 1, 'Female', 'Florida'); + +-- Student 21 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Elijah Smith', 5, 3, 'Male', 'Texas'); + +-- Student 22 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Isabella Davis', 4, 2, 'Female', 'California'); + +-- Student 23 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Liam Johnson', 3, 1, 'Male', 'New York'); + +-- Student 24 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Olivia Garcia', 2, 1, 'Female', 'Florida'); + +-- Student 25 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Noah Rodriguez', 5, 3, 'Male', 'Texas'); + +-- Student 26 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Sophia Hernandez', 4, 2, 'Female', 'California'); + +-- Student 27 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Mason Smith', 3, 1, 'Male', 'New York'); + +-- Student 28 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Ava Taylor', 2, 1, 'Female', 'Florida'); + +-- Student 29 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('William Brown', 5, 5, 'Male', 'Texas'); + +-- Student 30 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Olivia Martinez', 4, 4, 'Female', 'California'); diff --git a/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcclient/JdbcClientUnitTest.java b/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcclient/JdbcClientUnitTest.java new file mode 100644 index 0000000000..be30efcb9c --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcclient/JdbcClientUnitTest.java @@ -0,0 +1,104 @@ +package com.baeldung.jdbcclient; + +import com.baeldung.jdbcclient.dao.StudentDao; +import com.baeldung.jdbcclient.model.Student; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.jdbc.Sql; + +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +@Sql(value = "/jdbcclient/student.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) +@Sql(value = "/jdbcclient/drop_student.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@SpringBootTest(classes = JdbcClientDemoApplication.class) +@TestPropertySource(locations = {"classpath:jdbcclient/application.properties"}) + +public class JdbcClientUnitTest { + private static final Logger logger = LoggerFactory.getLogger(JdbcClientUnitTest.class); + + @Autowired + private StudentDao studentDao; + + @Test + void givenJdbcClient_whenInsertWithNamedParamAndSqlType_thenSuccess() { + logger.info("testing invoked successfully"); + Student student = getSampleStudent("Johny Dep", 8, 4, "Male", "New York"); + assertEquals(1, studentDao.insertWithSetParamWithNamedParamAndSqlType(student)); + } + + @Test + void givenJdbcClient_whenQueryWithPositionalParams_thenSuccess() { + logger.info("testing invoked successfully"); + List students = studentDao.getStudentsOfGradeStateAndGenderWithPositionalParams( + 1, "New York", "Male"); + logger.info("number of students fetched " + students.size()); + assertEquals(6, students.size()); + } + + @Test + void givenJdbcClient_whenQueryWithParamsInVarargs_thenSuccess() { + logger.info("testing invoked successfully"); + Student student = studentDao.getStudentsOfGradeStateAndGenderWithParamsInVarargs( + 1, "New York", "Male"); + assertNotNull(student); + } + + @Test + void givenJdbcClient_whenQueryWithParamsInList_thenSuccess() { + logger.info("testing invoked successfully"); + List params = List.of(1, "New York", "Male"); + Optional optional = studentDao.getStudentsOfGradeStateAndGenderWithParamsInList(params); + if(optional.isPresent()) { + assertNotNull(optional.get()); + } else { + assertThrows(NoSuchElementException.class, () -> optional.get()); + } + } + + @Test + void givenJdbcClient_whenQueryWithParamsIndex_thenSuccess() { + logger.info("testing invoked successfully"); + List students = studentDao.getStudentsOfGradeStateAndGenderWithParamIndex( + 1, "New York", "Male"); + assertEquals(6, students.size()); + } + @Test + void givenJdbcClient_whenQueryWithNamedParam_thenSuccess() { + logger.info("testing invoked successfully"); + Integer count = studentDao.getCountOfStudentsOfGradeStateAndGenderWithNamedParam( + 1, "New York", "Male"); + logger.info("number of students fetched " + count); + assertEquals(6, count); + } + @Test + void givenJdbcClient_whenQueryWithParamMap_thenSuccess() { + logger.info("testing invoked successfully"); + Map paramMap = Map.of( + "grade", 1, + "gender", "Male", + "state", "New York" + ); + List students = studentDao.getStudentsOfGradeStateAndGenderWithParamMap(paramMap); + logger.info("number of students fetched " + students.size()); + assertEquals(6, students.size()); + } + + private Student getSampleStudent(String name, int age, int grade, String gender, String state) { + Student student = new Student(); + student.setStudentName(name); + student.setStudentGender(gender); + student.setAge(age); + student.setGrade(grade); + student.setState(state); + return student; + } +} diff --git a/persistence-modules/spring-jdbc-2/src/test/resources/logback-test.xml b/persistence-modules/spring-jdbc-2/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 327d83017f..ab1fffa8b9 100644 --- a/pom.xml +++ b/pom.xml @@ -349,7 +349,6 @@ - @@ -362,7 +361,7 @@ muleesb web-modules/java-lite persistence-modules/deltaspike - persistence-modules/hibernate-ogm + persistence-modules/hibernate-ogm persistence-modules/spring-data-cassandra-reactive java-nashorn jeromq @@ -523,7 +522,6 @@ - @@ -534,7 +532,7 @@ muleesb web-modules/java-lite persistence-modules/deltaspike - persistence-modules/hibernate-ogm + persistence-modules/hibernate-ogm persistence-modules/spring-data-cassandra-reactive java-nashorn jeromq @@ -765,13 +763,11 @@ aws-modules checker-framework - couchbase core-groovy-modules core-java-modules custom-pmd data-structures - ddd-contexts jackson-modules jmh deeplearning4j @@ -821,11 +817,8 @@ atomikos atomix - axon - bazel google-auto-project - ddd disruptor dozer dubbo @@ -937,6 +930,7 @@ spring-di-4 spring-kafka-2 + libraries-llms @@ -1039,8 +1033,7 @@ aws-modules checker-framework - couchbase - + core-groovy-modules core-java-modules @@ -1057,7 +1050,6 @@ spring-aop-2 custom-pmd data-structures - ddd-contexts jackson-modules jmh deeplearning4j @@ -1107,11 +1099,8 @@ atomikos atomix - axon - bazel google-auto-project - ddd disruptor dozer @@ -1221,10 +1210,10 @@ gradle-modules/gradle/maven-to-gradle persistence-modules/spring-data-neo4j spring-actuator - gcp-firebase spring-di-4 spring-kafka-2 + libraries-llms diff --git a/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java b/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java deleted file mode 100644 index d289693a73..0000000000 --- a/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.activitiwithspring; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ActivitiWithSpringApplication.class) -@AutoConfigureTestDatabase -public class ActivitiWithSpringApplicationIntegrationTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-boot-modules/spring-boot-3-2/README.md b/spring-boot-modules/spring-boot-3-2/README.md new file mode 100644 index 0000000000..c176de2310 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-2/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Spring Boot 3.1’s ConnectionDetails Abstraction](https://www.baeldung.com/spring-boot-3-1-connectiondetails-abstraction) diff --git a/spring-boot-modules/spring-boot-3-2/pom.xml b/spring-boot-modules/spring-boot-3-2/pom.xml index 9e73d8ea32..276659c609 100644 --- a/spring-boot-modules/spring-boot-3-2/pom.xml +++ b/spring-boot-modules/spring-boot-3-2/pom.xml @@ -15,6 +15,14 @@ ../../parent-boot-3 + + + repository.spring.release + Spring GA Repository + https://repo.spring.io/milestone + + + org.springframework.boot @@ -94,6 +102,17 @@ org.springframework.boot spring-boot-starter-test + 3.2.0-M2 + + + org.junit.jupiter + junit-jupiter + 5.10.0 + + + org.junit.jupiter + junit-jupiter-api + 5.10.0 org.postgresql @@ -175,6 +194,18 @@ + + + + org.springframework.boot + spring-boot-dependencies + 3.2.0-M2 + import + pom + + + + @@ -244,9 +275,6 @@ org.apache.maven.plugins maven-compiler-plugin - - --enable-preview - diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/conditionalonthreading/ConditionalOnThreadingUnitTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/conditionalonthreading/ConditionalOnThreadingUnitTest.java new file mode 100644 index 0000000000..ed65769954 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/conditionalonthreading/ConditionalOnThreadingUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.conditionalonthreading; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; +import org.springframework.boot.autoconfigure.condition.ConditionalOnThreading; +import org.springframework.boot.autoconfigure.thread.Threading; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +public class ConditionalOnThreadingUnitTest { + + ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() + .withUserConfiguration(CurrentConfig.class); + + @Configuration + static class CurrentConfig { + + @Bean + @ConditionalOnThreading(Threading.PLATFORM) + ThreadingType platformBean() { + return ThreadingType.PLATFORM; + } + + @Bean + @ConditionalOnThreading(Threading.VIRTUAL) + ThreadingType virtualBean() { + return ThreadingType.VIRTUAL; + } + } + + enum ThreadingType { + PLATFORM, VIRTUAL + } + + @Test + @EnabledForJreRange(max = JRE.JAVA_20) + public void whenJava20AndVirtualThreadsEnabled_thenThreadingIsPlatform() { + applicationContextRunner.withPropertyValues("spring.threads.virtual.enabled=true").run(context -> { + Assertions.assertThat(context.getBean(ThreadingType.class)).isEqualTo(ThreadingType.PLATFORM); + }); + } + + @Test + @EnabledForJreRange(max = JRE.JAVA_20) + public void whenJava20AndVirtualThreadsDisabled_thenThreadingIsPlatform() { + applicationContextRunner.withPropertyValues("spring.threads.virtual.enabled=false").run(context -> { + Assertions.assertThat(context.getBean(ThreadingType.class)).isEqualTo(ThreadingType.PLATFORM); + }); + } + + @Test + @EnabledForJreRange(min = JRE.JAVA_21) + public void whenJava21AndVirtualThreadsEnabled_thenThreadingIsVirtual() { + applicationContextRunner.withPropertyValues("spring.threads.virtual.enabled=true").run(context -> { + Assertions.assertThat(context.getBean(ThreadingType.class)).isEqualTo(ThreadingType.VIRTUAL); + }); + } + + @Test + @EnabledForJreRange(min = JRE.JAVA_21) + public void whenJava21AndVirtualThreadsDisabled_thenThreadingIsPlatform() { + applicationContextRunner.withPropertyValues("spring.threads.virtual.enabled=false").run(context -> { + Assertions.assertThat(context.getBean(ThreadingType.class)).isEqualTo(ThreadingType.PLATFORM); + }); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3/README.md b/spring-boot-modules/spring-boot-3/README.md index 8791aaae1f..ded5db30e4 100644 --- a/spring-boot-modules/spring-boot-3/README.md +++ b/spring-boot-modules/spring-boot-3/README.md @@ -8,3 +8,4 @@ - [HTTP Interface in Spring 6](https://www.baeldung.com/spring-6-http-interface) - [Working with Virtual Threads in Spring 6](https://www.baeldung.com/spring-6-virtual-threads) - [Docker Compose Support in Spring Boot 3](https://www.baeldung.com/ops/docker-compose-support-spring-boot) +- [A Guide to RestClient in Spring Boot](https://www.baeldung.com/spring-boot-restclient) diff --git a/spring-boot-modules/spring-boot-data-2/README.md b/spring-boot-modules/spring-boot-data-2/README.md index 9ff2b2caf8..8e6619dce4 100644 --- a/spring-boot-modules/spring-boot-data-2/README.md +++ b/spring-boot-modules/spring-boot-data-2/README.md @@ -1,7 +1,6 @@ ### Relevant Articles: - [HttpMessageNotWritableException: No Converter for [class …] With Preset Content-Type](https://www.baeldung.com/spring-no-converter-with-preset) -- [Spring Boot: Customize the Jackson ObjectMapper](https://www.baeldung.com/spring-boot-customize-jackson-objectmapper) - [“HttpMessageNotWritableException: No converter found for return value of type”](https://www.baeldung.com/spring-no-converter-found) - [Creating a Read-Only Repository with Spring Data](https://www.baeldung.com/spring-data-read-only-repository) - [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) diff --git a/spring-boot-modules/spring-boot-data/README.md b/spring-boot-modules/spring-boot-data/README.md index c56c87014d..aa745b77a2 100644 --- a/spring-boot-modules/spring-boot-data/README.md +++ b/spring-boot-modules/spring-boot-data/README.md @@ -11,4 +11,5 @@ This module contains articles about Spring Boot with Spring Data - [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) - [Using @JsonComponent in Spring Boot](https://www.baeldung.com/spring-boot-jsoncomponent) - [Guide To Running Logic on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) +- [Spring Boot: Customize the Jackson ObjectMapper](https://www.baeldung.com/spring-boot-customize-jackson-objectmapper) diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/app/Application.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/app/Application.java similarity index 100% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/app/Application.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/app/Application.java diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeConstants.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeConstants.java similarity index 100% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeConstants.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeConstants.java index d1875d03d9..ecb07e44b1 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeConstants.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeConstants.java @@ -1,10 +1,10 @@ package com.baeldung.boot.jackson.config; -import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; - import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; + public class CoffeeConstants { public static final String DATETIME_FORMAT = "dd-MM-yyyy HH:mm"; diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeCustomizerConfig.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeCustomizerConfig.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeCustomizerConfig.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeCustomizerConfig.java index edb2b478fc..0aa2d3eb96 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeCustomizerConfig.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeCustomizerConfig.java @@ -1,11 +1,12 @@ package com.baeldung.boot.jackson.config; -import com.fasterxml.jackson.annotation.JsonInclude; +import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; + import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; +import com.fasterxml.jackson.annotation.JsonInclude; @Configuration public class CoffeeCustomizerConfig { diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeHttpConverterConfiguration.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeHttpConverterConfiguration.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeHttpConverterConfiguration.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeHttpConverterConfiguration.java index eff2b5c252..be8e3bb34d 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeHttpConverterConfiguration.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeHttpConverterConfiguration.java @@ -1,12 +1,13 @@ package com.baeldung.boot.jackson.config; -import com.fasterxml.jackson.annotation.JsonInclude; +import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; +import com.fasterxml.jackson.annotation.JsonInclude; @Configuration public class CoffeeHttpConverterConfiguration { diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeJacksonBuilderConfig.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeJacksonBuilderConfig.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeJacksonBuilderConfig.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeJacksonBuilderConfig.java index 8057fff3db..19501f872c 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeJacksonBuilderConfig.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeJacksonBuilderConfig.java @@ -1,12 +1,13 @@ package com.baeldung.boot.jackson.config; -import com.fasterxml.jackson.annotation.JsonInclude; +import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; -import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; +import com.fasterxml.jackson.annotation.JsonInclude; @Configuration public class CoffeeJacksonBuilderConfig { diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeObjectMapperConfig.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeObjectMapperConfig.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeObjectMapperConfig.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeObjectMapperConfig.java index f1ce6458ae..cadf17b6b8 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeObjectMapperConfig.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeObjectMapperConfig.java @@ -1,13 +1,14 @@ package com.baeldung.boot.jackson.config; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; -import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; @Configuration public class CoffeeObjectMapperConfig { diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeRegisterModuleConfig.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeRegisterModuleConfig.java similarity index 88% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeRegisterModuleConfig.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeRegisterModuleConfig.java index fc157f8156..55a928dabc 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeRegisterModuleConfig.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeRegisterModuleConfig.java @@ -1,19 +1,19 @@ package com.baeldung.boot.jackson.config; -import com.fasterxml.jackson.databind.Module; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; -import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; @Configuration @PropertySource("classpath:coffee.properties") public class CoffeeRegisterModuleConfig { @Bean - public Module javaTimeModule() { + public JavaTimeModule javaTimeModule() { JavaTimeModule module = new JavaTimeModule(); module.addSerializer(LOCAL_DATETIME_SERIALIZER); return module; diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/controller/CoffeeController.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/controller/CoffeeController.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/controller/CoffeeController.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/controller/CoffeeController.java index 23749b18a2..36489a645a 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/controller/CoffeeController.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/controller/CoffeeController.java @@ -1,11 +1,12 @@ package com.baeldung.boot.jackson.controller; -import com.baeldung.boot.jackson.model.Coffee; +import static com.baeldung.boot.jackson.config.CoffeeConstants.FIXED_DATE; + import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import static com.baeldung.boot.jackson.config.CoffeeConstants.FIXED_DATE; +import com.baeldung.boot.jackson.model.Coffee; @RestController public class CoffeeController { diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/model/Coffee.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/model/Coffee.java similarity index 100% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/model/Coffee.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/model/Coffee.java diff --git a/spring-boot-modules/spring-boot-data-2/src/main/resources/coffee.properties b/spring-boot-modules/spring-boot-data/src/main/resources/coffee.properties similarity index 100% rename from spring-boot-modules/spring-boot-data-2/src/main/resources/coffee.properties rename to spring-boot-modules/spring-boot-data/src/main/resources/coffee.properties diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/AbstractCoffeeIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/AbstractCoffeeIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/AbstractCoffeeIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/AbstractCoffeeIntegrationTest.java index f1bc35a8ce..961ab8979c 100644 --- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/AbstractCoffeeIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/AbstractCoffeeIntegrationTest.java @@ -1,15 +1,16 @@ package com.baeldung.boot.jackson.app; -import com.baeldung.boot.jackson.config.CoffeeConstants; +import static com.baeldung.boot.jackson.config.CoffeeConstants.FIXED_DATE; +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.format.DateTimeFormatter; + import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; -import java.time.format.DateTimeFormatter; - -import static com.baeldung.boot.jackson.config.CoffeeConstants.FIXED_DATE; -import static org.assertj.core.api.Assertions.assertThat; +import com.baeldung.boot.jackson.config.CoffeeConstants; @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public abstract class AbstractCoffeeIntegrationTest { diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeCustomizerIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeCustomizerIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeCustomizerIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeCustomizerIntegrationTest.java index d690de1b9c..ed5baf239c 100644 --- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeCustomizerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeCustomizerIntegrationTest.java @@ -1,8 +1,9 @@ package com.baeldung.boot.jackson.app; -import com.baeldung.boot.jackson.config.CoffeeCustomizerConfig; import org.springframework.context.annotation.Import; +import com.baeldung.boot.jackson.config.CoffeeCustomizerConfig; + @Import(CoffeeCustomizerConfig.class) public class CoffeeCustomizerIntegrationTest extends AbstractCoffeeIntegrationTest { } diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeHttpConverterIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeHttpConverterIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeHttpConverterIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeHttpConverterIntegrationTest.java index 62b1d42152..0c77948d8e 100644 --- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeHttpConverterIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeHttpConverterIntegrationTest.java @@ -1,8 +1,9 @@ package com.baeldung.boot.jackson.app; -import com.baeldung.boot.jackson.config.CoffeeHttpConverterConfiguration; import org.springframework.context.annotation.Import; +import com.baeldung.boot.jackson.config.CoffeeHttpConverterConfiguration; + @Import(CoffeeHttpConverterConfiguration.class) public class CoffeeHttpConverterIntegrationTest extends AbstractCoffeeIntegrationTest { } diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeJacksonBuilderIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeJacksonBuilderIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeJacksonBuilderIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeJacksonBuilderIntegrationTest.java index 52a55394c0..da9251de99 100644 --- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeJacksonBuilderIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeJacksonBuilderIntegrationTest.java @@ -1,8 +1,9 @@ package com.baeldung.boot.jackson.app; -import com.baeldung.boot.jackson.config.CoffeeJacksonBuilderConfig; import org.springframework.context.annotation.Import; +import com.baeldung.boot.jackson.config.CoffeeJacksonBuilderConfig; + @Import(CoffeeJacksonBuilderConfig.class) public class CoffeeJacksonBuilderIntegrationTest extends AbstractCoffeeIntegrationTest { } diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeObjectMapperIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeObjectMapperIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeObjectMapperIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeObjectMapperIntegrationTest.java index 34743ceba5..1226eacbf2 100644 --- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeObjectMapperIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeObjectMapperIntegrationTest.java @@ -1,8 +1,9 @@ package com.baeldung.boot.jackson.app; -import com.baeldung.boot.jackson.config.CoffeeObjectMapperConfig; import org.springframework.context.annotation.Import; +import com.baeldung.boot.jackson.config.CoffeeObjectMapperConfig; + @Import(CoffeeObjectMapperConfig.class) public class CoffeeObjectMapperIntegrationTest extends AbstractCoffeeIntegrationTest { } diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeRegisterModuleIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeRegisterModuleIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeRegisterModuleIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeRegisterModuleIntegrationTest.java index 69bbd5be2a..38dc4a76cd 100644 --- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeRegisterModuleIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeRegisterModuleIntegrationTest.java @@ -1,8 +1,9 @@ package com.baeldung.boot.jackson.app; -import com.baeldung.boot.jackson.config.CoffeeRegisterModuleConfig; import org.springframework.context.annotation.Import; +import com.baeldung.boot.jackson.config.CoffeeRegisterModuleConfig; + @Import(CoffeeRegisterModuleConfig.class) public class CoffeeRegisterModuleIntegrationTest extends AbstractCoffeeIntegrationTest { } diff --git a/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathControllerIntegrationTest.java b/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathControllerIntegrationTest.java index e21223e6ea..c19b3f3694 100644 --- a/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathControllerIntegrationTest.java +++ b/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathControllerIntegrationTest.java @@ -1,5 +1,10 @@ package com.baeldung.spring.cloud.springcloudcontractconsumer.controller; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -13,6 +18,7 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -26,6 +32,36 @@ public class BasicMathControllerIntegrationTest { @Autowired private MockMvc mockMvc; + private static WireMockServer wireMockServer; + + + @BeforeClass + public static void setupClass() { + WireMockConfiguration wireMockConfiguration = WireMockConfiguration.options().port(8090); // Use the same port as in your code + + wireMockServer = new WireMockServer(wireMockConfiguration); + wireMockServer.start(); + } + + @AfterClass + public static void teardownClass() { + wireMockServer.stop(); + } + + @Before + public void setup() { + wireMockServer.stubFor(get(urlEqualTo("/validate/prime-number?number=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("Odd"))); + + wireMockServer.stubFor(get(urlEqualTo("/validate/prime-number?number=2")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("Even"))); + } @Test public void given_WhenPassEvenNumberInQueryParam_ThenReturnEven() throws Exception { diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index f6142cffb0..2d11cc2124 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -149,7 +149,7 @@ org.apache.maven.plugins maven-war-plugin - ${maven.version} + ${maven-war-plugin.version} false @@ -166,7 +166,7 @@ 3.6 2.1.0 3.22.0-GA - 3.2.2 + 3.2.2 \ No newline at end of file diff --git a/spring-core-4/pom.xml b/spring-core-4/pom.xml index 2d11cc701b..fb544e29fd 100644 --- a/spring-core-4/pom.xml +++ b/spring-core-4/pom.xml @@ -74,7 +74,7 @@ org.apache.commons commons-text - ${apache-commons-text.version} + ${commons-text.version} @@ -84,7 +84,7 @@ 4.0.2 4.0.0 1.3.2 - 1.10.0 + 1.10.0 \ No newline at end of file diff --git a/spring-credhub/pom.xml b/spring-credhub/pom.xml index 4604833d0b..defe378b6b 100644 --- a/spring-credhub/pom.xml +++ b/spring-credhub/pom.xml @@ -27,7 +27,7 @@ org.springframework.credhub spring-credhub-starter - 2.2.0 + ${spring-credhub-starter.version} com.google.code.gson @@ -36,8 +36,7 @@ - 8 - 8 + 2.2.0 UTF-8 diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index c6c163d7d1..042e81971f 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -45,6 +45,12 @@ ${cucumber.version} test + + org.junit.vintage + junit-vintage-engine + ${junit-vintage-engine.version} + test + org.apache.commons @@ -54,8 +60,9 @@ - 6.8.0 + 7.14.0 1.3.2 + 5.10.0 \ No newline at end of file diff --git a/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/CucumberOptionsApplication.java b/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/CucumberOptionsApplication.java new file mode 100644 index 0000000000..03082128b3 --- /dev/null +++ b/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/CucumberOptionsApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.cucumberoptions; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CucumberOptionsApplication { + + public static void main(String[] args) { + SpringApplication.run(CucumberOptionsApplication.class, args); + } + +} \ No newline at end of file diff --git a/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java b/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java new file mode 100644 index 0000000000..637dbdb540 --- /dev/null +++ b/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java @@ -0,0 +1,22 @@ +package com.baeldung.cucumberoptions; + +import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HealthCheckController { + + @GetMapping(path = "/v1/status", produces = APPLICATION_JSON_VALUE) + public HttpStatus getV1Status() { + return ResponseEntity.ok().build().getStatusCode(); + } + + @GetMapping(path = "/v2/status", produces = APPLICATION_JSON_VALUE) + public HttpStatus getV2Status() { + return ResponseEntity.ok().build().getStatusCode(); + } +} \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java new file mode 100644 index 0000000000..999adadbef --- /dev/null +++ b/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java @@ -0,0 +1,38 @@ +package com.baeldung.cucumberoptions; + +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +import com.baeldung.SpringIntegrationTest; + +public class HealthCheckStepDefsIntegrationTest extends SpringIntegrationTest { + + private ResponseEntity statusResponse; + + private ResponseEntity doGet(String url) { + return new RestTemplate().getForEntity(url, String.class); + } + + @When("^the client calls /v1/status") + public void checkV1Status() throws Throwable { + statusResponse = doGet("http://localhost:8082/v1/status"); + } + + @When("^the client calls /v2/status") + public void checkV2Status() throws Throwable { + statusResponse = doGet("http://localhost:8082/v2/status"); + } + + @Then("^the client receives (\\d+) status code$") + public void verifyStatusCode(int statusCode) throws Throwable { + final HttpStatus currentStatusCode = statusResponse.getStatusCode(); + assertThat(currentStatusCode.value(), is(statusCode)); + } +} \ No newline at end of file diff --git a/spring-cucumber/src/test/resources/com/baeldung/cucumberoptions/healthcheck.feature b/spring-cucumber/src/test/resources/com/baeldung/cucumberoptions/healthcheck.feature new file mode 100644 index 0000000000..33e07c1add --- /dev/null +++ b/spring-cucumber/src/test/resources/com/baeldung/cucumberoptions/healthcheck.feature @@ -0,0 +1,11 @@ +Feature: healthcheck endpoints can be verified + + @v1 + Scenario: v1 status is healthy + When the client calls /v1/status + Then the client receives 200 status code + + @v2 + Scenario: v2 status is healthy + When the client calls /v2/status + Then the client receives 200 status code diff --git a/spring-cucumber/src/test/resources/cucumber.properties b/spring-cucumber/src/test/resources/cucumber.properties new file mode 100644 index 0000000000..22c3379201 --- /dev/null +++ b/spring-cucumber/src/test/resources/cucumber.properties @@ -0,0 +1 @@ +cucumber.filter.tags=not @v2 \ No newline at end of file diff --git a/spring-ejb-modules/ejb-beans/pom.xml b/spring-ejb-modules/ejb-beans/pom.xml index 6bfbb42a14..94f7963ad6 100644 --- a/spring-ejb-modules/ejb-beans/pom.xml +++ b/spring-ejb-modules/ejb-beans/pom.xml @@ -66,12 +66,12 @@ org.apache.activemq activemq-broker - ${activemq.broker.version} + ${activemq-broker.version} org.apache.activemq.tooling activemq-junit - ${activemq.junit.version} + ${activemq-junit.version} test @@ -187,8 +187,8 @@ 8.2.1.Final 3.2 5.2.3.RELEASE - 5.16.3 - 5.16.3 + 5.16.3 + 5.16.3 2.21.0 2.8 8.2.1.Final diff --git a/spring-kafka-2/pom.xml b/spring-kafka-2/pom.xml index 76a82f6000..0bca20447d 100644 --- a/spring-kafka-2/pom.xml +++ b/spring-kafka-2/pom.xml @@ -53,7 +53,7 @@ org.testcontainers junit-jupiter - ${testcontainers-kafka.version} + ${testcontainers-junit-jupiter.version} test @@ -65,6 +65,7 @@ 1.16.2 + 1.16.2 \ No newline at end of file diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index c013be32e3..7ff7a9710a 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -26,12 +26,12 @@ org.springframework.boot spring-boot-starter-actuator - 3.0.5 + ${spring-boot-starter-actuator.version} io.micrometer micrometer-registry-prometheus - 1.10.5 + ${micrometer-registry-prometheus.version} org.springframework.kafka @@ -90,6 +90,8 @@ + 3.0.5 + 1.10.5 1.16.2 diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index b836a42bca..595cde5109 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -33,7 +33,7 @@ io.katharsis katharsis-spring - ${katharsis.version} + ${katharsis-spring.version} org.apache.commons @@ -132,7 +132,7 @@ - 3.0.2 + 3.0.2 0.9.10 1.6.1 diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index f810159eb7..d96faf3274 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -37,24 +37,16 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - 1.1.5.RELEASE - 11 - 11 \ No newline at end of file diff --git a/spring-pulsar/pom.xml b/spring-pulsar/pom.xml index df1959c84e..05debcab1c 100644 --- a/spring-pulsar/pom.xml +++ b/spring-pulsar/pom.xml @@ -27,7 +27,7 @@ org.springframework.pulsar spring-pulsar-spring-boot-starter - 0.2.0 + ${spring-pulsar-spring-boot-starter.version} @@ -46,4 +46,8 @@ + + 0.2.0 + + diff --git a/spring-reactive-modules/spring-reactive-security/pom.xml b/spring-reactive-modules/spring-reactive-security/pom.xml index bd74202437..cf34b21083 100644 --- a/spring-reactive-modules/spring-reactive-security/pom.xml +++ b/spring-reactive-modules/spring-reactive-security/pom.xml @@ -76,12 +76,12 @@ io.reactivex.rxjava2 rxjava - ${rxjava-version} + ${rxjava.version} io.projectreactor reactor-test - ${project-reactor-test} + ${project-reactor-test.version} test @@ -110,11 +110,11 @@ 1.0.1.RELEASE - 2.1.12 + 2.1.12 1.1.3 1.0 1.0 - 3.1.6.RELEASE + 3.1.6.RELEASE \ No newline at end of file diff --git a/spring-remoting-modules/pom.xml b/spring-remoting-modules/pom.xml index 41d77c2969..8a5990fd1d 100644 --- a/spring-remoting-modules/pom.xml +++ b/spring-remoting-modules/pom.xml @@ -43,16 +43,10 @@ org.apache.maven.plugins maven-compiler-plugin ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - 11 - 11 \ No newline at end of file diff --git a/spring-security-modules/spring-security-core-2/README.md b/spring-security-modules/spring-security-core-2/README.md index 80027ea42f..5f54dc1a50 100644 --- a/spring-security-modules/spring-security-core-2/README.md +++ b/spring-security-modules/spring-security-core-2/README.md @@ -8,7 +8,8 @@ This module contains articles about core Spring Security - [Prevent Cross-Site Scripting (XSS) in a Spring Application](https://www.baeldung.com/spring-prevent-xss) - [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver) - [A Custom Spring SecurityConfigurer](https://www.baeldung.com/spring-security-custom-configurer) - +- [HttpSecurity vs. WebSecurity in Spring Security](https://www.baeldung.com/spring-security-httpsecurity-vs-websecurity) + ### Build the Project `mvn clean install` diff --git a/spring-security-modules/spring-security-core-2/pom.xml b/spring-security-modules/spring-security-core-2/pom.xml index e540d7bc01..5d77098869 100644 --- a/spring-security-modules/spring-security-core-2/pom.xml +++ b/spring-security-modules/spring-security-core-2/pom.xml @@ -15,6 +15,10 @@ ../../parent-boot-2 + + 5.8.4 + + org.springframework.boot @@ -49,6 +53,16 @@ org.springframework.security spring-security-test + + org.springframework.security + spring-security-web + ${spring.security.version} + + + org.springframework.security + spring-security-core + ${spring.security.version} + @@ -100,4 +114,4 @@ - \ No newline at end of file + diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java new file mode 100644 index 0000000000..d6361255e5 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java @@ -0,0 +1,31 @@ +package com.baeldung.httpsecurityvswebsecurity; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class HttpSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + // Given: HttpSecurity configured + + http.authorizeRequests() + .antMatchers("/public/**").permitAll() + .antMatchers("/admin/**").hasRole("ADMIN") + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login") + .permitAll() + .and() + .logout() + .permitAll(); + + // When: Accessing specific URLs + // Then: Access is granted based on defined rules + } +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java new file mode 100644 index 0000000000..46a82918aa --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java @@ -0,0 +1,35 @@ +package com.baeldung.httpsecurityvswebsecurity; + +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; + +@Configuration +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private UserDetailsService userDetailsService; + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth + .userDetailsService(userDetailsService) + .passwordEncoder(new BCryptPasswordEncoder()); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin(); + } +} diff --git a/spring-security-modules/spring-security-core/pom.xml b/spring-security-modules/spring-security-core/pom.xml index 0eb70c0853..03d7030057 100644 --- a/spring-security-modules/spring-security-core/pom.xml +++ b/spring-security-modules/spring-security-core/pom.xml @@ -100,4 +100,4 @@ - \ No newline at end of file + diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java index 07bc22f184..873c28c6a2 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java @@ -49,7 +49,7 @@ public class SessionTimerInterceptorIntegrationTest { .andReturn() .getRequest() .getSession(); - Thread.sleep(51000); + Thread.sleep(5000); mockMvc.perform(get("/auth/foos").session((MockHttpSession) session)) .andExpect(status().is2xxSuccessful()); } diff --git a/spring-shell/pom.xml b/spring-shell/pom.xml index 952920fd1e..24fe5b0fb6 100644 --- a/spring-shell/pom.xml +++ b/spring-shell/pom.xml @@ -28,7 +28,6 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} src/main/webapp false diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index 594eb3dd19..6c49f1f39c 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -34,7 +34,7 @@ jakarta.xml.bind jakarta.xml.bind-api - 4.0.0 + ${jakarta.xml.bind-api.version} @@ -58,7 +58,7 @@ org.codehaus.mojo jaxb2-maven-plugin - 3.1.0 + ${jaxb2-maven-plugin.version} xjc @@ -79,7 +79,7 @@ org.jvnet.jaxb2.maven2 maven-jaxb2-plugin - 0.15.3 + ${maven-jaxb2-plugin.version} @@ -103,5 +103,8 @@ 17 + 4.0.0 + 3.1.0 + 0.15.3 \ No newline at end of file diff --git a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml index c529951b07..b57a014a8f 100644 --- a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml +++ b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml @@ -29,22 +29,22 @@ org.hibernate hibernate-validator - 6.0.10.Final + ${hibernate-validator.version} javax.validation validation-api - 2.0.1.Final + ${validation-api.version} org.openapitools openapi-generator - 3.3.4 + ${openapi-generator.version} com.fasterxml.jackson.core jackson-databind - 2.10.0.pr3 + ${jackson-databind.version} org.springdoc @@ -62,7 +62,7 @@ org.openapitools openapi-generator-maven-plugin - 5.1.0 + ${openapi-generator-maven-plugin.version} @@ -97,6 +97,11 @@ 3.0.0 2.17.1 1.7.0 + 6.0.10.Final + 2.0.1.Final + 3.3.4 + 2.10.0.pr3 + 5.1.0 \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml index f125018fb0..ee2c86238a 100644 --- a/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml @@ -34,55 +34,55 @@ io.swagger swagger-annotations - ${swagger-annotations-version} + ${swagger-annotations.version} com.google.code.findbugs jsr305 - 3.0.2 + ${findbugs-jsr305.version} org.springframework spring-web - ${spring-web-version} + ${spring-web.version} com.fasterxml.jackson.core jackson-core - ${jackson-version} + ${jackson.version} com.fasterxml.jackson.core jackson-annotations - ${jackson-version} + ${jackson.version} com.fasterxml.jackson.core jackson-databind - ${jackson-version} + ${jackson.version} com.fasterxml.jackson.jaxrs jackson-jaxrs-json-provider - ${jackson-version} + ${jackson.version} org.openapitools jackson-databind-nullable - ${jackson-databind-nullable-version} + ${jackson-databind-nullable.version} com.fasterxml.jackson.datatype jackson-datatype-jsr310 - ${jackson-version} + ${jackson.version} com.github.joschi.jackson jackson-datatype-threetenbp - ${jackson-threetenbp-version} + ${jackson-threetenbp.version} @@ -94,7 +94,7 @@ javax.annotation javax.annotation-api - 1.3.2 + ${javax.annotation-api.version} @@ -103,7 +103,7 @@ org.apache.maven.plugins maven-enforcer-plugin - 3.0.0-M1 + ${maven-enforcer-plugin.version} enforce-maven @@ -123,7 +123,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.12 + ${maven-surefire-plugin.version} @@ -154,7 +154,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.2 + ${maven-jar-plugin.version} @@ -169,7 +169,7 @@ org.codehaus.mojo build-helper-maven-plugin - 1.10 + ${build-helper-maven-plugin.version} add_sources @@ -200,7 +200,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.6.1 + ${maven-compiler-plugin.version} 1.8 1.8 @@ -209,7 +209,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.10.4 + ${maven-javadoc-plugin.version} attach-javadocs @@ -222,7 +222,7 @@ org.apache.maven.plugins maven-source-plugin - 2.2.1 + ${maven-source-plugin.version} attach-sources @@ -243,7 +243,7 @@ org.apache.maven.plugins maven-gpg-plugin - 1.5 + ${maven-gpg-plugin.version} sign-artifacts @@ -260,14 +260,25 @@ - 1.5.22 - 4.3.9.RELEASE - 2.11.1 + 1.5.22 + 4.3.9.RELEASE + 3.0.2 + 2.11.1 - 0.2.1 - 2.9.10 - 1.0.0 + 0.2.1 + 2.9.10 + 1.0.0 5.8.1 + 1.3.2 + + 3.0.0-M1 + 2.12 + 2.2 + 1.10 + 3.6.1 + 2.10.4 + 2.2.1 + 1.5 \ No newline at end of file diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml index b2e97c7a49..35f4978411 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -40,13 +40,13 @@ io.swagger swagger-annotations - ${swagger-annotations-version} + ${swagger-annotations.version} org.springframework spring-web - ${spring-web-version} + ${spring-web.version} @@ -77,12 +77,12 @@ joda-time joda-time - ${jodatime-version} + ${jodatime.version} javax.annotation javax.annotation-api - 1.3.2 + ${javax.annotation-api.version} @@ -189,9 +189,10 @@ - 1.5.15 - 4.3.9.RELEASE - 2.9.9 + 1.5.15 + 4.3.9.RELEASE + 2.9.9 + 1.3.2 2.2 1.5 2.2.1 diff --git a/spring-vault/pom.xml b/spring-vault/pom.xml index 60a5ee18f2..b3690c7b7f 100644 --- a/spring-vault/pom.xml +++ b/spring-vault/pom.xml @@ -36,7 +36,7 @@ org.springframework.vault spring-vault-core - ${spring.vault.core.version} + ${spring-vault-core.version} org.springframework.data @@ -69,18 +69,20 @@ software.amazon.awssdk auth - 2.20.140 + ${auth.version} org.springframework.cloud spring-cloud-starter-vault-config - 3.1.3 + ${spring-cloud-starter-vault-config.version} - 2.3.4 + 2.3.4 + 2.20.140 + 3.1.3 17 diff --git a/spring-web-modules/pom.xml b/spring-web-modules/pom.xml index 9f03b83392..2be896ad83 100644 --- a/spring-web-modules/pom.xml +++ b/spring-web-modules/pom.xml @@ -10,8 +10,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 diff --git a/spring-web-modules/spring-mvc-xml-2/pom.xml b/spring-web-modules/spring-mvc-xml-2/pom.xml index f4326ccf68..8c0062f538 100644 --- a/spring-web-modules/spring-mvc-xml-2/pom.xml +++ b/spring-web-modules/spring-mvc-xml-2/pom.xml @@ -19,12 +19,12 @@ org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -64,7 +64,7 @@ org.springframework.boot spring-boot-starter-test - ${spring-boot.version} + ${spring-boot-starter-test.version} test @@ -95,8 +95,6 @@ - 5.0.2.RELEASE - 1.5.10.RELEASE 5.1.40 4.4.5 4.5.2 diff --git a/testing-modules/testing-libraries-2/README.md b/testing-modules/testing-libraries-2/README.md index 9e17da96a7..a37612e207 100644 --- a/testing-modules/testing-libraries-2/README.md +++ b/testing-modules/testing-libraries-2/README.md @@ -7,3 +7,4 @@ - [Gray Box Testing Using the OAT Technique](https://www.baeldung.com/java-gray-box-orthogonal-array-testing) - [Unit Testing of System.in With JUnit](https://www.baeldung.com/java-junit-testing-system-in) - [Fail Maven Build if JUnit Coverage Falls Below Certain Threshold](https://www.baeldung.com/maven-junit-fail-build-coverage-threshold) +- [How to Mock Environment Variables in Unit Tests](https://www.baeldung.com/java-unit-testing-environment-variables) diff --git a/grails/.gitignore b/web-modules/grails/.gitignore similarity index 100% rename from grails/.gitignore rename to web-modules/grails/.gitignore diff --git a/grails/README.md b/web-modules/grails/README.md similarity index 100% rename from grails/README.md rename to web-modules/grails/README.md diff --git a/grails/build.gradle b/web-modules/grails/build.gradle similarity index 100% rename from grails/build.gradle rename to web-modules/grails/build.gradle diff --git a/grails/gradle.properties b/web-modules/grails/gradle.properties similarity index 100% rename from grails/gradle.properties rename to web-modules/grails/gradle.properties diff --git a/grails/gradle/wrapper/gradle-wrapper.properties b/web-modules/grails/gradle/wrapper/gradle-wrapper.properties similarity index 100% rename from grails/gradle/wrapper/gradle-wrapper.properties rename to web-modules/grails/gradle/wrapper/gradle-wrapper.properties diff --git a/grails/gradlew b/web-modules/grails/gradlew similarity index 100% rename from grails/gradlew rename to web-modules/grails/gradlew diff --git a/grails/gradlew.bat b/web-modules/grails/gradlew.bat similarity index 100% rename from grails/gradlew.bat rename to web-modules/grails/gradlew.bat diff --git a/grails/grails-app/assets/images/apple-touch-icon-retina.png b/web-modules/grails/grails-app/assets/images/apple-touch-icon-retina.png similarity index 100% rename from grails/grails-app/assets/images/apple-touch-icon-retina.png rename to web-modules/grails/grails-app/assets/images/apple-touch-icon-retina.png diff --git a/grails/grails-app/assets/images/apple-touch-icon.png b/web-modules/grails/grails-app/assets/images/apple-touch-icon.png similarity index 100% rename from grails/grails-app/assets/images/apple-touch-icon.png rename to web-modules/grails/grails-app/assets/images/apple-touch-icon.png diff --git a/grails/grails-app/assets/images/favicon.ico b/web-modules/grails/grails-app/assets/images/favicon.ico similarity index 100% rename from grails/grails-app/assets/images/favicon.ico rename to web-modules/grails/grails-app/assets/images/favicon.ico diff --git a/grails/grails-app/assets/images/grails-cupsonly-logo-white.svg b/web-modules/grails/grails-app/assets/images/grails-cupsonly-logo-white.svg similarity index 100% rename from grails/grails-app/assets/images/grails-cupsonly-logo-white.svg rename to web-modules/grails/grails-app/assets/images/grails-cupsonly-logo-white.svg diff --git a/grails/grails-app/assets/images/grails.svg b/web-modules/grails/grails-app/assets/images/grails.svg similarity index 100% rename from grails/grails-app/assets/images/grails.svg rename to web-modules/grails/grails-app/assets/images/grails.svg diff --git a/grails/grails-app/assets/images/skin/database_add.png b/web-modules/grails/grails-app/assets/images/skin/database_add.png similarity index 100% rename from grails/grails-app/assets/images/skin/database_add.png rename to web-modules/grails/grails-app/assets/images/skin/database_add.png diff --git a/grails/grails-app/assets/images/skin/database_delete.png b/web-modules/grails/grails-app/assets/images/skin/database_delete.png similarity index 100% rename from grails/grails-app/assets/images/skin/database_delete.png rename to web-modules/grails/grails-app/assets/images/skin/database_delete.png diff --git a/grails/grails-app/assets/images/skin/database_edit.png b/web-modules/grails/grails-app/assets/images/skin/database_edit.png similarity index 100% rename from grails/grails-app/assets/images/skin/database_edit.png rename to web-modules/grails/grails-app/assets/images/skin/database_edit.png diff --git a/grails/grails-app/assets/images/skin/database_save.png b/web-modules/grails/grails-app/assets/images/skin/database_save.png similarity index 100% rename from grails/grails-app/assets/images/skin/database_save.png rename to web-modules/grails/grails-app/assets/images/skin/database_save.png diff --git a/grails/grails-app/assets/images/skin/database_table.png b/web-modules/grails/grails-app/assets/images/skin/database_table.png similarity index 100% rename from grails/grails-app/assets/images/skin/database_table.png rename to web-modules/grails/grails-app/assets/images/skin/database_table.png diff --git a/grails/grails-app/assets/images/skin/exclamation.png b/web-modules/grails/grails-app/assets/images/skin/exclamation.png similarity index 100% rename from grails/grails-app/assets/images/skin/exclamation.png rename to web-modules/grails/grails-app/assets/images/skin/exclamation.png diff --git a/grails/grails-app/assets/images/skin/house.png b/web-modules/grails/grails-app/assets/images/skin/house.png similarity index 100% rename from grails/grails-app/assets/images/skin/house.png rename to web-modules/grails/grails-app/assets/images/skin/house.png diff --git a/grails/grails-app/assets/images/skin/information.png b/web-modules/grails/grails-app/assets/images/skin/information.png similarity index 100% rename from grails/grails-app/assets/images/skin/information.png rename to web-modules/grails/grails-app/assets/images/skin/information.png diff --git a/grails/grails-app/assets/images/skin/shadow.jpg b/web-modules/grails/grails-app/assets/images/skin/shadow.jpg similarity index 100% rename from grails/grails-app/assets/images/skin/shadow.jpg rename to web-modules/grails/grails-app/assets/images/skin/shadow.jpg diff --git a/grails/grails-app/assets/images/skin/sorted_asc.gif b/web-modules/grails/grails-app/assets/images/skin/sorted_asc.gif similarity index 100% rename from grails/grails-app/assets/images/skin/sorted_asc.gif rename to web-modules/grails/grails-app/assets/images/skin/sorted_asc.gif diff --git a/grails/grails-app/assets/images/skin/sorted_desc.gif b/web-modules/grails/grails-app/assets/images/skin/sorted_desc.gif similarity index 100% rename from grails/grails-app/assets/images/skin/sorted_desc.gif rename to web-modules/grails/grails-app/assets/images/skin/sorted_desc.gif diff --git a/grails/grails-app/assets/images/spinner.gif b/web-modules/grails/grails-app/assets/images/spinner.gif similarity index 100% rename from grails/grails-app/assets/images/spinner.gif rename to web-modules/grails/grails-app/assets/images/spinner.gif diff --git a/grails/grails-app/assets/javascripts/application.js b/web-modules/grails/grails-app/assets/javascripts/application.js similarity index 100% rename from grails/grails-app/assets/javascripts/application.js rename to web-modules/grails/grails-app/assets/javascripts/application.js diff --git a/grails/grails-app/assets/javascripts/bootstrap.js b/web-modules/grails/grails-app/assets/javascripts/bootstrap.js similarity index 100% rename from grails/grails-app/assets/javascripts/bootstrap.js rename to web-modules/grails/grails-app/assets/javascripts/bootstrap.js diff --git a/grails/grails-app/assets/javascripts/jquery-2.2.0.min.js b/web-modules/grails/grails-app/assets/javascripts/jquery-2.2.0.min.js similarity index 100% rename from grails/grails-app/assets/javascripts/jquery-2.2.0.min.js rename to web-modules/grails/grails-app/assets/javascripts/jquery-2.2.0.min.js diff --git a/grails/grails-app/assets/stylesheets/application.css b/web-modules/grails/grails-app/assets/stylesheets/application.css similarity index 100% rename from grails/grails-app/assets/stylesheets/application.css rename to web-modules/grails/grails-app/assets/stylesheets/application.css diff --git a/grails/grails-app/assets/stylesheets/bootstrap.css b/web-modules/grails/grails-app/assets/stylesheets/bootstrap.css similarity index 100% rename from grails/grails-app/assets/stylesheets/bootstrap.css rename to web-modules/grails/grails-app/assets/stylesheets/bootstrap.css diff --git a/grails/grails-app/assets/stylesheets/errors.css b/web-modules/grails/grails-app/assets/stylesheets/errors.css similarity index 100% rename from grails/grails-app/assets/stylesheets/errors.css rename to web-modules/grails/grails-app/assets/stylesheets/errors.css diff --git a/grails/grails-app/assets/stylesheets/grails.css b/web-modules/grails/grails-app/assets/stylesheets/grails.css similarity index 100% rename from grails/grails-app/assets/stylesheets/grails.css rename to web-modules/grails/grails-app/assets/stylesheets/grails.css diff --git a/grails/grails-app/assets/stylesheets/main.css b/web-modules/grails/grails-app/assets/stylesheets/main.css similarity index 100% rename from grails/grails-app/assets/stylesheets/main.css rename to web-modules/grails/grails-app/assets/stylesheets/main.css diff --git a/grails/grails-app/assets/stylesheets/mobile.css b/web-modules/grails/grails-app/assets/stylesheets/mobile.css similarity index 100% rename from grails/grails-app/assets/stylesheets/mobile.css rename to web-modules/grails/grails-app/assets/stylesheets/mobile.css diff --git a/grails/grails-app/conf/application.yml b/web-modules/grails/grails-app/conf/application.yml similarity index 100% rename from grails/grails-app/conf/application.yml rename to web-modules/grails/grails-app/conf/application.yml diff --git a/grails/grails-app/conf/logback.groovy b/web-modules/grails/grails-app/conf/logback.groovy similarity index 100% rename from grails/grails-app/conf/logback.groovy rename to web-modules/grails/grails-app/conf/logback.groovy diff --git a/grails/grails-app/conf/spring/resources.groovy b/web-modules/grails/grails-app/conf/spring/resources.groovy similarity index 100% rename from grails/grails-app/conf/spring/resources.groovy rename to web-modules/grails/grails-app/conf/spring/resources.groovy diff --git a/grails/grails-app/controllers/com/baeldung/grails/StudentController.groovy b/web-modules/grails/grails-app/controllers/com/baeldung/grails/StudentController.groovy similarity index 100% rename from grails/grails-app/controllers/com/baeldung/grails/StudentController.groovy rename to web-modules/grails/grails-app/controllers/com/baeldung/grails/StudentController.groovy diff --git a/grails/grails-app/controllers/grails/UrlMappings.groovy b/web-modules/grails/grails-app/controllers/grails/UrlMappings.groovy similarity index 100% rename from grails/grails-app/controllers/grails/UrlMappings.groovy rename to web-modules/grails/grails-app/controllers/grails/UrlMappings.groovy diff --git a/grails/grails-app/domain/com/baeldung/grails/Student.groovy b/web-modules/grails/grails-app/domain/com/baeldung/grails/Student.groovy similarity index 100% rename from grails/grails-app/domain/com/baeldung/grails/Student.groovy rename to web-modules/grails/grails-app/domain/com/baeldung/grails/Student.groovy diff --git a/grails/grails-app/i18n/messages.properties b/web-modules/grails/grails-app/i18n/messages.properties similarity index 100% rename from grails/grails-app/i18n/messages.properties rename to web-modules/grails/grails-app/i18n/messages.properties diff --git a/grails/grails-app/i18n/messages_cs.properties b/web-modules/grails/grails-app/i18n/messages_cs.properties similarity index 100% rename from grails/grails-app/i18n/messages_cs.properties rename to web-modules/grails/grails-app/i18n/messages_cs.properties diff --git a/grails/grails-app/i18n/messages_da.properties b/web-modules/grails/grails-app/i18n/messages_da.properties similarity index 100% rename from grails/grails-app/i18n/messages_da.properties rename to web-modules/grails/grails-app/i18n/messages_da.properties diff --git a/grails/grails-app/i18n/messages_de.properties b/web-modules/grails/grails-app/i18n/messages_de.properties similarity index 100% rename from grails/grails-app/i18n/messages_de.properties rename to web-modules/grails/grails-app/i18n/messages_de.properties diff --git a/grails/grails-app/i18n/messages_es.properties b/web-modules/grails/grails-app/i18n/messages_es.properties similarity index 100% rename from grails/grails-app/i18n/messages_es.properties rename to web-modules/grails/grails-app/i18n/messages_es.properties diff --git a/grails/grails-app/i18n/messages_fr.properties b/web-modules/grails/grails-app/i18n/messages_fr.properties similarity index 100% rename from grails/grails-app/i18n/messages_fr.properties rename to web-modules/grails/grails-app/i18n/messages_fr.properties diff --git a/grails/grails-app/i18n/messages_it.properties b/web-modules/grails/grails-app/i18n/messages_it.properties similarity index 100% rename from grails/grails-app/i18n/messages_it.properties rename to web-modules/grails/grails-app/i18n/messages_it.properties diff --git a/grails/grails-app/i18n/messages_ja.properties b/web-modules/grails/grails-app/i18n/messages_ja.properties similarity index 100% rename from grails/grails-app/i18n/messages_ja.properties rename to web-modules/grails/grails-app/i18n/messages_ja.properties diff --git a/grails/grails-app/i18n/messages_nb.properties b/web-modules/grails/grails-app/i18n/messages_nb.properties similarity index 100% rename from grails/grails-app/i18n/messages_nb.properties rename to web-modules/grails/grails-app/i18n/messages_nb.properties diff --git a/grails/grails-app/i18n/messages_nl.properties b/web-modules/grails/grails-app/i18n/messages_nl.properties similarity index 100% rename from grails/grails-app/i18n/messages_nl.properties rename to web-modules/grails/grails-app/i18n/messages_nl.properties diff --git a/grails/grails-app/i18n/messages_pl.properties b/web-modules/grails/grails-app/i18n/messages_pl.properties similarity index 100% rename from grails/grails-app/i18n/messages_pl.properties rename to web-modules/grails/grails-app/i18n/messages_pl.properties diff --git a/grails/grails-app/i18n/messages_pt_BR.properties b/web-modules/grails/grails-app/i18n/messages_pt_BR.properties similarity index 100% rename from grails/grails-app/i18n/messages_pt_BR.properties rename to web-modules/grails/grails-app/i18n/messages_pt_BR.properties diff --git a/grails/grails-app/i18n/messages_pt_PT.properties b/web-modules/grails/grails-app/i18n/messages_pt_PT.properties similarity index 100% rename from grails/grails-app/i18n/messages_pt_PT.properties rename to web-modules/grails/grails-app/i18n/messages_pt_PT.properties diff --git a/grails/grails-app/i18n/messages_ru.properties b/web-modules/grails/grails-app/i18n/messages_ru.properties similarity index 100% rename from grails/grails-app/i18n/messages_ru.properties rename to web-modules/grails/grails-app/i18n/messages_ru.properties diff --git a/grails/grails-app/i18n/messages_sk.properties b/web-modules/grails/grails-app/i18n/messages_sk.properties similarity index 100% rename from grails/grails-app/i18n/messages_sk.properties rename to web-modules/grails/grails-app/i18n/messages_sk.properties diff --git a/grails/grails-app/i18n/messages_sv.properties b/web-modules/grails/grails-app/i18n/messages_sv.properties similarity index 100% rename from grails/grails-app/i18n/messages_sv.properties rename to web-modules/grails/grails-app/i18n/messages_sv.properties diff --git a/grails/grails-app/i18n/messages_th.properties b/web-modules/grails/grails-app/i18n/messages_th.properties similarity index 100% rename from grails/grails-app/i18n/messages_th.properties rename to web-modules/grails/grails-app/i18n/messages_th.properties diff --git a/grails/grails-app/i18n/messages_zh_CN.properties b/web-modules/grails/grails-app/i18n/messages_zh_CN.properties similarity index 100% rename from grails/grails-app/i18n/messages_zh_CN.properties rename to web-modules/grails/grails-app/i18n/messages_zh_CN.properties diff --git a/grails/grails-app/init/grails/Application.groovy b/web-modules/grails/grails-app/init/grails/Application.groovy similarity index 100% rename from grails/grails-app/init/grails/Application.groovy rename to web-modules/grails/grails-app/init/grails/Application.groovy diff --git a/grails/grails-app/init/grails/BootStrap.groovy b/web-modules/grails/grails-app/init/grails/BootStrap.groovy similarity index 100% rename from grails/grails-app/init/grails/BootStrap.groovy rename to web-modules/grails/grails-app/init/grails/BootStrap.groovy diff --git a/grails/grails-app/services/com/baeldung/grails/StudentService.groovy b/web-modules/grails/grails-app/services/com/baeldung/grails/StudentService.groovy similarity index 100% rename from grails/grails-app/services/com/baeldung/grails/StudentService.groovy rename to web-modules/grails/grails-app/services/com/baeldung/grails/StudentService.groovy diff --git a/grails/grails-app/views/error.gsp b/web-modules/grails/grails-app/views/error.gsp similarity index 100% rename from grails/grails-app/views/error.gsp rename to web-modules/grails/grails-app/views/error.gsp diff --git a/grails/grails-app/views/index.gsp b/web-modules/grails/grails-app/views/index.gsp similarity index 100% rename from grails/grails-app/views/index.gsp rename to web-modules/grails/grails-app/views/index.gsp diff --git a/grails/grails-app/views/layouts/main.gsp b/web-modules/grails/grails-app/views/layouts/main.gsp similarity index 100% rename from grails/grails-app/views/layouts/main.gsp rename to web-modules/grails/grails-app/views/layouts/main.gsp diff --git a/grails/grails-app/views/notFound.gsp b/web-modules/grails/grails-app/views/notFound.gsp similarity index 100% rename from grails/grails-app/views/notFound.gsp rename to web-modules/grails/grails-app/views/notFound.gsp diff --git a/grails/grails-app/views/student/create.gsp b/web-modules/grails/grails-app/views/student/create.gsp similarity index 100% rename from grails/grails-app/views/student/create.gsp rename to web-modules/grails/grails-app/views/student/create.gsp diff --git a/grails/grails-app/views/student/index.gsp b/web-modules/grails/grails-app/views/student/index.gsp similarity index 100% rename from grails/grails-app/views/student/index.gsp rename to web-modules/grails/grails-app/views/student/index.gsp diff --git a/grails/grails-app/views/student/show.gsp b/web-modules/grails/grails-app/views/student/show.gsp similarity index 100% rename from grails/grails-app/views/student/show.gsp rename to web-modules/grails/grails-app/views/student/show.gsp diff --git a/grails/grailsw b/web-modules/grails/grailsw similarity index 100% rename from grails/grailsw rename to web-modules/grails/grailsw diff --git a/grails/grailsw.bat b/web-modules/grails/grailsw.bat similarity index 100% rename from grails/grailsw.bat rename to web-modules/grails/grailsw.bat diff --git a/grails/src/integration-test/groovy/com/baeldung/grails/StudentIntegrationSpec.groovy b/web-modules/grails/src/integration-test/groovy/com/baeldung/grails/StudentIntegrationSpec.groovy similarity index 100% rename from grails/src/integration-test/groovy/com/baeldung/grails/StudentIntegrationSpec.groovy rename to web-modules/grails/src/integration-test/groovy/com/baeldung/grails/StudentIntegrationSpec.groovy diff --git a/grails/src/integration-test/resources/GebConfig.groovy b/web-modules/grails/src/integration-test/resources/GebConfig.groovy similarity index 100% rename from grails/src/integration-test/resources/GebConfig.groovy rename to web-modules/grails/src/integration-test/resources/GebConfig.groovy diff --git a/grails/src/test/groovy/com/baeldung/grails/StudentControllerSpec.groovy b/web-modules/grails/src/test/groovy/com/baeldung/grails/StudentControllerSpec.groovy similarity index 100% rename from grails/src/test/groovy/com/baeldung/grails/StudentControllerSpec.groovy rename to web-modules/grails/src/test/groovy/com/baeldung/grails/StudentControllerSpec.groovy diff --git a/web-modules/pom.xml b/web-modules/pom.xml index 684283b546..57810f90de 100644 --- a/web-modules/pom.xml +++ b/web-modules/pom.xml @@ -19,6 +19,7 @@ bootique dropwizard google-web-toolkit + jakarta-ee javax-servlets diff --git a/xml-2/pom.xml b/xml-2/pom.xml index 7d10f36042..0f94588ba0 100644 --- a/xml-2/pom.xml +++ b/xml-2/pom.xml @@ -46,6 +46,16 @@ underscore ${underscore.version} + + org.apache.xmlbeans + xmlbeans + 5.0.2 + + + org.apache.logging.log4j + log4j-core + 2.12.4 + @@ -74,4 +84,4 @@ 1.89 - \ No newline at end of file + diff --git a/xml-2/src/main/resources/log4j2.xml b/xml-2/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..f022ab633b --- /dev/null +++ b/xml-2/src/main/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/xml-2/src/test/java/com/baeldung/xml/xml2document/XMLStringToDocumentObjectUnitTest.java b/xml-2/src/test/java/com/baeldung/xml/xml2document/XMLStringToDocumentObjectUnitTest.java new file mode 100644 index 0000000000..f573e1c96d --- /dev/null +++ b/xml-2/src/test/java/com/baeldung/xml/xml2document/XMLStringToDocumentObjectUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.xml2document; + +import org.junit.Test; +import org.w3c.dom.*; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import java.io.IOException; +import java.io.StringReader; + +import static org.junit.Assert.assertEquals; + +public class XMLStringToDocumentObjectUnitTest { + @Test + public void givenValidXMLString_whenParsing_thenDocumentIsCorrect() throws ParserConfigurationException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + String xmlString = "XML Parsing Example"; + InputSource is = new InputSource(new StringReader(xmlString)); + Document xmlDoc = null; + try { + xmlDoc = builder.parse(is); + } catch (SAXException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + + assertEquals("root", xmlDoc.getDocumentElement().getNodeName()); + assertEquals("element", xmlDoc.getDocumentElement().getElementsByTagName("element").item(0).getNodeName()); + assertEquals("XML Parsing Example", xmlDoc.getDocumentElement().getElementsByTagName("element").item(0).getTextContent()); + } +} diff --git a/xml-2/src/test/java/com/baeldung/xml/xml2string/XMLObjectToStringUnitTest.java b/xml-2/src/test/java/com/baeldung/xml/xml2string/XMLObjectToStringUnitTest.java new file mode 100644 index 0000000000..0afa3424f3 --- /dev/null +++ b/xml-2/src/test/java/com/baeldung/xml/xml2string/XMLObjectToStringUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.xml2string; + +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Test; +import org.junit.Before; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.StringWriter; + +import static org.junit.Assert.assertTrue; + +public class XMLObjectToStringUnitTest { + private Document document; + + @Before + public void setup() throws ParserConfigurationException { +// Create a DocumentBuilder + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + +// Create a new Document + document = builder.newDocument(); + +// Create the root element + Element rootElement = document.createElement("root"); + document.appendChild(rootElement); + +// Create child elements + Element childElement1 = document.createElement("child1"); + Element childElement2 = document.createElement("child2"); + +// Add text content to the child elements + childElement1.appendChild(document.createTextNode("This is child element 1")); + childElement2.appendChild(document.createTextNode("This is child element 2")); + +// Append child elements to the root element + rootElement.appendChild(childElement1); + rootElement.appendChild(childElement2); + } + + @Test + public void givenXMLDocument_whenUsingTransformer_thenConvertXMLToString() throws TransformerException { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + StringWriter stringWriter = new StringWriter(); + transformer.transform(new DOMSource(document), new StreamResult(stringWriter)); + String result = stringWriter.toString(); + + assertTrue(result.contains("")); + assertTrue(result.contains("This is child element 1")); + assertTrue(result.contains("This is child element 2")); + } + + @Test + public void givenXMLDocument_whenUsingXmlBeans_thenConvertXMLToString() { + try { + + XmlObject xmlObject = XmlObject.Factory.parse(document); + + XmlOptions options = new XmlOptions(); + options.setSavePrettyPrint(); + options.setUseDefaultNamespace(); + options.setSaveAggressiveNamespaces(); + + String xmlString = xmlObject.xmlText(options); + + xmlString = "" + xmlString; + + assertTrue(xmlString.contains("")); + assertTrue(xmlString.contains("This is child element 1")); + assertTrue(xmlString.contains("This is child element 2")); + } catch (XmlException e) { + e.printStackTrace(); + } + } +}