From 2922f0619f280b23209dafe18abc49015d206b3a Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Sat, 16 Mar 2024 23:21:47 +0530 Subject: [PATCH 01/23] Create SetMatrixToZero.java --- .../matrixToZero/SetMatrixToZero.java | 115 ++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixToZero/SetMatrixToZero.java diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixToZero/SetMatrixToZero.java b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixToZero/SetMatrixToZero.java new file mode 100644 index 0000000000..d195698299 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixToZero/SetMatrixToZero.java @@ -0,0 +1,115 @@ +package com.baeldung.matrixToZero; + +import java.util.*; + +public class SetMatrixToZero{ + static void setZeroesBruteForce(int[][] matrix) { + int row = matrix.length; + int col = matrix[0].length; + int [][] result = new int[row][col]; + + for(int i = 0; i rowSet = new HashSet<>(); + Set colSet = new HashSet<>(); + + for(int i = 0; i < rows; i++){ + for(int j = 0; j < cols; j++){ + if (matrix[i][j] == 0){ + rowSet.add(i); + colSet.add(j); + } + } + } + for(int row: rowSet){ + for(int j = 0; j < cols; j++){ + matrix[row][j] = 0; + } + } + for(int col: colSet) { + for(int i = 0; i < rows; i++){ + matrix[i][col] = 0; + } + } + } + static void setZeroesOptimized(int[][] matrix){ + int rows = matrix.length; + int cols = matrix[0].length; + + boolean firstRowZero = false; + boolean firstColZero = false; + + for(int j = 0; j < cols; j++){ + if (matrix[0][j] == 0) { + firstRowZero = true; + break; + } + } + + for(int i = 0; i < rows; i++){ + if (matrix[i][0] == 0) { + firstColZero = true; + break; + } + } + for(int i = 1; i < rows; i++){ + for(int j = 1; j < cols; j++){ + if (matrix[i][j] == 0){ + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for(int i = 1; i < rows; i++){ + if(matrix[i][0] == 0){ + for(int j = 1; j < cols; j++){ + matrix[i][j] = 0; + } + } + } + for(int j = 1; j < cols; j++){ + if(matrix[0][j] == 0) { + for(int i = 1; i < rows; i++){ + matrix[i][j] = 0; + } + } + } + if(firstRowZero){ + for(int j = 0; j < cols; j++){ + matrix[0][j] = 0; + } + } + if(firstColZero){ + for(int i = 0; i < rows; i++){ + matrix[i][0] = 0; + } + } + } +} From f88022796a6dd2ec5fb475c049b09e35ab22a883 Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Sat, 16 Mar 2024 23:32:11 +0530 Subject: [PATCH 02/23] Create SetMatrixToZeroUnitTest.java --- .../matrixtozero/SetMatrixToZeroUnitTest.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/matrixtozero/SetMatrixToZeroUnitTest.java diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/matrixtozero/SetMatrixToZeroUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/matrixtozero/SetMatrixToZeroUnitTest.java new file mode 100644 index 0000000000..e144c90ba7 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/matrixtozero/SetMatrixToZeroUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.matrixtozero; + +import org.junit.Test; + +public class SetMatrixToZeroUnitTest{ + @Test + void givenMatrix_whenUsingBruteForce_thenSetZeroes() { + int[][] matrix = { + {1, 2, 3}, + {4, 0, 6}, + {7, 8, 9} + }; + int[][] expected = { + {1, 0, 3}, + {0, 0, 0}, + {7, 0, 9} + }; + SetMatrixToZero.setZeroesBruteForce(matrix); + assertArrayEquals(expected, matrix); + } + + @Test + void givenMatrix_whenUsingExtraSpace_thenSetZeroes() { + int[][] matrix = { + {1, 2, 3}, + {4, 0, 6}, + {7, 8, 9} + }; + int[][] expected = { + {1, 0, 3}, + {0, 0, 0}, + {7, 0, 9} + }; + SetMatrixToZero.setZeroesExtraSpace(matrix); + assertArrayEquals(expected, matrix); + } + + @Test + void givenMatrix_whenUsingOptimized_thenSetZeroes() { + int[][] matrix = { + {1, 2, 3}, + {4, 0, 6}, + {7, 8, 9} + }; + int[][] expected = { + {1, 0, 3}, + {0, 0, 0}, + {7, 0, 9} + }; + SetMatrixToZero.setZeroesOptimized(matrix); + assertArrayEquals(expected, matrix); + } +} From 44aab189871e0f5a113d8c7e4d8ab94e95e34e3f Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Sat, 16 Mar 2024 23:34:03 +0530 Subject: [PATCH 03/23] Delete core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixToZero directory --- .../matrixToZero/SetMatrixToZero.java | 115 ------------------ 1 file changed, 115 deletions(-) delete mode 100644 core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixToZero/SetMatrixToZero.java diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixToZero/SetMatrixToZero.java b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixToZero/SetMatrixToZero.java deleted file mode 100644 index d195698299..0000000000 --- a/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixToZero/SetMatrixToZero.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.baeldung.matrixToZero; - -import java.util.*; - -public class SetMatrixToZero{ - static void setZeroesBruteForce(int[][] matrix) { - int row = matrix.length; - int col = matrix[0].length; - int [][] result = new int[row][col]; - - for(int i = 0; i rowSet = new HashSet<>(); - Set colSet = new HashSet<>(); - - for(int i = 0; i < rows; i++){ - for(int j = 0; j < cols; j++){ - if (matrix[i][j] == 0){ - rowSet.add(i); - colSet.add(j); - } - } - } - for(int row: rowSet){ - for(int j = 0; j < cols; j++){ - matrix[row][j] = 0; - } - } - for(int col: colSet) { - for(int i = 0; i < rows; i++){ - matrix[i][col] = 0; - } - } - } - static void setZeroesOptimized(int[][] matrix){ - int rows = matrix.length; - int cols = matrix[0].length; - - boolean firstRowZero = false; - boolean firstColZero = false; - - for(int j = 0; j < cols; j++){ - if (matrix[0][j] == 0) { - firstRowZero = true; - break; - } - } - - for(int i = 0; i < rows; i++){ - if (matrix[i][0] == 0) { - firstColZero = true; - break; - } - } - for(int i = 1; i < rows; i++){ - for(int j = 1; j < cols; j++){ - if (matrix[i][j] == 0){ - matrix[i][0] = 0; - matrix[0][j] = 0; - } - } - } - for(int i = 1; i < rows; i++){ - if(matrix[i][0] == 0){ - for(int j = 1; j < cols; j++){ - matrix[i][j] = 0; - } - } - } - for(int j = 1; j < cols; j++){ - if(matrix[0][j] == 0) { - for(int i = 1; i < rows; i++){ - matrix[i][j] = 0; - } - } - } - if(firstRowZero){ - for(int j = 0; j < cols; j++){ - matrix[0][j] = 0; - } - } - if(firstColZero){ - for(int i = 0; i < rows; i++){ - matrix[i][0] = 0; - } - } - } -} From 576925e862aa776462ac113958bfced34aa9bcd5 Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Sat, 16 Mar 2024 23:36:32 +0530 Subject: [PATCH 04/23] Create SetMatrixToZero.java --- .../matrixtozero/SetMatrixToZero.java | 115 ++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java new file mode 100644 index 0000000000..46d24b0d38 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java @@ -0,0 +1,115 @@ +package com.baeldung.matrixtozero; + +import java.util.*; + +public class SetMatrixToZero{ + static void setZeroesBruteForce(int[][] matrix) { + int row = matrix.length; + int col = matrix[0].length; + int [][] result = new int[row][col]; + + for(int i = 0; i rowSet = new HashSet<>(); + Set colSet = new HashSet<>(); + + for(int i = 0; i < rows; i++){ + for(int j = 0; j < cols; j++){ + if (matrix[i][j] == 0){ + rowSet.add(i); + colSet.add(j); + } + } + } + for(int row: rowSet){ + for(int j = 0; j < cols; j++){ + matrix[row][j] = 0; + } + } + for(int col: colSet) { + for(int i = 0; i < rows; i++){ + matrix[i][col] = 0; + } + } + } + static void setZeroesOptimized(int[][] matrix){ + int rows = matrix.length; + int cols = matrix[0].length; + + boolean firstRowZero = false; + boolean firstColZero = false; + + for(int j = 0; j < cols; j++){ + if (matrix[0][j] == 0) { + firstRowZero = true; + break; + } + } + + for(int i = 0; i < rows; i++){ + if (matrix[i][0] == 0) { + firstColZero = true; + break; + } + } + for(int i = 1; i < rows; i++){ + for(int j = 1; j < cols; j++){ + if (matrix[i][j] == 0){ + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for(int i = 1; i < rows; i++){ + if(matrix[i][0] == 0){ + for(int j = 1; j < cols; j++){ + matrix[i][j] = 0; + } + } + } + for(int j = 1; j < cols; j++){ + if(matrix[0][j] == 0) { + for(int i = 1; i < rows; i++){ + matrix[i][j] = 0; + } + } + } + if(firstRowZero){ + for(int j = 0; j < cols; j++){ + matrix[0][j] = 0; + } + } + if(firstColZero){ + for(int i = 0; i < rows; i++){ + matrix[i][0] = 0; + } + } + } +} From 9d0024b92645418d41607284cb4c9293f8c07f0f Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Sat, 16 Mar 2024 23:49:41 +0530 Subject: [PATCH 05/23] Apply formatting --- .../java/com/baeldung/matrixtozero/SetMatrixToZero.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java index 46d24b0d38..6362f3672c 100644 --- a/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java +++ b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java @@ -33,6 +33,7 @@ public class SetMatrixToZero{ } } } + static void setZeroesExtraSpace(int[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; @@ -48,17 +49,20 @@ public class SetMatrixToZero{ } } } + for(int row: rowSet){ for(int j = 0; j < cols; j++){ matrix[row][j] = 0; } } + for(int col: colSet) { for(int i = 0; i < rows; i++){ matrix[i][col] = 0; } } } + static void setZeroesOptimized(int[][] matrix){ int rows = matrix.length; int cols = matrix[0].length; @@ -79,6 +83,7 @@ public class SetMatrixToZero{ break; } } + for(int i = 1; i < rows; i++){ for(int j = 1; j < cols; j++){ if (matrix[i][j] == 0){ @@ -87,6 +92,7 @@ public class SetMatrixToZero{ } } } + for(int i = 1; i < rows; i++){ if(matrix[i][0] == 0){ for(int j = 1; j < cols; j++){ @@ -94,6 +100,7 @@ public class SetMatrixToZero{ } } } + for(int j = 1; j < cols; j++){ if(matrix[0][j] == 0) { for(int i = 1; i < rows; i++){ @@ -101,11 +108,13 @@ public class SetMatrixToZero{ } } } + if(firstRowZero){ for(int j = 0; j < cols; j++){ matrix[0][j] = 0; } } + if(firstColZero){ for(int i = 0; i < rows; i++){ matrix[i][0] = 0; From cd5a95f764b70f58a2a2f36a65aa34d4ff79ce77 Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Sun, 17 Mar 2024 01:10:47 +0530 Subject: [PATCH 06/23] Included import statements in Test file --- .../com/baeldung/matrixtozero/SetMatrixToZeroUnitTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/matrixtozero/SetMatrixToZeroUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/matrixtozero/SetMatrixToZeroUnitTest.java index e144c90ba7..ba8d53a11f 100644 --- a/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/matrixtozero/SetMatrixToZeroUnitTest.java +++ b/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/matrixtozero/SetMatrixToZeroUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.matrixtozero; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import org.junit.jupiter.api.Test; public class SetMatrixToZeroUnitTest{ @Test From e73a578dbdc343997f189dae3bab267a939ef104 Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Tue, 2 Apr 2024 22:14:45 +0530 Subject: [PATCH 07/23] Update method names --- .../java/com/baeldung/matrixtozero/SetMatrixToZero.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java index 6362f3672c..778a5d6ce5 100644 --- a/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java +++ b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java @@ -3,7 +3,7 @@ package com.baeldung.matrixtozero; import java.util.*; public class SetMatrixToZero{ - static void setZeroesBruteForce(int[][] matrix) { + static void setZeroesByNaiveApproach(int[][] matrix) { int row = matrix.length; int col = matrix[0].length; int [][] result = new int[row][col]; @@ -34,7 +34,7 @@ public class SetMatrixToZero{ } } - static void setZeroesExtraSpace(int[][] matrix) { + static void setZeroesByTimeOptimizedApproach(int[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; @@ -63,7 +63,7 @@ public class SetMatrixToZero{ } } - static void setZeroesOptimized(int[][] matrix){ + static void setZeroesByOptimalApproach(int[][] matrix){ int rows = matrix.length; int cols = matrix[0].length; From dbd9448e99db9b1e3440c6f579e3e53333bde4f0 Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Tue, 2 Apr 2024 22:14:57 +0530 Subject: [PATCH 08/23] Update method names --- .../matrixtozero/SetMatrixToZeroUnitTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/matrixtozero/SetMatrixToZeroUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/matrixtozero/SetMatrixToZeroUnitTest.java index ba8d53a11f..ee4996457e 100644 --- a/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/matrixtozero/SetMatrixToZeroUnitTest.java +++ b/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/matrixtozero/SetMatrixToZeroUnitTest.java @@ -5,7 +5,7 @@ import org.junit.jupiter.api.Test; public class SetMatrixToZeroUnitTest{ @Test - void givenMatrix_whenUsingBruteForce_thenSetZeroes() { + void givenMatrix_whenUsingSetZeroesByNaiveApproach_thenSetZeroes() { int[][] matrix = { {1, 2, 3}, {4, 0, 6}, @@ -16,12 +16,12 @@ public class SetMatrixToZeroUnitTest{ {0, 0, 0}, {7, 0, 9} }; - SetMatrixToZero.setZeroesBruteForce(matrix); + SetMatrixToZero.setZeroesByNaiveApproach(matrix); assertArrayEquals(expected, matrix); } @Test - void givenMatrix_whenUsingExtraSpace_thenSetZeroes() { + void givenMatrix_whenUsingSetZeroesByTimeOptimizedApproach_thenSetZeroes() { int[][] matrix = { {1, 2, 3}, {4, 0, 6}, @@ -32,12 +32,12 @@ public class SetMatrixToZeroUnitTest{ {0, 0, 0}, {7, 0, 9} }; - SetMatrixToZero.setZeroesExtraSpace(matrix); + SetMatrixToZero.setZeroesByTimeOptimizedApproach(matrix); assertArrayEquals(expected, matrix); } @Test - void givenMatrix_whenUsingOptimized_thenSetZeroes() { + void givenMatrix_whenUsingSetZeroesByOptimalApproach_thenSetZeroes() { int[][] matrix = { {1, 2, 3}, {4, 0, 6}, @@ -48,7 +48,7 @@ public class SetMatrixToZeroUnitTest{ {0, 0, 0}, {7, 0, 9} }; - SetMatrixToZero.setZeroesOptimized(matrix); + SetMatrixToZero.setZeroesByOptimalApproach(matrix); assertArrayEquals(expected, matrix); } } From 306d2da98c9f66ab25fe2d1efb942cfbe74692b9 Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Tue, 9 Apr 2024 23:18:22 +0530 Subject: [PATCH 09/23] Update SetMatrixToZero.java --- .../matrixtozero/SetMatrixToZero.java | 107 +++++++++++------- 1 file changed, 65 insertions(+), 42 deletions(-) diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java index 778a5d6ce5..57c558caa7 100644 --- a/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java +++ b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixtozero/SetMatrixToZero.java @@ -61,64 +61,87 @@ public class SetMatrixToZero{ matrix[i][col] = 0; } } - } - - static void setZeroesByOptimalApproach(int[][] matrix){ - int rows = matrix.length; - int cols = matrix[0].length; + } - boolean firstRowZero = false; - boolean firstColZero = false; - - for(int j = 0; j < cols; j++){ + static boolean hasZeroInFirstRow(int[][] matrix, int cols) { + for (int j = 0; j < cols; j++) { if (matrix[0][j] == 0) { - firstRowZero = true; - break; + return true; } } + return false; + } - for(int i = 0; i < rows; i++){ + static boolean hasZeroInFirstCol(int[][] matrix, int rows) { + for (int i = 0; i < rows; i++) { if (matrix[i][0] == 0) { - firstColZero = true; - break; + return true; } } - - for(int i = 1; i < rows; i++){ - for(int j = 1; j < cols; j++){ - if (matrix[i][j] == 0){ + return false; + } + + static void markZeroesInMatrix(int[][] matrix, int rows, int cols) { + for (int i = 1; i < rows; i++) { + for (int j = 1; j < cols; j++) { + if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } - - for(int i = 1; i < rows; i++){ - if(matrix[i][0] == 0){ - for(int j = 1; j < cols; j++){ + } + + static void setZeroesInRows(int[][] matrix, int rows, int cols) { + for (int i = 1; i < rows; i++) { + if (matrix[i][0] == 0) { + for (int j = 1; j < cols; j++) { matrix[i][j] = 0; } } } - - for(int j = 1; j < cols; j++){ - if(matrix[0][j] == 0) { - for(int i = 1; i < rows; i++){ - matrix[i][j] = 0; - } - } - } - - if(firstRowZero){ - for(int j = 0; j < cols; j++){ - matrix[0][j] = 0; - } - } - - if(firstColZero){ - for(int i = 0; i < rows; i++){ - matrix[i][0] = 0; - } - } } + + static void setZeroesInCols(int[][] matrix, int rows, int cols) { + for (int j = 1; j < cols; j++) { + if (matrix[0][j] == 0) { + for (int i = 1; i < rows; i++) { + matrix[i][j] = 0; + } + } + } + } + + static void setZeroesInFirstRow(int[][] matrix, int cols) { + for (int j = 0; j < cols; j++) { + matrix[0][j] = 0; + } + } + + static void setZeroesInFirstCol(int[][] matrix, int rows) { + for (int i = 0; i < rows; i++) { + matrix[i][0] = 0; + } + } + + static void setZeroesByOptimalApproach(int[][] matrix) { + int rows = matrix.length; + int cols = matrix[0].length; + + boolean firstRowZero = hasZeroInFirstRow(matrix, cols); + boolean firstColZero = hasZeroInFirstCol(matrix, rows); + + markZeroesInMatrix(matrix, rows, cols); + + setZeroesInRows(matrix, rows, cols); + setZeroesInCols(matrix, rows, cols); + + if (firstRowZero) { + setZeroesInFirstRow(matrix, cols); + } + if (firstColZero) { + setZeroesInFirstCol(matrix, rows); + } + } + } From 2a8e5bb69def5e142afd6e9a952656c1187a6ec6 Mon Sep 17 00:00:00 2001 From: "Kai.Yuan" Date: Wed, 10 Apr 2024 21:59:56 +0200 Subject: [PATCH 10/23] [fix-merging-overlapping] fix --- .../MergeOverlappingIntervals.java | 18 +++++------ .../MergeIntervalsUnitTest.java | 32 ++++++++++++------- 2 files changed, 28 insertions(+), 22 deletions(-) diff --git a/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/mergeintervals/MergeOverlappingIntervals.java b/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/mergeintervals/MergeOverlappingIntervals.java index ba424772d5..ec7081bec7 100644 --- a/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/mergeintervals/MergeOverlappingIntervals.java +++ b/algorithms-modules/algorithms-miscellaneous-8/src/main/java/com/baeldung/algorithms/mergeintervals/MergeOverlappingIntervals.java @@ -1,23 +1,22 @@ package com.baeldung.algorithms.mergeintervals; +import static java.lang.Integer.max; + import java.util.ArrayList; +import java.util.Comparator; import java.util.List; public class MergeOverlappingIntervals { public List doMerge(List intervals) { - // Sort the intervals based on start time - intervals.sort((one, two) -> one.start - two.start); - - // Create somewhere to put the merged list, start it off with the earliest starting interval + intervals.sort(Comparator.comparingInt(interval -> interval.start)); ArrayList merged = new ArrayList<>(); merged.add(intervals.get(0)); - // Loop over each interval and merge if start time is before the end time of the - // previous interval intervals.forEach(interval -> { - if (merged.get(merged.size() - 1).end > interval.start) { - merged.get(merged.size() - 1).setEnd(interval.end); + Interval lastMerged = merged.get(merged.size() - 1); + if (interval.start <= lastMerged.end){ + lastMerged.setEnd(max(interval.end, lastMerged.end)); } else { merged.add(interval); } @@ -25,5 +24,4 @@ public class MergeOverlappingIntervals { return merged; } - -} +} \ No newline at end of file diff --git a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/mergeintervals/MergeIntervalsUnitTest.java b/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/mergeintervals/MergeIntervalsUnitTest.java index 5f15fe00f6..2d8a94dca4 100644 --- a/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/mergeintervals/MergeIntervalsUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/mergeintervals/MergeIntervalsUnitTest.java @@ -1,30 +1,38 @@ package com.baeldung.algorithms.mergeintervals; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import org.junit.jupiter.api.Test; class MergeIntervalsUnitTest { - private ArrayList intervals = new ArrayList<>(Arrays.asList( - new Interval(2, 5), - new Interval(13, 20), - new Interval(11, 15), - new Interval(1, 3) + private List intervals = new ArrayList<>(Arrays.asList( + // @formatter:off + new Interval(3, 5), + new Interval(13, 20), + new Interval(11, 15), + new Interval(15, 16), + new Interval(1, 3), + new Interval(4, 5), + new Interval(16, 17) + // @formatter:on )); - private ArrayList intervalsMerged = new ArrayList<>(Arrays.asList( - new Interval(1, 5), - new Interval(11, 20) + private List intervalsMerged = new ArrayList<>(Arrays.asList( + // @formatter:off + new Interval(1, 5), + new Interval(11, 20) + // @formatter:on )); @Test void givenIntervals_whenMerging_thenReturnMergedIntervals() { MergeOverlappingIntervals merger = new MergeOverlappingIntervals(); - ArrayList result = (ArrayList) merger.doMerge(intervals); - assertArrayEquals(intervalsMerged.toArray(), result.toArray()); + List result = merger.doMerge(intervals); + assertEquals(intervalsMerged, result); } -} +} \ No newline at end of file From de1f1c50b8ce0dc9c885f9f75d914823197e7cb1 Mon Sep 17 00:00:00 2001 From: Maiklins Date: Sat, 13 Apr 2024 12:32:13 +0200 Subject: [PATCH 11/23] Update README.md --- .../core-java-arrays-operations-advanced-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/README.md b/core-java-modules/core-java-arrays-operations-advanced-2/README.md index e762508bcd..2df723e9c9 100644 --- a/core-java-modules/core-java-arrays-operations-advanced-2/README.md +++ b/core-java-modules/core-java-arrays-operations-advanced-2/README.md @@ -3,3 +3,4 @@ - [Find the Equilibrium Indexes of an Array in Java](https://www.baeldung.com/java-equilibrium-index-array) - [Moves Zeros to the End of an Array in Java](https://www.baeldung.com/java-array-sort-move-zeros-end) - [Finding the Majority Element of an Array in Java](https://www.baeldung.com/java-array-find-majority-element) +- [Set Matrix Elements to Zero in Java](https://www.baeldung.com/java-set-matrix-elements-to-zero) From e9758956957612ee00ab3a76e7c4be2514458a09 Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Sat, 13 Apr 2024 22:48:50 +0200 Subject: [PATCH 12/23] This PR is related to BAEL-5998 (#16384) * This commit is related to BAEL-5998 This commit aims to add a class named "Employee". * This commit is related to BAEL-5998 This commit aims to add a test class titled "PrintingNullValuesUnitTest". * Update PrintingNullValuesUnitTest.java --- .../baeldung/printnullvalues/Employee.java | 44 +++++++++++++++++++ .../PrintingNullValuesUnitTest.java | 30 +++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/printnullvalues/Employee.java create mode 100644 core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/printnullvalues/PrintingNullValuesUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/printnullvalues/Employee.java b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/printnullvalues/Employee.java new file mode 100644 index 0000000000..b4cd62897b --- /dev/null +++ b/core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/printnullvalues/Employee.java @@ -0,0 +1,44 @@ +package com.baeldung.printnullvalues; + +import java.util.Objects; +import java.util.Optional; + +public class Employee { + private String name; + private int age; + private String department; + + public Employee(String name, int age, String department) { + this.name = name; + this.age = age; + this.department = department; + } + + public String toStringUsingNullCheck() { + return "Name: " + (name != null ? name : "Unknown") + + ", Age: " + age + + ", Department: " + (department != null ? department : "Unknown"); + } + + public String toStringUsingOptional() { + return "Name: " + Optional.ofNullable(name).orElse("Unknown") + + ", Age: " + age + + ", Department: " + Optional.ofNullable(department).orElse("Unknown"); + } + + private String getDefaultIfNull(String value, String defaultValue) { + return value != null ? value : defaultValue; + } + + public String toStringUsingCustomHelper() { + return "Name: " + getDefaultIfNull(name, "Unknown") + + ", Age: " + age + + ", Department: " + getDefaultIfNull(department, "Unknown"); + } + + public String toStringUsingObjects() { + return "Name: " + Objects.toString(name, "Unknown") + + ", Age: " + age + + ", Department: " + Objects.toString(department, "Unknown"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/printnullvalues/PrintingNullValuesUnitTest.java b/core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/printnullvalues/PrintingNullValuesUnitTest.java new file mode 100644 index 0000000000..7526cd9ac4 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/printnullvalues/PrintingNullValuesUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.printnullvalues; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class PrintingNullValuesUnitTest { + Employee employee = new Employee(null, 30, null); + String expected = "Name: Unknown, Age: 30, Department: Unknown"; + + @Test + public void givenNullValues_whenToStringUsingNullCheck_thenCorrectStringReturned() { + assertEquals(expected, employee.toStringUsingNullCheck()); + } + + @Test + public void givenNullValues_whenToStringUsingOptional_thenCorrectStringReturned() { + assertEquals(expected, employee.toStringUsingOptional()); + } + + @Test + public void givenNullValues_whenToStringUsingCustomHelper_thenCorrectStringReturned() { + assertEquals(expected, employee.toStringUsingCustomHelper()); + } + + @Test + public void givenNullValues_whenToStringUsingObjects_thenCorrectStringReturned() { + assertEquals(expected, employee.toStringUsingObjects()); + } +} From 977071357e594c1806d2c8f4c11e3b775683622d Mon Sep 17 00:00:00 2001 From: Alexandru Borza Date: Sat, 13 Apr 2024 23:50:11 +0300 Subject: [PATCH 13/23] BAEL-7615 - Implement the Builder Pattern in Java 8 (#16399) * BAEL-7255 - Implementing GraphQL Mutation without Returning Data * BAEL-7615 - Implement the Builder Pattern in Java 8 * BAEL-7615 - Implement the Builder Pattern in Java 8 --- .../design-patterns-creational-2/pom.xml | 7 +- .../implementation/GenericBuilder.java | 29 ++++++++ .../builder/implementation/LombokPost.java | 18 +++++ .../baeldung/builder/implementation/Post.java | 74 +++++++++++++++++++ .../BuilderImplementationUnitTest.java | 50 +++++++++++++ 5 files changed, 177 insertions(+), 1 deletion(-) create mode 100644 patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/builder/implementation/GenericBuilder.java create mode 100644 patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/builder/implementation/LombokPost.java create mode 100644 patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/builder/implementation/Post.java create mode 100644 patterns-modules/design-patterns-creational-2/src/test/java/com/baeldung/builder/implementation/BuilderImplementationUnitTest.java diff --git a/patterns-modules/design-patterns-creational-2/pom.xml b/patterns-modules/design-patterns-creational-2/pom.xml index 30e052e6db..bfb8f3ff7c 100644 --- a/patterns-modules/design-patterns-creational-2/pom.xml +++ b/patterns-modules/design-patterns-creational-2/pom.xml @@ -19,10 +19,15 @@ ${mockito-inline.version} test + + org.projectlombok + lombok + 1.18.32 + 5.2.0 - \ No newline at end of file + diff --git a/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/builder/implementation/GenericBuilder.java b/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/builder/implementation/GenericBuilder.java new file mode 100644 index 0000000000..6159f92189 --- /dev/null +++ b/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/builder/implementation/GenericBuilder.java @@ -0,0 +1,29 @@ +package com.baeldung.builder.implementation; + +import java.util.function.BiConsumer; +import java.util.function.Supplier; + +public class GenericBuilder { + + private final Supplier supplier; + + private GenericBuilder(Supplier supplier) { + this.supplier = supplier; + } + + public static GenericBuilder of(Supplier supplier) { + return new GenericBuilder<>(supplier); + } + + public

GenericBuilder with(BiConsumer consumer, P value) { + return new GenericBuilder<>(() -> { + T object = supplier.get(); + consumer.accept(object, value); + return object; + }); + } + + public T build() { + return supplier.get(); + } +} diff --git a/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/builder/implementation/LombokPost.java b/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/builder/implementation/LombokPost.java new file mode 100644 index 0000000000..76edf2390c --- /dev/null +++ b/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/builder/implementation/LombokPost.java @@ -0,0 +1,18 @@ +package com.baeldung.builder.implementation; + +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +@Builder +@Getter +@Setter +public class LombokPost { + + private String title; + + private String text; + + private String category; + +} diff --git a/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/builder/implementation/Post.java b/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/builder/implementation/Post.java new file mode 100644 index 0000000000..621618a0e6 --- /dev/null +++ b/patterns-modules/design-patterns-creational-2/src/main/java/com/baeldung/builder/implementation/Post.java @@ -0,0 +1,74 @@ +package com.baeldung.builder.implementation; + +public class Post { + + private String title; + + private String text; + + private String category; + + Post(Builder builder) { + this.title = builder.title; + this.text = builder.text; + this.category = builder.category; + } + + Post() {} + + public String getTitle() { + return title; + } + + public String getText() { + return text; + } + + public String getCategory() { + return category; + } + + public void setTitle(String title) { + this.title = title; + } + + public void setText(String text) { + this.text = text; + } + + public void setCategory(String category) { + this.category = category; + } + + @Override + public String toString() { + return "Post{" + "title='" + title + '\'' + ", text='" + text + '\'' + ", category='" + category + '\'' + '}'; + } + + public static class Builder { + private String title; + private String text; + private String category; + + public Builder() {} + + public Builder title(String title) { + this.title = title; + return this; + } + + public Builder text(String text) { + this.text = text; + return this; + } + + public Builder category(String category) { + this.category = category; + return this; + } + + public Post build() { + return new Post(this); + } + } +} diff --git a/patterns-modules/design-patterns-creational-2/src/test/java/com/baeldung/builder/implementation/BuilderImplementationUnitTest.java b/patterns-modules/design-patterns-creational-2/src/test/java/com/baeldung/builder/implementation/BuilderImplementationUnitTest.java new file mode 100644 index 0000000000..e05d4f476a --- /dev/null +++ b/patterns-modules/design-patterns-creational-2/src/test/java/com/baeldung/builder/implementation/BuilderImplementationUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.builder.implementation; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class BuilderImplementationUnitTest { + + @Test + void givenClassicBuilder_whenBuild_thenReturnObject() { + + Post post = new Post.Builder() + .title("Java Builder Pattern") + .text("Explaining how to implement the Builder Pattern in Java") + .category("Programming") + .build(); + + assertEquals("Java Builder Pattern", post.getTitle()); + assertEquals("Explaining how to implement the Builder Pattern in Java", post.getText()); + assertEquals("Programming", post.getCategory()); + } + + @Test + void givenGenericBuilder_whenBuild_thenReturnObject() { + + Post post = GenericBuilder.of(Post::new) + .with(Post::setTitle, "Java Builder Pattern") + .with(Post::setText, "Explaining how to implement the Builder Pattern in Java") + .with(Post::setCategory, "Programming") + .build(); + + assertEquals("Java Builder Pattern", post.getTitle()); + assertEquals("Explaining how to implement the Builder Pattern in Java", post.getText()); + assertEquals("Programming", post.getCategory()); + } + + @Test + void givenLombokBuilder_whenBuild_thenReturnObject() { + + LombokPost post = LombokPost.builder() + .title("Java Builder Pattern") + .text("Explaining how to implement the Builder Pattern in Java") + .category("Programming") + .build(); + + assertEquals("Java Builder Pattern", post.getTitle()); + assertEquals("Explaining how to implement the Builder Pattern in Java", post.getText()); + assertEquals("Programming", post.getCategory()); + } +} From eaf222dfa069b92b1ee6b6ae0143e15448e35bc3 Mon Sep 17 00:00:00 2001 From: DiegoMarti2 <150871541+DiegoMarti2@users.noreply.github.com> Date: Sat, 13 Apr 2024 22:53:03 +0200 Subject: [PATCH 14/23] baeldung-articles : BAEL-6484 (#16398) * updating the pom.xml file Here i add a new module networking-5 * baeldung-articles : BAEL-6484 Finding the Redirected URL of a URL in Java. --- .../core-java-networking-5/README.md | 2 + .../core-java-networking-5/pom.xml | 59 +++++++++++++++++++ .../redirectedurl/RedirectedUrlUnitTest.java | 57 ++++++++++++++++++ core-java-modules/pom.xml | 1 + 4 files changed, 119 insertions(+) create mode 100644 core-java-modules/core-java-networking-5/README.md create mode 100644 core-java-modules/core-java-networking-5/pom.xml create mode 100644 core-java-modules/core-java-networking-5/src/test/java/com/baeldung/redirectedurl/RedirectedUrlUnitTest.java diff --git a/core-java-modules/core-java-networking-5/README.md b/core-java-modules/core-java-networking-5/README.md new file mode 100644 index 0000000000..5d69c73138 --- /dev/null +++ b/core-java-modules/core-java-networking-5/README.md @@ -0,0 +1,2 @@ +## Relevant Articles: +- [[<-- Prev]](/core-java-modules/core-java-networking-4) diff --git a/core-java-modules/core-java-networking-5/pom.xml b/core-java-modules/core-java-networking-5/pom.xml new file mode 100644 index 0000000000..978a294204 --- /dev/null +++ b/core-java-modules/core-java-networking-5/pom.xml @@ -0,0 +1,59 @@ + + + 4.0.0 + core-java-networking-5 + jar + core-java-networking-5 + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + commons-validator + commons-validator + ${commons-validator.version} + + + org.jsoup + jsoup + ${jsoup.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + javax.ws.rs + javax.ws.rs-api + ${javax.ws.rs-api.version} + + + org.glassfish.jersey.core + jersey-common + ${jersey-common.version} + test + + + org.springframework + spring-web + ${spring-web.version} + + + + + 1.7 + 1.17.2 + 4.5.2 + 2.1.1 + 2.22.2 + 6.0.6 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-networking-5/src/test/java/com/baeldung/redirectedurl/RedirectedUrlUnitTest.java b/core-java-modules/core-java-networking-5/src/test/java/com/baeldung/redirectedurl/RedirectedUrlUnitTest.java new file mode 100644 index 0000000000..1fc1dc3699 --- /dev/null +++ b/core-java-modules/core-java-networking-5/src/test/java/com/baeldung/redirectedurl/RedirectedUrlUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.redirectedurl; + +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.junit.Test; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +import static org.junit.Assert.assertEquals; + +public class RedirectedUrlUnitTest { + String canonicalUrl = "http://www.baeldung.com/"; + String expectedRedirectedUrl = "https://www.baeldung.com/"; + + @Test + public void givenOriginalUrl_whenFindRedirectUrlUsingHttpURLConnection_thenCorrectRedirectedUrlReturned() throws IOException { + URL url = new URL(canonicalUrl); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setInstanceFollowRedirects(true); + int status = connection.getResponseCode(); + String redirectedUrl = null; + if (status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_MOVED_TEMP) { + redirectedUrl = connection.getHeaderField("Location"); + } + connection.disconnect(); + assertEquals(expectedRedirectedUrl, redirectedUrl); + } + + @Test + public void givenOriginalUrl_whenFindRedirectUrlUsingHttpClient_thenCorrectRedirectedUrlReturned() throws IOException { + RequestConfig config = RequestConfig.custom() + .setRedirectsEnabled(false) + .build(); + try (CloseableHttpClient httpClient = HttpClients.custom() + .setDefaultRequestConfig(config) + .build()) { + HttpGet httpGet = new HttpGet(canonicalUrl); + try (CloseableHttpResponse response = httpClient.execute(httpGet)) { + int statusCode = response.getStatusLine().getStatusCode(); + String redirectedUrl = null; + if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) { + org.apache.http.Header[] headers = response.getHeaders("Location"); + if (headers.length > 0) { + redirectedUrl = headers[0].getValue(); + } + } + assertEquals(expectedRedirectedUrl, redirectedUrl); + } + } + } + +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index f6c5f8191a..00c40151e4 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -165,6 +165,7 @@ core-java-networking core-java-networking-2 core-java-networking-4 + core-java-networking-5 core-java-nio core-java-nio-2 core-java-numbers From 4d6b46699c38b3984a000e21218928370b05aa29 Mon Sep 17 00:00:00 2001 From: Usman Mohyuddin Date: Sun, 14 Apr 2024 01:58:24 +0500 Subject: [PATCH 15/23] Feature/spring data mongodb skip and limit (#16285) * mongo repo with @Aggregation in skip & limit * add tests for skip & limit in MongoRepository * cleanup * fix spaces * use BDD naming conventions --- .../baeldung/projection/model/Student.java | 36 ++++++++ .../repository/StudentRepository.java | 32 +++++++ .../projection/StudentIntegrationTest.java | 90 +++++++++++++++++++ 3 files changed, 158 insertions(+) create mode 100644 persistence-modules/spring-data-mongodb-2/src/main/java/com/baeldung/projection/model/Student.java create mode 100644 persistence-modules/spring-data-mongodb-2/src/main/java/com/baeldung/projection/repository/StudentRepository.java create mode 100644 persistence-modules/spring-data-mongodb-2/src/test/java/com/baeldung/projection/StudentIntegrationTest.java diff --git a/persistence-modules/spring-data-mongodb-2/src/main/java/com/baeldung/projection/model/Student.java b/persistence-modules/spring-data-mongodb-2/src/main/java/com/baeldung/projection/model/Student.java new file mode 100644 index 0000000000..5560d9c689 --- /dev/null +++ b/persistence-modules/spring-data-mongodb-2/src/main/java/com/baeldung/projection/model/Student.java @@ -0,0 +1,36 @@ +package com.baeldung.projection.model; + +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document(collection = "student") +public class Student { + @Id + private String id; + private String name; + private Long age; + + public Student(String id, String name, Long age) { + this.id = id; + this.name = name; + this.age = age; + } + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public Long getAge() { + return age; + } + public void setAge(Long age) { + this.age = age; + } +} diff --git a/persistence-modules/spring-data-mongodb-2/src/main/java/com/baeldung/projection/repository/StudentRepository.java b/persistence-modules/spring-data-mongodb-2/src/main/java/com/baeldung/projection/repository/StudentRepository.java new file mode 100644 index 0000000000..ec148400a9 --- /dev/null +++ b/persistence-modules/spring-data-mongodb-2/src/main/java/com/baeldung/projection/repository/StudentRepository.java @@ -0,0 +1,32 @@ +package com.baeldung.projection.repository; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.mongodb.repository.Aggregation; +import org.springframework.data.mongodb.repository.MongoRepository; + +import com.baeldung.projection.model.Student; + +import java.util.List; + +public interface StudentRepository extends MongoRepository { + @Aggregation(pipeline = { + "{ '$skip': ?0 }", + "{ '$limit': ?1 }" + }) + List findAll(Long skip, Long limit); + @Aggregation(pipeline = { + "{ '$match': { 'age': ?0 } }", + "{ $skip: ?1 }", + "{ $limit: ?2 }" + }) + List findAllByAgeCriteria(Long age, Long skip, Long limit); + @Aggregation(pipeline = { + "{ '$match': { 'id' : ?0 } }", + "{ '$sort' : { 'id' : 1 } }", + "{ '$skip' : ?1 }", + "{ '$limit' : ?2 }" + }) + List findByStudentId(final String studentId, Long skip, Long limit); + Page findAll(Pageable pageable); +} diff --git a/persistence-modules/spring-data-mongodb-2/src/test/java/com/baeldung/projection/StudentIntegrationTest.java b/persistence-modules/spring-data-mongodb-2/src/test/java/com/baeldung/projection/StudentIntegrationTest.java new file mode 100644 index 0000000000..ac68a2db32 --- /dev/null +++ b/persistence-modules/spring-data-mongodb-2/src/test/java/com/baeldung/projection/StudentIntegrationTest.java @@ -0,0 +1,90 @@ +package com.baeldung.projection; + +import com.baeldung.projection.config.ProjectionConfig; +import com.baeldung.projection.model.Student; +import com.baeldung.projection.repository.StudentRepository; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ProjectionConfig.class) +public class StudentIntegrationTest { + @Autowired + private StudentRepository studentRepository; + private List studentList; + + @Before + public void setUp() { + Student student1 = new Student("A", "Abraham", 15L); + Student student2 = new Student("B", "Usman", 30L); + Student student3 = new Student("C", "David", 20L); + Student student4 = new Student("D", "Tina", 45L); + Student student5 = new Student("E", "Maria", 33L); + + studentList = Arrays.asList(student1, student2, student3, student4, student5); + studentRepository.saveAll(studentList); + } + + @Test + public void whenRetrievingAllStudents_thenReturnsCorrectNumberOfRecords() { + // WHEN + List result = studentRepository.findAll(0L, 5L); + // THEN + assertEquals(5, result.size()); + } + + @Test + public void whenLimitingAndSkipping_thenReturnsLimitedStudents() { + // WHEN + List result = studentRepository.findAll(3L, 2L); + // THEN + assertEquals(2, result.size()); + assertEquals("Tina", result.get(0).getName()); + assertEquals("Maria", result.get(1).getName()); + } + + @Test + public void whenFilteringByAge_thenReturnsStudentsMatchingCriteria() { + // WHEN + List result = studentRepository.findAllByAgeCriteria(30L, 0L, 10L); + // THEN + assertEquals(1, result.size()); + assertEquals("Usman", result.get(0).getName()); + } + + @Test + public void whenFindingById_thenReturnsMatchingStudent() { + // WHEN + List result = studentRepository.findByStudentId("A", 0L, 5L); + // THEN + assertEquals(1, result.size()); + assertEquals("Abraham", result.get(0).getName()); + } + + @Test + public void whenFindByStudentIdUsingPageable_thenReturnsPageOfStudents() { + // GIVEN + Sort sort = Sort.by(Sort.Direction.DESC, "id"); + Pageable pageable = PageRequest.of(0, 5, sort); + + // WHEN + Page resultPage = studentRepository.findAll(pageable); + + // THEN + assertEquals(5, resultPage.getTotalElements()); + assertEquals("Maria", resultPage.getContent().get(0).getName()); + } +} \ No newline at end of file From f18a5c4472de49bc1fd1d3a276ee4df087604f7e Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Sat, 13 Apr 2024 23:54:45 +0200 Subject: [PATCH 16/23] JAVA-33535: Fix errors after mockito upgrade. (#16389) * Fix eureka-client * Fix eureka-server * Fix spring-cloud-zuul * Fix spring-reactive-data-couchbase * Fix and cleanup apache-poi --- .../execution/ApplicationRunnerTaskExecutor.java | 6 ++++-- .../runner/execution/CommandLineTaskExecutor.java | 4 ++-- .../application/runner/execution/TaskService.java | 4 ++-- .../execution/RunApplicationIntegrationTest.java | 13 +++++-------- .../eureka-client/pom.xml | 10 ++++++++++ .../eureka-server/pom.xml | 10 ++++++++++ spring-cloud-modules/spring-cloud-zuul/pom.xml | 7 +++++++ .../spring-reactive-data-couchbase/pom.xml | 7 +++++++ 8 files changed, 47 insertions(+), 14 deletions(-) diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationRunnerTaskExecutor.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationRunnerTaskExecutor.java index 3bf08491bf..8143b97f94 100644 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationRunnerTaskExecutor.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationRunnerTaskExecutor.java @@ -14,14 +14,16 @@ import org.springframework.stereotype.Component; matchIfMissing = true) @Component public class ApplicationRunnerTaskExecutor implements ApplicationRunner { - private TaskService taskService; + + private final TaskService taskService; public ApplicationRunnerTaskExecutor(TaskService taskService) { this.taskService = taskService; } @Override - public void run(ApplicationArguments args) throws Exception { + public void run(ApplicationArguments args) { taskService.execute("application runner task"); } + } diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/CommandLineTaskExecutor.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/CommandLineTaskExecutor.java index 38fd3b9c0a..0dd26eed8a 100644 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/CommandLineTaskExecutor.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/CommandLineTaskExecutor.java @@ -13,14 +13,14 @@ import org.springframework.stereotype.Component; matchIfMissing = true) @Component public class CommandLineTaskExecutor implements CommandLineRunner { - private TaskService taskService; + private final TaskService taskService; public CommandLineTaskExecutor(TaskService taskService) { this.taskService = taskService; } @Override - public void run(String... args) throws Exception { + public void run(String... args) { taskService.execute("command line runner task"); } } diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/TaskService.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/TaskService.java index dac437e72d..9190b12a22 100644 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/TaskService.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/TaskService.java @@ -6,9 +6,9 @@ import org.springframework.stereotype.Service; @Service public class TaskService { - private static Logger logger = LoggerFactory.getLogger(TaskService.class); + private static final Logger logger = LoggerFactory.getLogger(TaskService.class); public void execute(String task) { - logger.info("do " + task); + logger.info("do {}", task); } } diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationIntegrationTest.java index 26a7339f1d..43447ca178 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationIntegrationTest.java @@ -1,16 +1,13 @@ package com.baeldung.prevent.commandline.application.runner.execution; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.SpyBean; - -import com.baeldung.prevent.commandline.application.runner.execution.ApplicationRunnerTaskExecutor; -import com.baeldung.prevent.commandline.application.runner.execution.CommandLineTaskExecutor; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.SpyBean; + @SpringBootTest class RunApplicationIntegrationTest { @SpyBean @@ -21,6 +18,6 @@ class RunApplicationIntegrationTest { @Test void whenContextLoads_thenRunnersRun() throws Exception { verify(applicationRunnerTaskExecutor, times(1)).run(any()); - verify(commandLineTaskExecutor, times(1)).run(any()); + verify(commandLineTaskExecutor, times(1)).run(any(String[].class)); } } diff --git a/spring-cloud-modules/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml b/spring-cloud-modules/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml index 952b7867de..d4a651f3dd 100644 --- a/spring-cloud-modules/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml +++ b/spring-cloud-modules/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml @@ -44,8 +44,18 @@ ${spring-boot.version} test + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + test + + + 1.14.13 + + diff --git a/spring-cloud-modules/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml b/spring-cloud-modules/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml index 50169ff03a..de477f810a 100644 --- a/spring-cloud-modules/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml +++ b/spring-cloud-modules/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml @@ -44,8 +44,18 @@ ${spring-boot.version} test + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + test + + + 1.14.13 + + diff --git a/spring-cloud-modules/spring-cloud-zuul/pom.xml b/spring-cloud-modules/spring-cloud-zuul/pom.xml index beb996521a..0e56ccfbdb 100644 --- a/spring-cloud-modules/spring-cloud-zuul/pom.xml +++ b/spring-cloud-modules/spring-cloud-zuul/pom.xml @@ -60,6 +60,12 @@ spring-boot-starter-test test + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + test + @@ -82,6 +88,7 @@ 2021.0.3 2.2.7.RELEASE + 1.14.13 \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml index 7e09bf1770..d13706bbd5 100644 --- a/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml +++ b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml @@ -65,6 +65,12 @@ ${couchbaseMock.version} test + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + test + @@ -129,6 +135,7 @@ 11 11 11 + 1.14.13 \ No newline at end of file From 9219e0216e0e7b2b24d1ada959f1c618fd1bee2f Mon Sep 17 00:00:00 2001 From: Ruchira Madhushan Rajapaksha <52396694+LordMaduz@users.noreply.github.com> Date: Sun, 14 Apr 2024 10:01:07 +0800 Subject: [PATCH 17/23] [BAEL-7546] - How to intercept a request and add headers in WebFlux (#16291) * [BAEL-7546] - How to intercept a request and add headers in WebFlux * Added the Implementation Code. * [BAEL-7546] - How to intercept a request and add headers in WebFlux * Added the JUnit Tests. * [BAEL-7546] - How to intercept a request and add headers in WebFlux * Updated parent module with the new module reference. * [BAEL-7546] - How to intercept a request and add headers in WebFlux * CICD Build Fix for PMD Violation * [BAEL-7546] - How to intercept a request and add headers in WebFlux * CICD Build Fix for PMD Violation * [BAEL-7546] - How to intercept a request and add headers in WebFlux * Use four space indents in the pom file. * [BAEL-7546] - How to intercept a request and add headers in WebFlux * Use 2 space indents line continuation. * [BAEL-7546] - How to intercept a request and add headers in WebFlux * Add test case for Unmodifiable Header map scenario. * [BAEL-7546] - How to intercept a request and add headers in WebFlux * Indentation fixes. --- spring-reactive-modules/pom.xml | 1 + .../spring-reactive-4/pom.xml | 53 ++++++++++++++++ .../baeldung/SpringReactiveApplication.java | 13 ++++ .../baeldung/controller/TraceController.java | 21 +++++++ .../filters/ExceptionalTraceFilter.java | 25 ++++++++ .../filters/TraceHandlerFilterFunction.java | 20 +++++++ .../com/baeldung/filters/TraceWebFilter.java | 20 +++++++ .../baeldung/filters/WebClientFilters.java | 18 ++++++ .../baeldung/handler/TraceRouterHandler.java | 22 +++++++ .../java/com/baeldung/router/TraceRouter.java | 27 +++++++++ .../src/main/resources/application.properties | 0 .../src/main/resources/logback.xml | 13 ++++ .../TraceControllerIntegrationTest.java | 50 ++++++++++++++++ .../filters/WebClientFilterUnitTest.java | 55 +++++++++++++++++ .../TraceRouteHandlerIntegrationTest.java | 60 +++++++++++++++++++ 15 files changed, 398 insertions(+) create mode 100644 spring-reactive-modules/spring-reactive-4/pom.xml create mode 100644 spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/SpringReactiveApplication.java create mode 100644 spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/controller/TraceController.java create mode 100644 spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/ExceptionalTraceFilter.java create mode 100644 spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/TraceHandlerFilterFunction.java create mode 100644 spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/TraceWebFilter.java create mode 100644 spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/WebClientFilters.java create mode 100644 spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/handler/TraceRouterHandler.java create mode 100644 spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/router/TraceRouter.java create mode 100644 spring-reactive-modules/spring-reactive-4/src/main/resources/application.properties create mode 100644 spring-reactive-modules/spring-reactive-4/src/main/resources/logback.xml create mode 100644 spring-reactive-modules/spring-reactive-4/src/test/java/com/baeldung/controller/TraceControllerIntegrationTest.java create mode 100644 spring-reactive-modules/spring-reactive-4/src/test/java/com/baeldung/filters/WebClientFilterUnitTest.java create mode 100644 spring-reactive-modules/spring-reactive-4/src/test/java/com/baeldung/handler/TraceRouteHandlerIntegrationTest.java diff --git a/spring-reactive-modules/pom.xml b/spring-reactive-modules/pom.xml index a8a9d6de8a..2618ea67aa 100644 --- a/spring-reactive-modules/pom.xml +++ b/spring-reactive-modules/pom.xml @@ -20,6 +20,7 @@ spring-reactive-data spring-reactive-2 spring-reactive-3 + spring-reactive-4 spring-reactive-client spring-reactive-client-2 spring-reactive-filters diff --git a/spring-reactive-modules/spring-reactive-4/pom.xml b/spring-reactive-modules/spring-reactive-4/pom.xml new file mode 100644 index 0000000000..7fb099ec1e --- /dev/null +++ b/spring-reactive-modules/spring-reactive-4/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + spring-reactive-4 + 0.0.1-SNAPSHOT + spring-reactive-4 + jar + spring sample project about new features + + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 + + + + 3.4.2 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework.boot + spring-boot-starter-test + test + + + + io.projectreactor + reactor-test + test + + + + io.netty + netty-all + + + + org.wiremock + wiremock-standalone + ${wiremock-standalone.version} + test + + + + diff --git a/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/SpringReactiveApplication.java b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/SpringReactiveApplication.java new file mode 100644 index 0000000000..21fbfdac3e --- /dev/null +++ b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/SpringReactiveApplication.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringReactiveApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringReactiveApplication.class, args); + } + +} diff --git a/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/controller/TraceController.java b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/controller/TraceController.java new file mode 100644 index 0000000000..c6a564e6d6 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/controller/TraceController.java @@ -0,0 +1,21 @@ +package com.baeldung.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Mono; + +@RestController +public class TraceController { + + @GetMapping(value = "/trace-annotated") + public Mono trace(@RequestHeader(name = "traceId") final String traceId) { + return Mono.just("TraceId: ".concat(traceId)); + } + + @GetMapping(value = "/trace-exceptional") + public Mono traceExceptional() { + return Mono.just("Traced"); + } +} diff --git a/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/ExceptionalTraceFilter.java b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/ExceptionalTraceFilter.java new file mode 100644 index 0000000000..b721d10109 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/ExceptionalTraceFilter.java @@ -0,0 +1,25 @@ +package com.baeldung.filters; + +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.WebFilter; +import org.springframework.web.server.WebFilterChain; + +import reactor.core.publisher.Mono; + +@Component +public class ExceptionalTraceFilter implements WebFilter { + + @Override + public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { + if (exchange.getRequest() + .getPath() + .toString() + .equals("/trace-exceptional")) { + exchange.getRequest() + .getHeaders() + .add("traceId", "TRACE-ID"); + } + return chain.filter(exchange); + } +} \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/TraceHandlerFilterFunction.java b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/TraceHandlerFilterFunction.java new file mode 100644 index 0000000000..708e4dc509 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/TraceHandlerFilterFunction.java @@ -0,0 +1,20 @@ +package com.baeldung.filters; + +import org.springframework.web.reactive.function.server.HandlerFilterFunction; +import org.springframework.web.reactive.function.server.HandlerFunction; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; + +import reactor.core.publisher.Mono; + +public class TraceHandlerFilterFunction implements HandlerFilterFunction { + + @Override + public Mono filter(ServerRequest request, HandlerFunction handlerFunction) { + + ServerRequest serverRequest = ServerRequest.from(request) + .header("traceId", "FUNCTIONAL-TRACE-ID") + .build(); + return handlerFunction.handle(serverRequest); + } +} diff --git a/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/TraceWebFilter.java b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/TraceWebFilter.java new file mode 100644 index 0000000000..fcb5570db6 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/TraceWebFilter.java @@ -0,0 +1,20 @@ +package com.baeldung.filters; + +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.WebFilter; +import org.springframework.web.server.WebFilterChain; + +import reactor.core.publisher.Mono; + +@Component +public class TraceWebFilter implements WebFilter { + + @Override + public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { + exchange.getRequest() + .mutate() + .header("traceId", "ANNOTATED-TRACE-ID"); + return chain.filter(exchange); + } +} diff --git a/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/WebClientFilters.java b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/WebClientFilters.java new file mode 100644 index 0000000000..1748d4d103 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/filters/WebClientFilters.java @@ -0,0 +1,18 @@ +package com.baeldung.filters; + +import org.springframework.util.MultiValueMap; +import org.springframework.web.reactive.function.client.ClientRequest; +import org.springframework.web.reactive.function.client.ExchangeFilterFunction; + +public final class WebClientFilters { + + public static ExchangeFilterFunction modifyRequestHeaders(final MultiValueMap changedMap) { + return (request, next) -> { + final ClientRequest clientRequest = ClientRequest.from(request) + .header("traceId", "TRACE-ID") + .build(); + changedMap.addAll(clientRequest.headers()); + return next.exchange(clientRequest); + }; + } +} diff --git a/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/handler/TraceRouterHandler.java b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/handler/TraceRouterHandler.java new file mode 100644 index 0000000000..7285a564c3 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/handler/TraceRouterHandler.java @@ -0,0 +1,22 @@ +package com.baeldung.handler; + +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; + +import reactor.core.publisher.Mono; + +import static org.springframework.web.reactive.function.server.ServerResponse.ok; + +@Component +public class TraceRouterHandler { + + public Mono handle(final ServerRequest serverRequest) { + + final String traceId = serverRequest.headers() + .firstHeader("traceId"); + assert traceId != null; + final Mono body = Mono.just("TraceId: ".concat(traceId)); + return ok().body(body, String.class); + } +} diff --git a/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/router/TraceRouter.java b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/router/TraceRouter.java new file mode 100644 index 0000000000..cd25477965 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-4/src/main/java/com/baeldung/router/TraceRouter.java @@ -0,0 +1,27 @@ +package com.baeldung.router; + +import com.baeldung.filters.TraceHandlerFilterFunction; +import com.baeldung.handler.TraceRouterHandler; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; + +import static org.springframework.web.reactive.function.server.RequestPredicates.GET; +import static org.springframework.web.reactive.function.server.RouterFunctions.route; + +@Configuration +public class TraceRouter { + + @Bean + public RouterFunction routes(TraceRouterHandler routerHandler) { + return route(GET("/trace-functional-filter"), routerHandler::handle).filter(new TraceHandlerFilterFunction()) + .and(route().GET("/trace-functional-before", routerHandler::handle) + .before(request -> ServerRequest.from(request) + .header("traceId", "FUNCTIONAL-TRACE-ID") + .build()) + .build()); + } +} diff --git a/spring-reactive-modules/spring-reactive-4/src/main/resources/application.properties b/spring-reactive-modules/spring-reactive-4/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-reactive-modules/spring-reactive-4/src/main/resources/logback.xml b/spring-reactive-modules/spring-reactive-4/src/main/resources/logback.xml new file mode 100644 index 0000000000..26beb6d5b4 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-4/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-4/src/test/java/com/baeldung/controller/TraceControllerIntegrationTest.java b/spring-reactive-modules/spring-reactive-4/src/test/java/com/baeldung/controller/TraceControllerIntegrationTest.java new file mode 100644 index 0000000000..eba9ba10a3 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-4/src/test/java/com/baeldung/controller/TraceControllerIntegrationTest.java @@ -0,0 +1,50 @@ +package com.baeldung.controller; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.reactive.server.EntityExchangeResult; +import org.springframework.test.web.reactive.server.WebTestClient; + +@ExtendWith(SpringExtension.class) +@WebFluxTest(controllers = TraceController.class) +public class TraceControllerIntegrationTest { + + @Autowired + private WebTestClient webTestClient; + + @Test + void whenCallTraceAnnotatedEndpoint_thenResponseContainsTraceId() { + EntityExchangeResult result = webTestClient.get() + .uri("/trace-annotated") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .returnResult(); + + final String body = "TraceId: ANNOTATED-TRACE-ID"; + assertEquals(result.getResponseBody(), body); + + } + + @Test + void whenCallTraceExceptionalEndpoint_thenThrowsException() { + EntityExchangeResult result = webTestClient.get() + .uri("/trace-exceptional") + .exchange() + .expectStatus() + .is5xxServerError() + .expectBody(Map.class) + .returnResult(); + + assertNotNull(result.getResponseBody()); + } +} diff --git a/spring-reactive-modules/spring-reactive-4/src/test/java/com/baeldung/filters/WebClientFilterUnitTest.java b/spring-reactive-modules/spring-reactive-4/src/test/java/com/baeldung/filters/WebClientFilterUnitTest.java new file mode 100644 index 0000000000..319f1e6f75 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-4/src/test/java/com/baeldung/filters/WebClientFilterUnitTest.java @@ -0,0 +1,55 @@ +package com.baeldung.filters; + +import static com.baeldung.filters.WebClientFilters.modifyRequestHeaders; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.reactive.function.client.WebClient; + +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; +import com.github.tomakehurst.wiremock.junit5.WireMockTest; + +@WireMockTest +public class WebClientFilterUnitTest { + + @RegisterExtension + static WireMockExtension extension = WireMockExtension.newInstance() + .options(wireMockConfig().dynamicPort() + .dynamicHttpsPort()) + .build(); + + @Test + void whenCallEndpoint_thenRequestHeadersModified() { + extension.stubFor(get("/test").willReturn(aResponse().withStatus(200) + .withBody("SUCCESS"))); + + final MultiValueMap map = new LinkedMultiValueMap<>(); + + WebClient webClient = WebClient.builder() + .filter(modifyRequestHeaders(map)) + .build(); + String actual = sendGetRequest(webClient); + + final String body = "SUCCESS"; + Assertions.assertEquals(actual, body); + Assertions.assertEquals("TRACE-ID", map.getFirst("traceId")); + } + + private String sendGetRequest(final WebClient webClient) { + return webClient.get() + .uri(getUrl()) + .retrieve() + .bodyToMono(String.class) + .block(); + } + + private String getUrl() { + return "http://localhost:" + extension.getPort() + "/test"; + } +} diff --git a/spring-reactive-modules/spring-reactive-4/src/test/java/com/baeldung/handler/TraceRouteHandlerIntegrationTest.java b/spring-reactive-modules/spring-reactive-4/src/test/java/com/baeldung/handler/TraceRouteHandlerIntegrationTest.java new file mode 100644 index 0000000000..ee30dfd3a2 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-4/src/test/java/com/baeldung/handler/TraceRouteHandlerIntegrationTest.java @@ -0,0 +1,60 @@ +package com.baeldung.handler; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.reactive.server.EntityExchangeResult; +import org.springframework.test.web.reactive.server.WebTestClient; + +import com.baeldung.router.TraceRouter; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { TraceRouter.class, TraceRouterHandler.class }) +@WebFluxTest +public class TraceRouteHandlerIntegrationTest { + + @Autowired + private ApplicationContext context; + private WebTestClient webTestClient; + + @BeforeEach + void setUp() { + webTestClient = WebTestClient.bindToApplicationContext(context) + .build(); + } + + @Test + void whenCallTraceFunctionalFilterEndpoint_thenResponseContainsTraceId() { + EntityExchangeResult result = webTestClient.get() + .uri("/trace-functional-filter") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .returnResult(); + + final String body = "TraceId: FUNCTIONAL-TRACE-ID"; + assertEquals(result.getResponseBody(), body); + } + + @Test + void whenCallTraceFunctionalBeforeEndpoint_thenResponseContainsTraceId() { + EntityExchangeResult result = webTestClient.get() + .uri("/trace-functional-before") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .returnResult(); + + final String body = "TraceId: FUNCTIONAL-TRACE-ID"; + assertEquals(result.getResponseBody(), body); + } +} From d50de8f6bd923fdc08dd9925ae8b556cd596d9e4 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Sun, 14 Apr 2024 12:34:57 +0200 Subject: [PATCH 18/23] JAVA-31405: Removed the repo.spring.io from tutorials repo (#16358) --- persistence-modules/spring-jdbc-2/pom.xml | 41 ++------------- .../jdbcclient/JdbcClientDemoApplication.java | 3 +- spring-ai/pom.xml | 2 +- spring-boot-modules/spring-boot-3-2/pom.xml | 22 +------- spring-boot-modules/spring-boot-3/pom.xml | 39 +------------- .../pom.xml | 8 --- spring-native/pom-nativeimage.xml | 21 -------- spring-native/pom.xml | 52 +++++++++---------- 8 files changed, 33 insertions(+), 155 deletions(-) diff --git a/persistence-modules/spring-jdbc-2/pom.xml b/persistence-modules/spring-jdbc-2/pom.xml index 7942e7675d..374c87d358 100644 --- a/persistence-modules/spring-jdbc-2/pom.xml +++ b/persistence-modules/spring-jdbc-2/pom.xml @@ -20,6 +20,7 @@ org.springframework.boot spring-boot-starter-jdbc + ${spring-boot.version} @@ -30,7 +31,7 @@ org.springframework.boot spring-boot-starter-test - + ${spring-boot.version} @@ -46,47 +47,11 @@ - - - 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 + 3.2.4 \ 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 index d10124fdef..1e7a6034ee 100644 --- 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 @@ -4,8 +4,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; -@SpringBootApplication -@ComponentScan(basePackages = "com.baledung.jdbcclient") +@SpringBootApplication(scanBasePackages = "com.baeldung") public class JdbcClientDemoApplication { public static void main(String[] args) { diff --git a/spring-ai/pom.xml b/spring-ai/pom.xml index 8864b03568..da4a38a868 100644 --- a/spring-ai/pom.xml +++ b/spring-ai/pom.xml @@ -18,7 +18,7 @@ spring-snapshots Spring Snapshots - https://repo.spring.io/snapshot + https://repo.spring.io/snapshot false diff --git a/spring-boot-modules/spring-boot-3-2/pom.xml b/spring-boot-modules/spring-boot-3-2/pom.xml index d427aff835..2509cbf0d0 100644 --- a/spring-boot-modules/spring-boot-3-2/pom.xml +++ b/spring-boot-modules/spring-boot-3-2/pom.xml @@ -14,14 +14,6 @@ 1.0.0-SNAPSHOT - - - repository.spring.release - Spring GA Repository - https://repo.spring.io/milestone - - - org.springframework.boot @@ -102,7 +94,6 @@ org.springframework.boot spring-boot-starter-test - 3.2.0-M2 org.junit.jupiter @@ -202,18 +193,6 @@ - - - - org.springframework.boot - spring-boot-dependencies - 3.2.0-M2 - import - pom - - - - @@ -300,6 +279,7 @@ 0.2.0 5.0.2 3.1.2 + 3.2.4 diff --git a/spring-boot-modules/spring-boot-3/pom.xml b/spring-boot-modules/spring-boot-3/pom.xml index 0c00a8af34..78196c3413 100644 --- a/spring-boot-modules/spring-boot-3/pom.xml +++ b/spring-boot-modules/spring-boot-3/pom.xml @@ -211,46 +211,9 @@ 3.0.0-M7 com.baeldung.sample.TodoApplication 5.14.0 - 3.2.0-SNAPSHOT + 3.2.4 0.2.0 5.10.0 - - - 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 - - - - \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/pom.xml b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/pom.xml index 86644a4999..3c059e65fa 100644 --- a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/pom.xml +++ b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/pom.xml @@ -90,14 +90,6 @@ - - - repository.spring.milestone - Spring Milestone Repository - https://repo.spring.io/release - - - diff --git a/spring-native/pom-nativeimage.xml b/spring-native/pom-nativeimage.xml index 08ceb09a8a..15712902e4 100644 --- a/spring-native/pom-nativeimage.xml +++ b/spring-native/pom-nativeimage.xml @@ -15,27 +15,6 @@ ../parent-boot-3 - - - spring-milestone - Spring Milestone - https://repo.spring.io/milestone - - - spring-snapshot - Spring Snapshot - https://repo.spring.io/snapshot - - - - - - spring-plugins-snapshot - Spring Plugins Snapshot - https://repo.spring.io/plugins-snapshot - - - org.springframework.boot diff --git a/spring-native/pom.xml b/spring-native/pom.xml index 97eb33c1c7..e2bf3d4078 100644 --- a/spring-native/pom.xml +++ b/spring-native/pom.xml @@ -15,32 +15,6 @@ ../parent-boot-2 - - - spring-milestone - Spring Milestone - https://repo.spring.io/milestone - - - spring-snapshot - Spring Snapshot - https://repo.spring.io/snapshot - - - - - - spring-plugins-snapshot - Spring Plugins Snapshot - https://repo.spring.io/plugins-snapshot - - - spring-plugins-milestone - Spring Plugins Milestone - https://repo.spring.io/plugins-milestone - - - org.springframework.boot @@ -84,5 +58,31 @@ 0.12.1 2.17.1 + + + + spring-milestone + Spring Milestone + https://repo.spring.io/milestone + + + spring-snapshot + Spring Snapshot + https://repo.spring.io/snapshot + + + + + + spring-plugins-snapshot + Spring Plugins Snapshot + https://repo.spring.io/plugins-snapshot + + + spring-plugins-milestone + Spring Plugins Milestone + https://repo.spring.io/plugins-milestone + + \ No newline at end of file From 6a813077241a0fdda2e02e76219c038e34e794aa Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Sun, 14 Apr 2024 14:27:11 +0200 Subject: [PATCH 19/23] Fix zuul-server. (#16408) --- .../zuul-server/pom.xml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/spring-cloud-modules/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml b/spring-cloud-modules/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml index 890e26bf19..937689db73 100644 --- a/spring-cloud-modules/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml +++ b/spring-cloud-modules/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml @@ -52,8 +52,19 @@ spring-boot-starter-test test + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + test + + + 1.14.13 + + + From dde9779c835f3f4f54baca332b860e301403f5ca Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 14 Apr 2024 14:29:34 +0200 Subject: [PATCH 20/23] Parallel Collectors with Virtual Threads (#16313) --- libraries-stream/pom.xml | 14 +++- ...lelCollectorsVirtualThreadsManualTest.java | 73 +++++++++++++++++++ pom.xml | 2 +- 3 files changed, 87 insertions(+), 2 deletions(-) create mode 100644 libraries-stream/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsVirtualThreadsManualTest.java diff --git a/libraries-stream/pom.xml b/libraries-stream/pom.xml index 6cd931c299..fea437db6b 100644 --- a/libraries-stream/pom.xml +++ b/libraries-stream/pom.xml @@ -49,11 +49,23 @@ 0.9.12 - 2.6.0 + 3.0.0 0.9.0 8.2.0 0.8.1 1.15 + + + + org.apache.maven.plugins + maven-compiler-plugin + + 21 + 21 + + + + diff --git a/libraries-stream/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsVirtualThreadsManualTest.java b/libraries-stream/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsVirtualThreadsManualTest.java new file mode 100644 index 0000000000..3038fb74f9 --- /dev/null +++ b/libraries-stream/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsVirtualThreadsManualTest.java @@ -0,0 +1,73 @@ +package com.baeldung.parallel_collectors; + +import com.pivovarit.collectors.ParallelCollectors; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.Executors; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import static java.util.stream.Collectors.toList; + +public class ParallelCollectorsVirtualThreadsManualTest { + + private static final Logger log = LoggerFactory.getLogger(ParallelCollectorsVirtualThreadsManualTest.class); + + // increase the number of parallel processes to find the max number of threads on your machine + @Test + public void givenParallelism_whenUsingOSThreads_thenShouldRunOutOfThreads() { + int parallelProcesses = 50_000; + + var e = Executors.newFixedThreadPool(parallelProcesses); + + var result = timed(() -> Stream.iterate(0, i -> i + 1).limit(parallelProcesses) + .collect(ParallelCollectors.parallel(i -> fetchById(i), toList(), e, parallelProcesses)) + .join()); + + log.info("{}", result); + } + + @Test + public void givenParallelism_whenUsingVThreads_thenShouldProcessInParallel() { + int parallelProcesses = 1000_000; + + var result = timed(() -> Stream.iterate(0, i -> i + 1).limit(parallelProcesses) + .collect(ParallelCollectors.parallel(i -> fetchById(i), toList())) + .join()); + + log.info("{}", result); + } + + @Test + public void givenParallelismAndPCollectors2_whenUsingVThreads_thenShouldProcessInParallel() { + int parallelProcesses = 1000_000; + + var result = timed(() -> Stream.iterate(0, i -> i + 1).limit(parallelProcesses) + .collect(ParallelCollectors.parallel(i -> fetchById(i), toList(), Executors.newVirtualThreadPerTaskExecutor(), Integer.MAX_VALUE)) + .join()); + + log.info("{}", result); + } + + private static String fetchById(int id) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // ignore shamelessly + } + + return "user-" + id; + } + + private static T timed(Supplier supplier) { + var before = Instant.now(); + T result = supplier.get(); + var after = Instant.now(); + log.info("Execution time: {} ms", Duration.between(before, after).toMillis()); + return result; + } +} diff --git a/pom.xml b/pom.xml index 60d42c5517..54c54bf7b8 100644 --- a/pom.xml +++ b/pom.xml @@ -737,7 +737,7 @@ libraries-security libraries-server-2 libraries-server - libraries-stream + libraries-testing-2 libraries-transform libraries From 5201ee6ab597c070cfeefa8fb6f3a32504c3fd73 Mon Sep 17 00:00:00 2001 From: Amit Pandey Date: Sun, 14 Apr 2024 18:37:36 +0530 Subject: [PATCH 21/23] [JAVA-29009] Upgrade to spring-reactive-oauth module to Spring Boot 3 (#16328) --- .../spring-reactive-oauth/pom.xml | 11 ++-- .../reactive/oauth/SecurityConfig.java | 10 ++-- .../Spring5ReactiveOauthApplication.java | 12 +++++ .../configuration/WebSecurityConfig.java | 11 ++-- .../configuration/WebSecurityConfig.java | 8 ++- .../configuration/WebClientConfig.java | 50 ++++++++++++++++--- .../configure/WebClientConfig.java | 2 +- .../configure/WebSecurityConfig.java | 4 +- .../Spring5ReactiveOauthIntegrationTest.java | 3 +- 9 files changed, 81 insertions(+), 30 deletions(-) diff --git a/spring-reactive-modules/spring-reactive-oauth/pom.xml b/spring-reactive-modules/spring-reactive-oauth/pom.xml index 9d2dbf6126..d4699acd6d 100644 --- a/spring-reactive-modules/spring-reactive-oauth/pom.xml +++ b/spring-reactive-modules/spring-reactive-oauth/pom.xml @@ -11,9 +11,10 @@ WebFlux and Spring Security OAuth - com.baeldung.spring.reactive - spring-reactive-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -62,4 +63,8 @@ + + com.baeldung.reactive.oauth.Spring5ReactiveOauthApplication + + \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/reactive/oauth/SecurityConfig.java b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/reactive/oauth/SecurityConfig.java index 2fa1dd9380..c2069d3cdb 100644 --- a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/reactive/oauth/SecurityConfig.java +++ b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/reactive/oauth/SecurityConfig.java @@ -1,6 +1,7 @@ package com.baeldung.reactive.oauth; import org.springframework.context.annotation.Bean; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.web.server.SecurityWebFilterChain; @@ -10,10 +11,11 @@ public class SecurityConfig { @Bean public SecurityWebFilterChain configure(ServerHttpSecurity http) throws Exception { - return http.authorizeExchange() + return http.authorizeExchange(auth -> auth .pathMatchers("/about").permitAll() - .anyExchange().authenticated() - .and().oauth2Login() - .and().build(); + .anyExchange().authenticated()) + .oauth2Login(Customizer.withDefaults()) + .build(); } + } diff --git a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/reactive/oauth/Spring5ReactiveOauthApplication.java b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/reactive/oauth/Spring5ReactiveOauthApplication.java index b95517200e..7fe82404be 100644 --- a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/reactive/oauth/Spring5ReactiveOauthApplication.java +++ b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/reactive/oauth/Spring5ReactiveOauthApplication.java @@ -4,9 +4,12 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository; import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction; import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository; +import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.web.reactive.function.client.WebClient; @PropertySource("classpath:default-application.yml") @@ -24,4 +27,13 @@ public class Spring5ReactiveOauthApplication { .filter(filter) .build(); } + + @Bean + public ReactiveClientRegistrationRepository clientRegistrations() { + ClientRegistration registration = ClientRegistration.withRegistrationId("bael").authorizationGrantType( + AuthorizationGrantType.CLIENT_CREDENTIALS).clientId("bael").tokenUri("default").build(); + + return new InMemoryReactiveClientRegistrationRepository(registration); + + } } diff --git a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/configuration/WebSecurityConfig.java b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/configuration/WebSecurityConfig.java index 4271ae96cf..325c322a73 100644 --- a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/configuration/WebSecurityConfig.java +++ b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/configuration/WebSecurityConfig.java @@ -2,6 +2,7 @@ package com.baeldung.webclient.authorizationcodeclient.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.Customizer; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.web.server.SecurityWebFilterChain; @@ -9,13 +10,9 @@ import org.springframework.security.web.server.SecurityWebFilterChain; public class WebSecurityConfig { @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http.authorizeExchange() - .anyExchange() - .authenticated() - .and() - .oauth2Client() - .and() - .formLogin(); + http.authorizeExchange(s-> s.anyExchange().authenticated()) + .oauth2Client(Customizer.withDefaults()) + .formLogin(Customizer.withDefaults()); return http.build(); } diff --git a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/configuration/WebSecurityConfig.java b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/configuration/WebSecurityConfig.java index f45fc09222..46e3828ec2 100644 --- a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/configuration/WebSecurityConfig.java +++ b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/configuration/WebSecurityConfig.java @@ -2,6 +2,7 @@ package com.baeldung.webclient.authorizationcodelogin.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.Customizer; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.web.server.SecurityWebFilterChain; @@ -9,11 +10,8 @@ import org.springframework.security.web.server.SecurityWebFilterChain; public class WebSecurityConfig { @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http.authorizeExchange() - .anyExchange() - .authenticated() - .and() - .oauth2Login(); + http.authorizeExchange(s-> s.anyExchange().authenticated()) + .oauth2Login(Customizer.withDefaults()); return http.build(); } diff --git a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/configuration/WebClientConfig.java b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/configuration/WebClientConfig.java index 8ffc92b4cd..1bf9ddd5be 100644 --- a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/configuration/WebClientConfig.java +++ b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/configuration/WebClientConfig.java @@ -1,22 +1,60 @@ package com.baeldung.webclient.clientcredentials.configuration; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.client.AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager; +import org.springframework.security.oauth2.client.InMemoryReactiveOAuth2AuthorizedClientService; +import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProvider; +import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProviderBuilder; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository; import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction; -import org.springframework.security.oauth2.client.web.server.UnAuthenticatedServerOAuth2AuthorizedClientRepository; +import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.web.reactive.function.client.WebClient; @Configuration public class WebClientConfig { @Bean - WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations) { - ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, new UnAuthenticatedServerOAuth2AuthorizedClientRepository()); - oauth.setDefaultClientRegistrationId("bael"); - return WebClient.builder() - .filter(oauth) + ReactiveClientRegistrationRepository clientRegistrations( + @Value("${spring.security.oauth2.client.provider.bael.token-uri}") String token_uri, + @Value("${spring.security.oauth2.client.registration.bael.client-id}") String client_id, + @Value("${spring.security.oauth2.client.registration.bael.client-secret}") String client_secret, + @Value("${spring.security.oauth2.client.registration.bael.authorization-grant-type}") String authorizationGrantType + + ) { + ClientRegistration registration = ClientRegistration + .withRegistrationId("keycloak") + .tokenUri(token_uri) + .clientId(client_id) + .clientSecret(client_secret) + .authorizationGrantType(new AuthorizationGrantType(authorizationGrantType)) .build(); + return new InMemoryReactiveClientRegistrationRepository(registration); + } + @Bean + public AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager( + ReactiveClientRegistrationRepository clientRegistrationRepository) { + InMemoryReactiveOAuth2AuthorizedClientService clientService = + new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository); + ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder().clientCredentials().build(); + AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager = + new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, clientService); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + return authorizedClientManager; } + @Bean + WebClient webClient(AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager auth2AuthorizedClientManager) { + ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = + new ServerOAuth2AuthorizedClientExchangeFilterFunction(auth2AuthorizedClientManager); + oauth2Client.setDefaultClientRegistrationId("bael"); + return WebClient.builder() + .filter(oauth2Client) + .build(); + } } diff --git a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebClientConfig.java b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebClientConfig.java index 51fc60821a..33493be61d 100644 --- a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebClientConfig.java +++ b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebClientConfig.java @@ -11,6 +11,6 @@ public class WebClientConfig { public WebClient configureWebClient() { return WebClient.builder() .build(); - }; + } } diff --git a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebSecurityConfig.java b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebSecurityConfig.java index 1753681db8..0aa38d2a12 100644 --- a/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebSecurityConfig.java +++ b/spring-reactive-modules/spring-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebSecurityConfig.java @@ -9,9 +9,7 @@ import org.springframework.security.web.server.SecurityWebFilterChain; public class WebSecurityConfig { @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http.authorizeExchange() - .anyExchange() - .permitAll(); + http.authorizeExchange(s -> s.anyExchange().permitAll()); return http.build(); } } diff --git a/spring-reactive-modules/spring-reactive-oauth/src/test/java/com/baeldung/reactive/oauth/Spring5ReactiveOauthIntegrationTest.java b/spring-reactive-modules/spring-reactive-oauth/src/test/java/com/baeldung/reactive/oauth/Spring5ReactiveOauthIntegrationTest.java index db545d63de..fc2b540f4d 100644 --- a/spring-reactive-modules/spring-reactive-oauth/src/test/java/com/baeldung/reactive/oauth/Spring5ReactiveOauthIntegrationTest.java +++ b/spring-reactive-modules/spring-reactive-oauth/src/test/java/com/baeldung/reactive/oauth/Spring5ReactiveOauthIntegrationTest.java @@ -1,12 +1,13 @@ package com.baeldung.reactive.oauth; +import com.baeldung.webclient.clientcredentials.configuration.WebClientConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(classes = WebClientConfig.class) public class Spring5ReactiveOauthIntegrationTest { @Test From 2685d31fd1b15956d83b875941f6bf56561f47e0 Mon Sep 17 00:00:00 2001 From: vunamtien Date: Sun, 14 Apr 2024 21:51:03 +0700 Subject: [PATCH 22/23] [JAVA-31561] Upgrade-springdoc-openapi-starter-webmvc-ui-&-springdoc-openapi-starter-webflux-ui (#16377) --- microservices-modules/event-driven-microservice/pom.xml | 3 ++- spring-boot-modules/spring-boot-3-2/pom.xml | 3 ++- spring-boot-modules/spring-boot-3-native/pom.xml | 3 ++- spring-boot-modules/spring-boot-3/pom.xml | 3 ++- spring-boot-modules/spring-boot-springdoc-2/pom.xml | 3 ++- spring-boot-modules/spring-boot-swagger-keycloak/pom.xml | 3 ++- spring-security-modules/spring-security-web-springdoc/pom.xml | 3 ++- 7 files changed, 14 insertions(+), 7 deletions(-) diff --git a/microservices-modules/event-driven-microservice/pom.xml b/microservices-modules/event-driven-microservice/pom.xml index a1ba8d6e35..6b6df3b14b 100644 --- a/microservices-modules/event-driven-microservice/pom.xml +++ b/microservices-modules/event-driven-microservice/pom.xml @@ -34,7 +34,7 @@ org.springdoc springdoc-openapi-starter-webmvc-ui - ${spring.webmvc.version} + ${springdoc-openapi-webmvc-ui.version} @@ -71,6 +71,7 @@ 17 2.0.8 2.1.0 + 2.5.0 diff --git a/spring-boot-modules/spring-boot-3-2/pom.xml b/spring-boot-modules/spring-boot-3-2/pom.xml index 2509cbf0d0..72dffa588a 100644 --- a/spring-boot-modules/spring-boot-3-2/pom.xml +++ b/spring-boot-modules/spring-boot-3-2/pom.xml @@ -65,7 +65,7 @@ org.springdoc springdoc-openapi-starter-webmvc-ui - ${springdoc.version} + ${springdoc-openapi-webmvc-ui.version} org.projectlombok @@ -280,6 +280,7 @@ 5.0.2 3.1.2 3.2.4 + 2.5.0 diff --git a/spring-boot-modules/spring-boot-3-native/pom.xml b/spring-boot-modules/spring-boot-3-native/pom.xml index 1e42cb6035..e446b19f03 100644 --- a/spring-boot-modules/spring-boot-3-native/pom.xml +++ b/spring-boot-modules/spring-boot-3-native/pom.xml @@ -22,7 +22,7 @@ org.springdoc springdoc-openapi-starter-webmvc-ui - ${springdoc.version} + ${springdoc-openapi-webmvc-ui.version} org.springframework.boot @@ -100,6 +100,7 @@ 3.0.0-M7 0.9.17 17 + 2.5.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3/pom.xml b/spring-boot-modules/spring-boot-3/pom.xml index 78196c3413..0cb9d33cb8 100644 --- a/spring-boot-modules/spring-boot-3/pom.xml +++ b/spring-boot-modules/spring-boot-3/pom.xml @@ -89,7 +89,7 @@ org.springdoc springdoc-openapi-starter-webmvc-ui - ${springdoc.version} + ${springdoc-openapi-webmvc-ui.version} org.projectlombok @@ -214,6 +214,7 @@ 3.2.4 0.2.0 5.10.0 + 2.5.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-springdoc-2/pom.xml b/spring-boot-modules/spring-boot-springdoc-2/pom.xml index 89f176e668..56d118e15f 100644 --- a/spring-boot-modules/spring-boot-springdoc-2/pom.xml +++ b/spring-boot-modules/spring-boot-springdoc-2/pom.xml @@ -40,7 +40,7 @@ org.springdoc springdoc-openapi-starter-webmvc-ui - ${springdoc.version} + ${springdoc-openapi-webmvc-ui.version} org.springdoc @@ -119,6 +119,7 @@ 2.2.0 + 2.5.0 1.4 17 diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml b/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml index df08a68a30..60aad3b4a4 100644 --- a/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml @@ -32,7 +32,7 @@ org.springdoc springdoc-openapi-starter-webmvc-ui - ${springdoc.version} + ${springdoc-openapi-webmvc-ui.version} javax.annotation @@ -53,6 +53,7 @@ 2.1.0 1.3.2 + 2.5.0 \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-springdoc/pom.xml b/spring-security-modules/spring-security-web-springdoc/pom.xml index 1df710394e..5ce51ed5b0 100644 --- a/spring-security-modules/spring-security-web-springdoc/pom.xml +++ b/spring-security-modules/spring-security-web-springdoc/pom.xml @@ -28,7 +28,7 @@ org.springdoc springdoc-openapi-starter-webmvc-ui - ${springdoc.version} + ${springdoc-openapi-webmvc-ui.version} com.google.guava @@ -45,6 +45,7 @@ 2.4.0 com.baeldung.basicauth.SpringBootSpringdocBasicAuth + 2.5.0 \ No newline at end of file From 684ee81ed1828c1e8a38e4b320379a4c4768b583 Mon Sep 17 00:00:00 2001 From: vunamtien Date: Sun, 14 Apr 2024 22:04:50 +0700 Subject: [PATCH 23/23] [JAVA-32759] Split-or-move-spring-boot-persistence-mongodb (#16392) --- persistence-modules/pom.xml | 1 + .../README.md | 5 +++ .../spring-boot-persistence-mongodb-4/pom.xml | 34 +++++++++++++++++++ .../mongodb/dbref/DbRefApplication.java | 0 .../baeldung/mongodb/dbref/DbRefTester.java | 3 +- .../baeldung/mongodb/dbref/model/Person.java | 4 +-- .../com/baeldung/mongodb/dbref/model/Pet.java | 0 .../dbref/repository/PersonRepository.java | 3 +- .../zoneddatetime/config/MongoConfig.java | 9 +++-- .../converter/ZonedDateTimeReadConverter.java | 0 .../ZonedDateTimeWriteConverter.java | 0 .../baeldung/zoneddatetime/model/Action.java | 0 .../repository/ActionRepository.java | 3 +- .../src/main/resources/application.properties | 1 + .../mongodb/dbref/DbRefIntegrationTest.java | 23 ++++++------- .../ActionRepositoryLiveTest.java | 7 ++-- .../src/test/resources/application.properties | 1 + .../spring-boot-persistence-mongodb/README.md | 2 -- 18 files changed, 65 insertions(+), 31 deletions(-) create mode 100644 persistence-modules/spring-boot-persistence-mongodb-4/README.md create mode 100644 persistence-modules/spring-boot-persistence-mongodb-4/pom.xml rename persistence-modules/{spring-boot-persistence-mongodb => spring-boot-persistence-mongodb-4}/src/main/java/com/baeldung/mongodb/dbref/DbRefApplication.java (100%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-boot-persistence-mongodb-4}/src/main/java/com/baeldung/mongodb/dbref/DbRefTester.java (99%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-boot-persistence-mongodb-4}/src/main/java/com/baeldung/mongodb/dbref/model/Person.java (100%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-boot-persistence-mongodb-4}/src/main/java/com/baeldung/mongodb/dbref/model/Pet.java (100%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-boot-persistence-mongodb-4}/src/main/java/com/baeldung/mongodb/dbref/repository/PersonRepository.java (99%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-boot-persistence-mongodb-4}/src/main/java/com/baeldung/zoneddatetime/config/MongoConfig.java (99%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-boot-persistence-mongodb-4}/src/main/java/com/baeldung/zoneddatetime/converter/ZonedDateTimeReadConverter.java (100%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-boot-persistence-mongodb-4}/src/main/java/com/baeldung/zoneddatetime/converter/ZonedDateTimeWriteConverter.java (100%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-boot-persistence-mongodb-4}/src/main/java/com/baeldung/zoneddatetime/model/Action.java (100%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-boot-persistence-mongodb-4}/src/main/java/com/baeldung/zoneddatetime/repository/ActionRepository.java (99%) create mode 100644 persistence-modules/spring-boot-persistence-mongodb-4/src/main/resources/application.properties rename persistence-modules/{spring-boot-persistence-mongodb => spring-boot-persistence-mongodb-4}/src/test/java/com/baeldung/mongodb/dbref/DbRefIntegrationTest.java (99%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-boot-persistence-mongodb-4}/src/test/java/com/baeldung/zoneddatetime/ActionRepositoryLiveTest.java (99%) create mode 100644 persistence-modules/spring-boot-persistence-mongodb-4/src/test/resources/application.properties diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 16893b825f..620fbe0825 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -69,6 +69,7 @@ spring-boot-persistence-mongodb spring-boot-persistence-mongodb-2 spring-boot-persistence-mongodb-3 + spring-boot-persistence-mongodb-4 spring-data-arangodb spring-data-cassandra-test diff --git a/persistence-modules/spring-boot-persistence-mongodb-4/README.md b/persistence-modules/spring-boot-persistence-mongodb-4/README.md new file mode 100644 index 0000000000..b6922eb10d --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb-4/README.md @@ -0,0 +1,5 @@ +# Relevant Articles + +- [ZonedDateTime with Spring Data MongoDB](https://www.baeldung.com/spring-data-mongodb-zoneddatetime) +- [A Guide to @DBRef in MongoDB](https://www.baeldung.com/spring-mongodb-dbref-annotation) +- More articles: [[<--prev]](../spring-boot-persistence-mongodb-3) diff --git a/persistence-modules/spring-boot-persistence-mongodb-4/pom.xml b/persistence-modules/spring-boot-persistence-mongodb-4/pom.xml new file mode 100644 index 0000000000..ae387c5709 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb-4/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + spring-boot-persistence-mongodb-4 + spring-boot-persistence-mongodb-4 + This is simple boot application for Spring boot persistence mongodb test + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + test + + + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/dbref/DbRefApplication.java b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/mongodb/dbref/DbRefApplication.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/dbref/DbRefApplication.java rename to persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/mongodb/dbref/DbRefApplication.java diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/dbref/DbRefTester.java b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/mongodb/dbref/DbRefTester.java similarity index 99% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/dbref/DbRefTester.java rename to persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/mongodb/dbref/DbRefTester.java index 58641e1258..b0c6bebd53 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/dbref/DbRefTester.java +++ b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/mongodb/dbref/DbRefTester.java @@ -1,5 +1,6 @@ package com.baeldung.mongodb.dbref; +import com.baeldung.mongodb.dbref.repository.PersonRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -7,8 +8,6 @@ import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; -import com.baeldung.mongodb.dbref.repository.PersonRepository; - @Component public class DbRefTester implements ApplicationRunner { diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/dbref/model/Person.java b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/mongodb/dbref/model/Person.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/dbref/model/Person.java rename to persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/mongodb/dbref/model/Person.java index 7b7826e716..93f372d8ef 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/dbref/model/Person.java +++ b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/mongodb/dbref/model/Person.java @@ -1,11 +1,11 @@ package com.baeldung.mongodb.dbref.model; -import java.util.List; - import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; +import java.util.List; + @Document(collection = "Person") public class Person { diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/dbref/model/Pet.java b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/mongodb/dbref/model/Pet.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/dbref/model/Pet.java rename to persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/mongodb/dbref/model/Pet.java diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/dbref/repository/PersonRepository.java b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/mongodb/dbref/repository/PersonRepository.java similarity index 99% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/dbref/repository/PersonRepository.java rename to persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/mongodb/dbref/repository/PersonRepository.java index 2ef5a9dbd6..7eebf8869b 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/dbref/repository/PersonRepository.java +++ b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/mongodb/dbref/repository/PersonRepository.java @@ -1,8 +1,7 @@ package com.baeldung.mongodb.dbref.repository; -import org.springframework.data.mongodb.repository.MongoRepository; - import com.baeldung.mongodb.dbref.model.Person; +import org.springframework.data.mongodb.repository.MongoRepository; public interface PersonRepository extends MongoRepository { diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/config/MongoConfig.java b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/zoneddatetime/config/MongoConfig.java similarity index 99% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/config/MongoConfig.java rename to persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/zoneddatetime/config/MongoConfig.java index 4eb3872e34..cf2d24c630 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/config/MongoConfig.java +++ b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/zoneddatetime/config/MongoConfig.java @@ -1,15 +1,14 @@ package com.baeldung.zoneddatetime.config; -import java.util.ArrayList; -import java.util.List; - +import com.baeldung.zoneddatetime.converter.ZonedDateTimeReadConverter; +import com.baeldung.zoneddatetime.converter.ZonedDateTimeWriteConverter; import org.springframework.core.convert.converter.Converter; import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration; import org.springframework.data.mongodb.core.convert.MongoCustomConversions; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; -import com.baeldung.zoneddatetime.converter.ZonedDateTimeReadConverter; -import com.baeldung.zoneddatetime.converter.ZonedDateTimeWriteConverter; +import java.util.ArrayList; +import java.util.List; @EnableMongoRepositories(basePackages = { "com.baeldung" }) public class MongoConfig extends AbstractMongoClientConfiguration { diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/converter/ZonedDateTimeReadConverter.java b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/zoneddatetime/converter/ZonedDateTimeReadConverter.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/converter/ZonedDateTimeReadConverter.java rename to persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/zoneddatetime/converter/ZonedDateTimeReadConverter.java diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/converter/ZonedDateTimeWriteConverter.java b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/zoneddatetime/converter/ZonedDateTimeWriteConverter.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/converter/ZonedDateTimeWriteConverter.java rename to persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/zoneddatetime/converter/ZonedDateTimeWriteConverter.java diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/model/Action.java b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/zoneddatetime/model/Action.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/model/Action.java rename to persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/zoneddatetime/model/Action.java diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/repository/ActionRepository.java b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/zoneddatetime/repository/ActionRepository.java similarity index 99% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/repository/ActionRepository.java rename to persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/zoneddatetime/repository/ActionRepository.java index e214c4b3c4..8fc33a6b6e 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/repository/ActionRepository.java +++ b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/java/com/baeldung/zoneddatetime/repository/ActionRepository.java @@ -1,7 +1,6 @@ package com.baeldung.zoneddatetime.repository; +import com.baeldung.zoneddatetime.model.Action; import org.springframework.data.mongodb.repository.MongoRepository; -import com.baeldung.zoneddatetime.model.Action; - public interface ActionRepository extends MongoRepository { } \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb-4/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/resources/application.properties new file mode 100644 index 0000000000..b1c7e18ea3 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb-4/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=spring-boot-persistence-mongodb-4 diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/dbref/DbRefIntegrationTest.java b/persistence-modules/spring-boot-persistence-mongodb-4/src/test/java/com/baeldung/mongodb/dbref/DbRefIntegrationTest.java similarity index 99% rename from persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/dbref/DbRefIntegrationTest.java rename to persistence-modules/spring-boot-persistence-mongodb-4/src/test/java/com/baeldung/mongodb/dbref/DbRefIntegrationTest.java index c357c0283c..8668bf9404 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/dbref/DbRefIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-mongodb-4/src/test/java/com/baeldung/mongodb/dbref/DbRefIntegrationTest.java @@ -1,11 +1,11 @@ package com.baeldung.mongodb.dbref; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.ArrayList; -import java.util.List; - +import com.baeldung.mongodb.dbref.model.Person; +import com.baeldung.mongodb.dbref.model.Pet; +import com.baeldung.mongodb.dbref.repository.PersonRepository; +import com.mongodb.BasicDBObjectBuilder; +import com.mongodb.DBObject; +import com.mongodb.DBRef; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -14,12 +14,11 @@ import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.mongodb.dbref.model.Person; -import com.baeldung.mongodb.dbref.model.Pet; -import com.baeldung.mongodb.dbref.repository.PersonRepository; -import com.mongodb.BasicDBObjectBuilder; -import com.mongodb.DBObject; -import com.mongodb.DBRef; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/zoneddatetime/ActionRepositoryLiveTest.java b/persistence-modules/spring-boot-persistence-mongodb-4/src/test/java/com/baeldung/zoneddatetime/ActionRepositoryLiveTest.java similarity index 99% rename from persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/zoneddatetime/ActionRepositoryLiveTest.java rename to persistence-modules/spring-boot-persistence-mongodb-4/src/test/java/com/baeldung/zoneddatetime/ActionRepositoryLiveTest.java index 3a241418ca..09ff1d9375 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/zoneddatetime/ActionRepositoryLiveTest.java +++ b/persistence-modules/spring-boot-persistence-mongodb-4/src/test/java/com/baeldung/zoneddatetime/ActionRepositoryLiveTest.java @@ -1,5 +1,8 @@ package com.baeldung.zoneddatetime; +import com.baeldung.zoneddatetime.config.MongoConfig; +import com.baeldung.zoneddatetime.model.Action; +import com.baeldung.zoneddatetime.repository.ActionRepository; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -10,10 +13,6 @@ import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.baeldung.zoneddatetime.config.MongoConfig; -import com.baeldung.zoneddatetime.model.Action; -import com.baeldung.zoneddatetime.repository.ActionRepository; - import java.time.ZoneOffset; import java.time.ZonedDateTime; diff --git a/persistence-modules/spring-boot-persistence-mongodb-4/src/test/resources/application.properties b/persistence-modules/spring-boot-persistence-mongodb-4/src/test/resources/application.properties new file mode 100644 index 0000000000..a5b5fb9804 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb-4/src/test/resources/application.properties @@ -0,0 +1 @@ +spring.mongodb.embedded.version=4.4.9 \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/README.md b/persistence-modules/spring-boot-persistence-mongodb/README.md index 5453eb0052..867b31c639 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/README.md +++ b/persistence-modules/spring-boot-persistence-mongodb/README.md @@ -4,8 +4,6 @@ - [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb) - [Upload and Retrieve Files Using MongoDB and Spring Boot](https://www.baeldung.com/spring-boot-mongodb-upload-file) - [GridFS in Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-gridfs) -- [ZonedDateTime with Spring Data MongoDB](https://www.baeldung.com/spring-data-mongodb-zoneddatetime) -- [A Guide to @DBRef in MongoDB](https://www.baeldung.com/spring-mongodb-dbref-annotation) - [Import Data to MongoDB From JSON File Using Java](https://www.baeldung.com/java-import-json-mongodb) - [Spring Data MongoDB – Configure Connection](https://www.baeldung.com/spring-data-mongodb-connection) - More articles: [[next-->]](../spring-boot-persistence-mongodb-2)