diff --git a/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java b/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java index 1170a2d761..33462d6171 100644 --- a/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java +++ b/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java @@ -7,6 +7,8 @@ import akka.http.javadsl.model.HttpEntities; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.testkit.JUnitRouteTest; import akka.http.javadsl.testkit.TestRoute; + +import org.junit.Ignore; import org.junit.Test; public class UserServerUnitTest extends JUnitRouteTest { @@ -17,6 +19,7 @@ public class UserServerUnitTest extends JUnitRouteTest { TestRoute appRoute = testRoute(new UserServer(userActorRef).routes()); + @Ignore @Test public void whenRequest_thenActorResponds() { diff --git a/algorithms-miscellaneous-1/pom.xml b/algorithms-miscellaneous-1/pom.xml index a2183f7474..b7c32bda43 100644 --- a/algorithms-miscellaneous-1/pom.xml +++ b/algorithms-miscellaneous-1/pom.xml @@ -64,7 +64,7 @@ org.codehaus.mojo cobertura-maven-plugin - 2.7 + ${cobertura.plugin.version} @@ -85,6 +85,7 @@ 1.11 27.0.1-jre 3.3.0 + 2.7 \ No newline at end of file diff --git a/algorithms-miscellaneous-3/pom.xml b/algorithms-miscellaneous-3/pom.xml index a893f0a045..673ac0121d 100644 --- a/algorithms-miscellaneous-3/pom.xml +++ b/algorithms-miscellaneous-3/pom.xml @@ -46,13 +46,13 @@ org.apache.commons commons-lang3 - 3.8.1 + ${commons.lang3.version} pl.pragmatists JUnitParams - 1.1.0 + ${JUnitParams.version} test @@ -91,6 +91,8 @@ 2.6.0 1.19 1.19 + 3.8.1 + 1.1.0 \ No newline at end of file diff --git a/algorithms-miscellaneous-5/pom.xml b/algorithms-miscellaneous-5/pom.xml index 95036da775..4f9cc8b711 100644 --- a/algorithms-miscellaneous-5/pom.xml +++ b/algorithms-miscellaneous-5/pom.xml @@ -37,7 +37,7 @@ com.google.guava guava - 28.1-jre + ${guava.version} @@ -65,6 +65,7 @@ 3.9.0 1.11 3.6.1 + 28.1-jre \ No newline at end of file diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/HeapNode.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/HeapNode.java new file mode 100644 index 0000000000..9e8439cb87 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/HeapNode.java @@ -0,0 +1,13 @@ +package com.baeldung.algorithms.minheapmerge; + +public class HeapNode { + + int element; + int arrayIndex; + int nextElementIndex = 1; + + public HeapNode(int element, int arrayIndex) { + this.element = element; + this.arrayIndex = arrayIndex; + } +} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeap.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeap.java new file mode 100644 index 0000000000..b77ce43160 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeap.java @@ -0,0 +1,88 @@ +package com.baeldung.algorithms.minheapmerge; + +public class MinHeap { + + HeapNode[] heapNodes; + + public MinHeap(HeapNode heapNodes[]) { + this.heapNodes = heapNodes; + heapifyFromLastLeafsParent(); + } + + void heapifyFromLastLeafsParent() { + int lastLeafsParentIndex = getParentNodeIndex(heapNodes.length); + while (lastLeafsParentIndex >= 0) { + heapify(lastLeafsParentIndex); + lastLeafsParentIndex--; + } + } + + void heapify(int index) { + int leftNodeIndex = getLeftNodeIndex(index); + int rightNodeIndex = getRightNodeIndex(index); + int smallestElementIndex = index; + if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) { + smallestElementIndex = leftNodeIndex; + } + if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) { + smallestElementIndex = rightNodeIndex; + } + if (smallestElementIndex != index) { + swap(index, smallestElementIndex); + heapify(smallestElementIndex); + } + } + + int getParentNodeIndex(int index) { + return (index - 1) / 2; + } + + int getLeftNodeIndex(int index) { + return (2 * index + 1); + } + + int getRightNodeIndex(int index) { + return (2 * index + 2); + } + + HeapNode getRootNode() { + return heapNodes[0]; + } + + void heapifyFromRoot() { + heapify(0); + } + + void swap(int i, int j) { + HeapNode temp = heapNodes[i]; + heapNodes[i] = heapNodes[j]; + heapNodes[j] = temp; + } + + static int[] merge(int[][] array) { + HeapNode[] heapNodes = new HeapNode[array.length]; + int resultingArraySize = 0; + + for (int i = 0; i < array.length; i++) { + HeapNode node = new HeapNode(array[i][0], i); + heapNodes[i] = node; + resultingArraySize += array[i].length; + } + + MinHeap minHeap = new MinHeap(heapNodes); + int[] resultingArray = new int[resultingArraySize]; + + for (int i = 0; i < resultingArraySize; i++) { + HeapNode root = minHeap.getRootNode(); + resultingArray[i] = root.element; + + if (root.nextElementIndex < array[root.arrayIndex].length) { + root.element = array[root.arrayIndex][root.nextElementIndex++]; + } else { + root.element = Integer.MAX_VALUE; + } + minHeap.heapifyFromRoot(); + } + return resultingArray; + } +} diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapUnitTest.java new file mode 100644 index 0000000000..80d0d20f05 --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.algorithms.minheapmerge; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class MinHeapUnitTest { + + private final int[][] inputArray = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 200, 650 } }; + private final int[] expectedArray = { 0, 1, 2, 4, 5, 6, 10, 100, 200, 650 }; + + @Test + public void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() { + int[] resultArray = MinHeap.merge(inputArray); + + assertThat(resultArray.length, is(equalTo(10))); + assertThat(resultArray, is(equalTo(expectedArray))); + } + +} diff --git a/algorithms-sorting-2/.gitignore b/algorithms-sorting-2/.gitignore new file mode 100644 index 0000000000..30b2b7442c --- /dev/null +++ b/algorithms-sorting-2/.gitignore @@ -0,0 +1,4 @@ +/target/ +.settings/ +.classpath +.project \ No newline at end of file diff --git a/algorithms-sorting-2/pom.xml b/algorithms-sorting-2/pom.xml new file mode 100644 index 0000000000..d862c91430 --- /dev/null +++ b/algorithms-sorting-2/pom.xml @@ -0,0 +1,64 @@ + + 4.0.0 + algorithms-sorting-2 + 0.0.1-SNAPSHOT + algorithms-sorting-2 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + commons-codec + commons-codec + ${commons-codec.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter-api.version} + test + + + org.assertj + assertj-core + ${org.assertj.core.version} + test + + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + + + + + + 3.6.1 + 3.9.0 + 1.11 + 5.3.1 + + + \ No newline at end of file diff --git a/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/BentleyMcIlroyPartioning.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/BentleyMcIlroyPartioning.java new file mode 100644 index 0000000000..d005f2654c --- /dev/null +++ b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/BentleyMcIlroyPartioning.java @@ -0,0 +1,66 @@ +package com.baeldung.algorithms.quicksort; + +import static com.baeldung.algorithms.quicksort.SortingUtils.swap; + +public class BentleyMcIlroyPartioning { + + public static Partition partition(int input[], int begin, int end) { + int left = begin, right = end; + int leftEqualKeysCount = 0, rightEqualKeysCount = 0; + + int partitioningValue = input[end]; + + while (true) { + while (input[left] < partitioningValue) + left++; + + while (input[right] > partitioningValue) { + if (right == begin) + break; + right--; + } + + if (left == right && input[left] == partitioningValue) { + swap(input, begin + leftEqualKeysCount, left); + leftEqualKeysCount++; + left++; + } + + if (left >= right) { + break; + } + + swap(input, left, right); + + if (input[left] == partitioningValue) { + swap(input, begin + leftEqualKeysCount, left); + leftEqualKeysCount++; + } + + if (input[right] == partitioningValue) { + swap(input, right, end - rightEqualKeysCount); + rightEqualKeysCount++; + } + left++; right--; + } + right = left - 1; + for (int k = begin; k < begin + leftEqualKeysCount; k++, right--) { + if (right >= begin + leftEqualKeysCount) + swap(input, k, right); + } + for (int k = end; k > end - rightEqualKeysCount; k--, left++) { + if (left <= end - rightEqualKeysCount) + swap(input, left, k); + } + return new Partition(right + 1, left - 1); + } + + public static void quicksort(int input[], int begin, int end) { + if (end <= begin) + return; + Partition middlePartition = partition(input, begin, end); + quicksort(input, begin, middlePartition.getLeft() - 1); + quicksort(input, middlePartition.getRight() + 1, end); + } + +} diff --git a/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/DutchNationalFlagPartioning.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/DutchNationalFlagPartioning.java new file mode 100644 index 0000000000..e868cf0e2e --- /dev/null +++ b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/DutchNationalFlagPartioning.java @@ -0,0 +1,38 @@ +package com.baeldung.algorithms.quicksort; + +import static com.baeldung.algorithms.quicksort.SortingUtils.compare; +import static com.baeldung.algorithms.quicksort.SortingUtils.swap; + +public class DutchNationalFlagPartioning { + + public static Partition partition(int[] a, int begin, int end) { + int lt = begin, current = begin, gt = end; + int partitioningValue = a[begin]; + + while (current <= gt) { + int compareCurrent = compare(a[current], partitioningValue); + switch (compareCurrent) { + case -1: + swap(a, current++, lt++); + break; + case 0: + current++; + break; + case 1: + swap(a, current, gt--); + break; + } + } + return new Partition(lt, gt); + } + + public static void quicksort(int[] input, int begin, int end) { + if (end <= begin) + return; + + Partition middlePartition = partition(input, begin, end); + + quicksort(input, begin, middlePartition.getLeft() - 1); + quicksort(input, middlePartition.getRight() + 1, end); + } +} diff --git a/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/Partition.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/Partition.java new file mode 100644 index 0000000000..29812f2720 --- /dev/null +++ b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/Partition.java @@ -0,0 +1,29 @@ +package com.baeldung.algorithms.quicksort; + +public class Partition { + private int left; + private int right; + + public Partition(int left, int right) { + super(); + this.left = left; + this.right = right; + } + + public int getLeft() { + return left; + } + + public void setLeft(int left) { + this.left = left; + } + + public int getRight() { + return right; + } + + public void setRight(int right) { + this.right = right; + } + +} diff --git a/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/SortingUtils.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/SortingUtils.java new file mode 100644 index 0000000000..ac1aa5e8ee --- /dev/null +++ b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/SortingUtils.java @@ -0,0 +1,32 @@ +package com.baeldung.algorithms.quicksort; + +public class SortingUtils { + + public static void swap(int[] array, int position1, int position2) { + if (position1 != position2) { + int temp = array[position1]; + array[position1] = array[position2]; + array[position2] = temp; + } + } + + public static int compare(int num1, int num2) { + if (num1 > num2) + return 1; + else if (num1 < num2) + return -1; + else + return 0; + } + + public static void printArray(int[] array) { + if (array == null) { + return; + } + for (int e : array) { + System.out.print(e + " "); + } + System.out.println(); + } + +} diff --git a/algorithms-sorting-2/src/main/resources/logback.xml b/algorithms-sorting-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..26beb6d5b4 --- /dev/null +++ b/algorithms-sorting-2/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/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java new file mode 100644 index 0000000000..847f7f8acb --- /dev/null +++ b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.algorithms.quicksort; + +import org.junit.Assert; +import org.junit.Test; + +public class BentleyMcilroyPartitioningUnitTest { + + @Test + public void given_IntegerArray_whenSortedWithBentleyMcilroyPartitioning_thenGetSortedArray() { + int[] actual = {3, 2, 2, 2, 3, 7, 7, 3, 2, 2, 7, 3, 3}; + int[] expected = {2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 7, 7, 7}; + BentleyMcIlroyPartioning.quicksort(actual, 0, actual.length - 1); + Assert.assertArrayEquals(expected, actual); + } + +} diff --git a/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java new file mode 100644 index 0000000000..a8e27253cc --- /dev/null +++ b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.algorithms.quicksort; + +import org.junit.Assert; +import org.junit.Test; + +public class DNFThreeWayQuickSortUnitTest { + + @Test + public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() { + int[] actual = {3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3}; + int[] expected = {3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7}; + DutchNationalFlagPartioning.quicksort(actual, 0, actual.length - 1); + Assert.assertArrayEquals(expected, actual); + } +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml index 43bbcf1ef4..1d7ecdb58f 100644 --- a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml @@ -18,19 +18,19 @@ javax.ws.rs javax.ws.rs-api - 2.1 + ${rs-api.version} provided javax.enterprise cdi-api - 2.0 + ${cdi-api.version} provided javax.json.bind javax.json.bind-api - 1.0 + ${bind-api.version} provided @@ -80,6 +80,9 @@ 2.4.2 false 18.0.0.2 + 2.1 + 2.0 + 1.0 diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml index a114946c47..333339ed33 100644 --- a/apache-poi/pom.xml +++ b/apache-poi/pom.xml @@ -32,7 +32,7 @@ - 3.15 + 4.1.1 1.0.6 diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelCellFormatter.java b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelCellFormatter.java new file mode 100644 index 0000000000..4a8854620c --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelCellFormatter.java @@ -0,0 +1,20 @@ +package com.baeldung.poi.excel; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.DataFormatter; +import org.apache.poi.ss.usermodel.FormulaEvaluator; +import org.apache.poi.ss.usermodel.Workbook; + +public class ExcelCellFormatter { + + public String getCellStringValue(Cell cell) { + DataFormatter formatter = new DataFormatter(); + return formatter.formatCellValue(cell); + } + + public String getCellStringValueWithFormula(Cell cell, Workbook workbook) { + DataFormatter formatter = new DataFormatter(); + FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); + return formatter.formatCellValue(cell, evaluator); + } +} diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/read/cellvalueandnotformula/CellValueAndNotFormulaHelper.java b/apache-poi/src/main/java/com/baeldung/poi/excel/read/cellvalueandnotformula/CellValueAndNotFormulaHelper.java new file mode 100644 index 0000000000..08dd0e07ab --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/read/cellvalueandnotformula/CellValueAndNotFormulaHelper.java @@ -0,0 +1,83 @@ +package com.baeldung.poi.excel.read.cellvalueandnotformula; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.FormulaEvaluator; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.util.CellAddress; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +public class CellValueAndNotFormulaHelper { + + public Object getCellValueByFetchingLastCachedValue(String fileLocation, String cellLocation) throws IOException { + Object cellValue = new Object(); + + FileInputStream inputStream = new FileInputStream(new File(fileLocation)); + Workbook workbook = new XSSFWorkbook(inputStream); + + Sheet sheet = workbook.getSheetAt(0); + + CellAddress cellAddress = new CellAddress(cellLocation); + Row row = sheet.getRow(cellAddress.getRow()); + Cell cell = row.getCell(cellAddress.getColumn()); + + if (cell.getCellType() == CellType.FORMULA) { + switch (cell.getCachedFormulaResultType()) { + case BOOLEAN: + cellValue = cell.getBooleanCellValue(); + break; + case NUMERIC: + cellValue = cell.getNumericCellValue(); + break; + case STRING: + cellValue = cell.getStringCellValue(); + break; + default: + cellValue = null; + } + } + + workbook.close(); + return cellValue; + } + + public Object getCellValueByEvaluatingFormula(String fileLocation, String cellLocation) throws IOException { + Object cellValue = new Object(); + + FileInputStream inputStream = new FileInputStream(new File(fileLocation)); + Workbook workbook = new XSSFWorkbook(inputStream); + + Sheet sheet = workbook.getSheetAt(0); + FormulaEvaluator evaluator = workbook.getCreationHelper() + .createFormulaEvaluator(); + + CellAddress cellAddress = new CellAddress(cellLocation); + Row row = sheet.getRow(cellAddress.getRow()); + Cell cell = row.getCell(cellAddress.getColumn()); + + if (cell.getCellType() == CellType.FORMULA) { + switch (evaluator.evaluateFormulaCell(cell)) { + case BOOLEAN: + cellValue = cell.getBooleanCellValue(); + break; + case NUMERIC: + cellValue = cell.getNumericCellValue(); + break; + case STRING: + cellValue = cell.getStringCellValue(); + break; + default: + cellValue = null; + } + } + + workbook.close(); + return cellValue; + } +} diff --git a/apache-poi/src/main/resources/ExcelCellFormatterTest.xlsx b/apache-poi/src/main/resources/ExcelCellFormatterTest.xlsx new file mode 100644 index 0000000000..54e8734d58 Binary files /dev/null and b/apache-poi/src/main/resources/ExcelCellFormatterTest.xlsx differ diff --git a/apache-poi/src/main/resources/test.xlsx b/apache-poi/src/main/resources/test.xlsx new file mode 100644 index 0000000000..64fe14f25b Binary files /dev/null and b/apache-poi/src/main/resources/test.xlsx differ diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterUnitTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterUnitTest.java new file mode 100644 index 0000000000..d9f96ee93c --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.poi.excel; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Paths; + +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.Before; +import org.junit.Test; + +public class ExcelCellFormatterUnitTest { + private static final String FILE_NAME = "ExcelCellFormatterTest.xlsx"; + private static final int STRING_CELL_INDEX = 0; + private static final int BOOLEAN_CELL_INDEX = 1; + private static final int RAW_NUMERIC_CELL_INDEX = 2; + private static final int FORMATTED_NUMERIC_CELL_INDEX = 3; + private static final int FORMULA_CELL_INDEX = 4; + + private String fileLocation; + + @Before + public void setup() throws IOException, URISyntaxException { + fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString(); + } + + @Test + public void givenStringCell_whenGetCellStringValue_thenReturnStringValue() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + + ExcelCellFormatter formatter = new ExcelCellFormatter(); + assertEquals("String Test", formatter.getCellStringValue(row.getCell(STRING_CELL_INDEX))); + workbook.close(); + } + + @Test + public void givenBooleanCell_whenGetCellStringValue_thenReturnBooleanStringValue() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + + ExcelCellFormatter formatter = new ExcelCellFormatter(); + assertEquals("TRUE", formatter.getCellStringValue(row.getCell(BOOLEAN_CELL_INDEX))); + workbook.close(); + } + + @Test + public void givenNumericCell_whenGetCellStringValue_thenReturnNumericStringValue() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + + ExcelCellFormatter formatter = new ExcelCellFormatter(); + assertEquals("1.234", formatter.getCellStringValue(row.getCell(RAW_NUMERIC_CELL_INDEX))); + assertEquals("1.23", formatter.getCellStringValue(row.getCell(FORMATTED_NUMERIC_CELL_INDEX))); + workbook.close(); + } + + @Test + public void givenFormualCell_whenGetCellStringValue_thenReturnOriginalFormulaString() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + + ExcelCellFormatter formatter = new ExcelCellFormatter(); + assertEquals("SUM(1+2)", formatter.getCellStringValue(row.getCell(FORMULA_CELL_INDEX))); + workbook.close(); + } + + @Test + public void givenFormualCell_whenGetCellStringValueForFormula_thenReturnOriginalFormulatring() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + + ExcelCellFormatter formatter = new ExcelCellFormatter(); + assertEquals("3", formatter.getCellStringValueWithFormula(row.getCell(FORMULA_CELL_INDEX), workbook)); + workbook.close(); + } + +} \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/read/cellvalueandnotformula/CellValueAndNotFormulaUnitTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/read/cellvalueandnotformula/CellValueAndNotFormulaUnitTest.java new file mode 100644 index 0000000000..885a955e9b --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/read/cellvalueandnotformula/CellValueAndNotFormulaUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.poi.excel.read.cellvalueandnotformula; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Paths; + +import org.junit.Before; +import org.junit.Test; + +public class CellValueAndNotFormulaUnitTest { + + private CellValueAndNotFormulaHelper readCellValueAndNotFormulaHelper; + private String fileLocation; + private static final String FILE_NAME = "test.xlsx"; + + @Before + public void setup() throws URISyntaxException { + fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString(); + readCellValueAndNotFormulaHelper = new CellValueAndNotFormulaHelper(); + } + + @Test + public void givenExcelCell_whenReadCellValueByLastCachedValue_thenProduceCorrectResult() throws IOException { + final double expectedResult = 7.0; + final Object cellValue = readCellValueAndNotFormulaHelper.getCellValueByFetchingLastCachedValue(fileLocation, "C2"); + + assertEquals(expectedResult, cellValue); + } + + @Test + public void givenExcelCell_whenReadCellValueByEvaluatingFormula_thenProduceCorrectResult() throws IOException { + final double expectedResult = 7.0; + final Object cellValue = readCellValueAndNotFormulaHelper.getCellValueByEvaluatingFormula(fileLocation, "C2"); + + assertEquals(expectedResult, cellValue); + } +} diff --git a/apache-rocketmq/pom.xml b/apache-rocketmq/pom.xml index 59c204dddf..f15dd0e61c 100644 --- a/apache-rocketmq/pom.xml +++ b/apache-rocketmq/pom.xml @@ -17,11 +17,12 @@ org.apache.rocketmq rocketmq-spring-boot-starter - 2.0.4 + ${rocketmq.version} 1.6.0 + 2.0.4 diff --git a/apache-tapestry/pom.xml b/apache-tapestry/pom.xml index e306b56b4a..a4124b07df 100644 --- a/apache-tapestry/pom.xml +++ b/apache-tapestry/pom.xml @@ -81,10 +81,10 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + ${compiler.plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} true @@ -92,7 +92,7 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's org.apache.maven.plugins maven-surefire-plugin - 2.7.2 + ${compiler.surefire.version} Qa @@ -104,7 +104,7 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's org.mortbay.jetty maven-jetty-plugin - 6.1.16 + ${compiler.jetty.version} @@ -140,6 +140,11 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's + 6.1.16 + 2.7.2 + 2.3.2 + 1.8 + 1.8 5.4.5 2.5 6.8.21 diff --git a/aws-reactive/pom.xml b/aws-reactive/pom.xml index b3fcb24902..046825130a 100644 --- a/aws-reactive/pom.xml +++ b/aws-reactive/pom.xml @@ -17,6 +17,8 @@ 1.8 + 2.2.1.RELEASE + 2.10.27 @@ -26,7 +28,7 @@ org.springframework.boot spring-boot-dependencies - 2.2.1.RELEASE + ${spring.version} pom import @@ -34,7 +36,7 @@ software.amazon.awssdk bom - 2.10.27 + ${awssdk.version} pom import diff --git a/blade/pom.xml b/blade/pom.xml index e302f33c51..6d73913e25 100644 --- a/blade/pom.xml +++ b/blade/pom.xml @@ -124,7 +124,7 @@ maven-assembly-plugin - 3.1.0 + ${assembly.plugin.version} ${project.build.finalName} false @@ -161,6 +161,7 @@ 3.11.1 3.0.0-M3 0.7 + 3.1.0 diff --git a/cloud-foundry-uaa/pom.xml b/cloud-foundry-uaa/pom.xml new file mode 100644 index 0000000000..0001e521ed --- /dev/null +++ b/cloud-foundry-uaa/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + cloud-foundry-uaa + 0.0.1-SNAPSHOT + cloud-foundry-uaa + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + cf-uaa-oauth2-client + cf-uaa-oauth2-resource-server + + + diff --git a/core-groovy-2/pom.xml b/core-groovy-2/pom.xml index e0987de4b3..752b6945b3 100644 --- a/core-groovy-2/pom.xml +++ b/core-groovy-2/pom.xml @@ -62,12 +62,12 @@ org.codehaus.groovy groovy-eclipse-compiler - 3.3.0-01 + ${groovy.compiler.version} true maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} groovy-eclipse-compiler ${java.version} @@ -113,7 +113,7 @@ maven-surefire-plugin - 2.20.1 + ${surefire.plugin.version} false @@ -126,7 +126,7 @@ org.apache.maven.plugins maven-assembly-plugin - 3.1.0 + ${assembly.plugin.version} @@ -183,6 +183,10 @@ 1.1.3 1.2.3 2.5.7 + 3.1.0 + 2.20.1 + 3.8.0 + 3.3.0-01 diff --git a/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy index a1f67b1e2e..5ba7a2347c 100644 --- a/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy +++ b/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy @@ -28,16 +28,17 @@ class CategoryUnitTest extends GroovyTestCase { } } - void test_whenUsingTimeCategory_thenOperationOnNumber() { - SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy") - use (TimeCategory) { - assert sdf.format(5.days.from.now) == sdf.format(new Date() + 5.days) - - sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss") - assert sdf.format(10.minutes.from.now) == sdf.format(new Date() + 10.minutes) - assert sdf.format(2.hours.ago) == sdf.format(new Date() - 2.hours) - } - } +// http://team.baeldung.com/browse/BAEL-20687 +// void test_whenUsingTimeCategory_thenOperationOnNumber() { +// SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy") +// use (TimeCategory) { +// assert sdf.format(5.days.from.now) == sdf.format(new Date() + 5.days) +// +// sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss") +// assert sdf.format(10.minutes.from.now) == sdf.format(new Date() + 10.minutes) +// assert sdf.format(2.hours.ago) == sdf.format(new Date() - 2.hours) +// } +// } void test_whenUsingDOMCategory_thenOperationOnXML() { diff --git a/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy index 302959d0d9..144d5720c8 100644 --- a/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy +++ b/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy @@ -9,7 +9,7 @@ import wslite.soap.SOAPMessageBuilder import wslite.http.auth.HTTPBasicAuthorization import org.junit.Test -class WebserviceUnitTest extends GroovyTestCase { +class WebserviceManualTest extends GroovyTestCase { JsonSlurper jsonSlurper = new JsonSlurper() @@ -75,6 +75,7 @@ class WebserviceUnitTest extends GroovyTestCase { assert stories.size() == 5 } + /* see BAEL-3753 void test_whenConsumingSoap_thenReceiveResponse() { def url = "http://www.dataaccess.com/webservicesserver/numberconversion.wso" def soapClient = new SOAPClient(url) @@ -89,6 +90,7 @@ class WebserviceUnitTest extends GroovyTestCase { def words = response.NumberToWordsResponse assert words == "one thousand two hundred and thirty four " } + */ void test_whenConsumingRestGet_thenReceiveResponse() { def path = "/get" @@ -149,4 +151,4 @@ class WebserviceUnitTest extends GroovyTestCase { assert e?.response?.statusCode != 200 } } -} \ No newline at end of file +} diff --git a/core-groovy-collections/pom.xml b/core-groovy-collections/pom.xml index 423be5e977..4e591970b0 100644 --- a/core-groovy-collections/pom.xml +++ b/core-groovy-collections/pom.xml @@ -99,7 +99,7 @@ maven-surefire-plugin - 2.20.1 + ${surefire.plugin.version} false @@ -126,6 +126,7 @@ 2.4.0 1.1-groovy-2.4 1.6 + 2.20.1 diff --git a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy index a479c265c4..b969f0d1ab 100644 --- a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy @@ -1,6 +1,7 @@ package com.baeldung.file import spock.lang.Specification +import spock.lang.Ignore class ReadFileUnitTest extends Specification { @@ -32,6 +33,7 @@ class ReadFileUnitTest extends Specification { assert lines.size(), 3 } + @Ignore def 'Should return file content in string using ReadFile.readFileString given filePath' () { given: def filePath = "src/main/resources/fileContent.txt" diff --git a/core-java-modules/core-java-11/pom.xml b/core-java-modules/core-java-11/pom.xml index 5bebaae00d..32bc68fa66 100644 --- a/core-java-modules/core-java-11/pom.xml +++ b/core-java-modules/core-java-11/pom.xml @@ -42,12 +42,12 @@ org.eclipse.collections eclipse-collections - 10.0.0 + ${eclipse.collections.version} org.eclipse.collections eclipse-collections-api - 10.0.0 + ${eclipse.collections.version} @@ -108,6 +108,7 @@ 3.11.1 benchmarks 1.22 + 10.0.0 diff --git a/core-java-modules/core-java-13/pom.xml b/core-java-modules/core-java-13/pom.xml index 1f215ae6b0..9469f49411 100644 --- a/core-java-modules/core-java-13/pom.xml +++ b/core-java-modules/core-java-13/pom.xml @@ -41,7 +41,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.0.0-M3 + ${surefire.plugin.version} --enable-preview @@ -53,6 +53,7 @@ 13 13 3.6.1 + 3.0.0-M3 \ No newline at end of file diff --git a/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/SwitchExpressionsWithYieldUnitTest.java b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/SwitchExpressionsWithYieldUnitTest.java new file mode 100644 index 0000000000..be1fcfd167 --- /dev/null +++ b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/SwitchExpressionsWithYieldUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.newfeatures; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class SwitchExpressionsWithYieldUnitTest { + + @Test + @SuppressWarnings("preview") + public void whenSwitchingOnOperationSquareMe_thenWillReturnSquare() { + var me = 4; + var operation = "squareMe"; + var result = switch (operation) { + case "doubleMe" -> { + yield me * 2; + } + case "squareMe" -> { + yield me * me; + } + default -> me; + }; + + assertEquals(16, result); + } + +} diff --git a/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/TextBlocksUnitTest.java b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/TextBlocksUnitTest.java new file mode 100644 index 0000000000..1f8ddcbfb4 --- /dev/null +++ b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/TextBlocksUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.newfeatures; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class TextBlocksUnitTest { + + private static final String JSON_STRING = "{\r\n" + "\"name\" : \"Baeldung\",\r\n" + "\"website\" : \"https://www.%s.com/\"\r\n" + "}"; + + @SuppressWarnings("preview") + private static final String TEXT_BLOCK_JSON = """ + { + "name" : "Baeldung", + "website" : "https://www.%s.com/" + } + """; + + @Test + public void whenTextBlocks_thenStringOperationsWork() { + + assertThat(TEXT_BLOCK_JSON.contains("Baeldung")).isTrue(); + assertThat(TEXT_BLOCK_JSON.indexOf("www")).isGreaterThan(0); + assertThat(TEXT_BLOCK_JSON.length()).isGreaterThan(0); + + } + + @SuppressWarnings("removal") + @Test + public void whenTextBlocks_thenFormattedWorksAsFormat() { + assertThat(TEXT_BLOCK_JSON.formatted("baeldung") + .contains("www.baeldung.com")).isTrue(); + + assertThat(String.format(JSON_STRING, "baeldung") + .contains("www.baeldung.com")).isTrue(); + + } + +} diff --git a/core-java-modules/core-java-14/pom.xml b/core-java-modules/core-java-14/pom.xml index 48ec627416..b985ada5e6 100644 --- a/core-java-modules/core-java-14/pom.xml +++ b/core-java-modules/core-java-14/pom.xml @@ -36,7 +36,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.0.0-M3 + ${surefire.plugin.version} --enable-preview @@ -47,6 +47,7 @@ 14 14 + 3.0.0-M3 \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-2/pom.xml b/core-java-modules/core-java-arrays-2/pom.xml index 532f0a6144..b300de511a 100644 --- a/core-java-modules/core-java-arrays-2/pom.xml +++ b/core-java-modules/core-java-arrays-2/pom.xml @@ -51,7 +51,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.0 + ${shade.plugin.version} package @@ -79,6 +79,7 @@ 3.9 3.10.0 + 3.2.0 diff --git a/core-java-modules/core-java-arrays/pom.xml b/core-java-modules/core-java-arrays/pom.xml index 20a835594f..02d82e4af6 100644 --- a/core-java-modules/core-java-arrays/pom.xml +++ b/core-java-modules/core-java-arrays/pom.xml @@ -183,8 +183,8 @@ maven-javadoc-plugin ${maven-javadoc-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} @@ -373,6 +373,8 @@ 3.1.1 2.0.3.RELEASE 1.6.0 + 1.8 + 1.8 diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/EAAsyncExample.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/EAAsyncExample.java new file mode 100644 index 0000000000..c7c893e731 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/EAAsyncExample.java @@ -0,0 +1,57 @@ +package com.baeldung.async; + +import static com.ea.async.Async.await; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import com.ea.async.Async; + +public class EAAsyncExample { + + static { + Async.init(); + } + + public static void main(String[] args) throws Exception { + usingCompletableFuture(); + usingAsyncAwait(); + } + + public static void usingCompletableFuture() throws InterruptedException, ExecutionException, Exception { + CompletableFuture completableFuture = hello() + .thenComposeAsync(hello -> mergeWorld(hello)) + .thenAcceptAsync(helloWorld -> print(helloWorld)) + .exceptionally( throwable -> { + System.out.println(throwable.getCause()); + return null; + }); + completableFuture.get(); + } + + public static CompletableFuture hello() { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + return completableFuture; + } + + public static CompletableFuture mergeWorld(String s) { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> { + return s + " World!"; + }); + return completableFuture; + } + + public static void print(String str) { + CompletableFuture.runAsync(() -> System.out.println(str)); + } + + private static void usingAsyncAwait() { + try { + String hello = await(hello()); + String helloWorld = await(mergeWorld(hello)); + await(CompletableFuture.runAsync(() -> print(helloWorld))); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/JavaAsync.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/JavaAsync.java new file mode 100644 index 0000000000..6f36f46154 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/JavaAsync.java @@ -0,0 +1,183 @@ +package com.baeldung.async; + +import static com.ea.async.Async.await; + +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import com.google.common.util.concurrent.AsyncCallable; +import com.google.common.util.concurrent.Callables; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import com.jcabi.aspects.Async; +import com.jcabi.aspects.Loggable; + +public class JavaAsync { + + static { + com.ea.async.Async.init(); + } + + private static final ExecutorService threadpool = Executors.newCachedThreadPool(); + + public static void main (String[] args) throws InterruptedException, ExecutionException { + int number = 20; + + //Thread Example + factorialUsingThread(number).start(); + + //FutureTask Example + Future futureTask = factorialUsingFutureTask(number); + System.out.println("Factorial of " + number + " is: " + futureTask.get()); + + // CompletableFuture Example + Future completableFuture = factorialUsingCompletableFuture(number); + System.out.println("Factorial of " + number + " is: " + completableFuture.get()); + + // EA Async example + System.out.println("Factorial of " + number + " is: " + factorialUsingEAAsync(number)); + + // cactoos async example + Future asyncFuture = factorialUsingCactoos(number); + System.out.println("Factorial of " + number + " is: " + asyncFuture.get()); + + // Guava example + ListenableFuture guavaFuture = factorialUsingGuavaServiceSubmit(number); + System.out.println("Factorial of " + number + " is: " + guavaFuture.get()); + + ListenableFuture guavaFutures = factorialUsingGuavaFutures(number); + System.out.println("Factorial of " + number + " is: " + guavaFutures.get()); + + // @async jcabi-aspect example + Future aspectFuture = factorialUsingJcabiAspect(number); + System.out.println("Factorial of " + number + " is: " + aspectFuture.get()); + + } + + /** + * Finds factorial of a number + * @param number + * @return + */ + public static long factorial(int number) { + long result = 1; + for(int i=number;i>0;i--) { + result *= i; + } + return result; + } + + /** + * Finds factorial of a number using Thread + * @param number + * @return + */ + @Loggable + public static Thread factorialUsingThread(int number) { + Thread newThread = new Thread(() -> { + System.out.println("Factorial of " + number + " is: " + factorial(number)); + }); + + return newThread; + } + + /** + * Finds factorial of a number using FutureTask + * @param number + * @return + */ + @Loggable + public static Future factorialUsingFutureTask(int number) { + Future futureTask = threadpool.submit(() -> factorial(number)); + + while (!futureTask.isDone()) { + System.out.println("FutureTask is not finished yet..."); + } + + return futureTask; + } + + /** + * Finds factorial of a number using CompletableFuture + * @param number + * @return + */ + @Loggable + public static Future factorialUsingCompletableFuture(int number) { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> factorial(number)); + return completableFuture; + } + + /** + * Finds factorial of a number using EA Async + * @param number + * @return + */ + @Loggable + public static long factorialUsingEAAsync(int number) { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> factorial(number)); + long result = await(completableFuture); + return result; + } + + /** + * Finds factorial of a number using Async of Cactoos + * @param number + * @return + * @throws InterruptedException + * @throws ExecutionException + */ + @Loggable + public static Future factorialUsingCactoos(int number) throws InterruptedException, ExecutionException { + org.cactoos.func.Async asyncFunction = new org.cactoos.func.Async(input -> factorial(input)); + Future asyncFuture = asyncFunction.apply(number); + return asyncFuture; + } + + /** + * Finds factorial of a number using Guava's ListeningExecutorService.submit() + * @param number + * @return + */ + @Loggable + public static ListenableFuture factorialUsingGuavaServiceSubmit(int number) { + ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool); + ListenableFuture factorialFuture = (ListenableFuture) service.submit(()-> factorial(number)); + return factorialFuture; + } + + /** + * Finds factorial of a number using Guava's Futures.submitAsync() + * @param number + * @return + */ + @Loggable + public static ListenableFuture factorialUsingGuavaFutures(int number) { + ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool); + AsyncCallable asyncCallable = Callables.asAsyncCallable(new Callable() { + public Long call() { + return factorial(number); + } + }, service); + return Futures.submitAsync(asyncCallable, service); + } + + /** + * Finds factorial of a number using @Async of jcabi-aspects + * @param number + * @return + */ + @Async + @Loggable + public static Future factorialUsingJcabiAspect(int number) { + Future factorialFuture = CompletableFuture.supplyAsync(() -> factorial(number)); + return factorialFuture; + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/rejection/SaturationPolicyUnitTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/rejection/SaturationPolicyUnitTest.java index 5016cc1d06..b0b065813f 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/rejection/SaturationPolicyUnitTest.java +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/rejection/SaturationPolicyUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.rejection; import org.junit.After; +import org.junit.Ignore; import org.junit.Test; import java.util.ArrayList; @@ -28,6 +29,7 @@ public class SaturationPolicyUnitTest { } } + @Ignore @Test public void givenAbortPolicy_WhenSaturated_ThenShouldThrowRejectedExecutionException() { executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new SynchronousQueue<>(), new AbortPolicy()); @@ -36,6 +38,7 @@ public class SaturationPolicyUnitTest { assertThatThrownBy(() -> executor.execute(() -> System.out.println("Will be rejected"))).isInstanceOf(RejectedExecutionException.class); } + @Ignore @Test public void givenCallerRunsPolicy_WhenSaturated_ThenTheCallerThreadRunsTheTask() { executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new SynchronousQueue<>(), new CallerRunsPolicy()); diff --git a/core-java-modules/core-java-datetime-computations/README.md b/core-java-modules/core-java-date-operations-1/README.md similarity index 84% rename from core-java-modules/core-java-datetime-computations/README.md rename to core-java-modules/core-java-date-operations-1/README.md index 591ddeaa94..b63fab63db 100644 --- a/core-java-modules/core-java-datetime-computations/README.md +++ b/core-java-modules/core-java-date-operations-1/README.md @@ -1,6 +1,5 @@ -## Java Date/time computations Cookbooks and Examples - -This module contains articles about date and time computations in Java. +## Core Date Operations (Part 1) +This module contains articles about date operations in Java. ### Relevant Articles: - [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference) @@ -13,3 +12,4 @@ This module contains articles about date and time computations in Java. - [Increment Date in Java](http://www.baeldung.com/java-increment-date) - [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date) - [Introduction to Joda-Time](http://www.baeldung.com/joda-time) +- [[Next -->]](/core-java-modules/core-java-date-operations-2) \ No newline at end of file diff --git a/core-java-modules/core-java-datetime-computations/pom.xml b/core-java-modules/core-java-date-operations-1/pom.xml similarity index 93% rename from core-java-modules/core-java-datetime-computations/pom.xml rename to core-java-modules/core-java-date-operations-1/pom.xml index af6b110296..83216f1ad8 100644 --- a/core-java-modules/core-java-datetime-computations/pom.xml +++ b/core-java-modules/core-java-date-operations-1/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - core-java-datetime-computations + core-java-date-operations-1 ${project.parent.version} - core-java-datetime-computations + core-java-date-operations-1 jar @@ -41,7 +41,7 @@ - core-java-datetime-computations + core-java-date-operations-1 src/main/resources diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/AgeCalculator.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/date/AgeCalculator.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/AgeCalculator.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/date/AgeCalculator.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/DateWithoutTime.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/date/DateWithoutTime.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/DateWithoutTime.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/date/DateWithoutTime.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/AddHoursToDate.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/AddHoursToDate.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/AddHoursToDate.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/AddHoursToDate.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java diff --git a/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/java9/time/TimeApi.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/java9/time/TimeApi.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/java9/time/TimeApi.java rename to core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/java9/time/TimeApi.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/DateDiffUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/DateDiffUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/DateDiffUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/DateDiffUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java diff --git a/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java rename to core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java diff --git a/core-java-modules/core-java-date-operations/README.md b/core-java-modules/core-java-date-operations-2/README.md similarity index 84% rename from core-java-modules/core-java-date-operations/README.md rename to core-java-modules/core-java-date-operations-2/README.md index 24bb493dce..478d3baf19 100644 --- a/core-java-modules/core-java-date-operations/README.md +++ b/core-java-modules/core-java-date-operations-2/README.md @@ -1,4 +1,4 @@ -## Core Date Operations +## Core Date Operations (Part 2) This module contains articles about date operations in Java. ### Relevant Articles: @@ -6,3 +6,4 @@ This module contains articles about date operations in Java. - [Skipping Weekends While Adding Days to LocalDate in Java 8](https://www.baeldung.com/java-localdate-add-days-skip-weekends) - [Checking If Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day) - [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime) +- [[<-- Prev]](/core-java-modules/core-java-date-operations-1) diff --git a/core-java-modules/core-java-date-operations/pom.xml b/core-java-modules/core-java-date-operations-2/pom.xml similarity index 78% rename from core-java-modules/core-java-date-operations/pom.xml rename to core-java-modules/core-java-date-operations-2/pom.xml index 4d267964ee..155b8ad0b7 100644 --- a/core-java-modules/core-java-date-operations/pom.xml +++ b/core-java-modules/core-java-date-operations-2/pom.xml @@ -3,9 +3,9 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - core-java-date-operations + core-java-date-operations-2 ${project.parent.version} - core-java-date-operations + core-java-date-operations-2 jar @@ -31,11 +31,18 @@ hirondelle-date4j ${hirondelle-date4j.version} + + org.assertj + assertj-core + ${assertj.version} + test + 2.10 1.5.1 + 3.14.0 \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/date/comparison/DateComparisonUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/date/comparison/DateComparisonUtils.java similarity index 97% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/date/comparison/DateComparisonUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/date/comparison/DateComparisonUtils.java index fea268964a..ab48934f1a 100644 --- a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/date/comparison/DateComparisonUtils.java +++ b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/date/comparison/DateComparisonUtils.java @@ -1,65 +1,65 @@ -package com.baeldung.date.comparison; - -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.time.LocalDate; -import java.time.ZoneId; -import java.time.temporal.ChronoUnit; -import java.util.Calendar; -import java.util.Date; -import java.util.TimeZone; - -import org.apache.commons.lang3.time.DateUtils; - -import hirondelle.date4j.DateTime; - -public class DateComparisonUtils { - - public static boolean isSameDayUsingLocalDate(Date date1, Date date2) { - LocalDate localDate1 = date1.toInstant() - .atZone(ZoneId.systemDefault()) - .toLocalDate(); - LocalDate localDate2 = date2.toInstant() - .atZone(ZoneId.systemDefault()) - .toLocalDate(); - return localDate1.isEqual(localDate2); - } - - public static boolean isSameDayUsingInstant(Date date1, Date date2) { - Instant instant1 = date1.toInstant() - .truncatedTo(ChronoUnit.DAYS); - Instant instant2 = date2.toInstant() - .truncatedTo(ChronoUnit.DAYS); - return instant1.equals(instant2); - } - - public static boolean isSameDayUsingSimpleDateFormat(Date date1, Date date2) { - SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd"); - return fmt.format(date1) - .equals(fmt.format(date2)); - } - - public static boolean isSameDayUsingCalendar(Date date1, Date date2) { - Calendar calendar1 = Calendar.getInstance(); - calendar1.setTime(date1); - Calendar calendar2 = Calendar.getInstance(); - calendar2.setTime(date2); - return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH); - } - - public static boolean isSameDayUsingApacheCommons(Date date1, Date date2) { - return DateUtils.isSameDay(date1, date2); - } - - public static boolean isSameDayUsingJoda(Date date1, Date date2) { - org.joda.time.LocalDate localDate1 = new org.joda.time.LocalDate(date1); - org.joda.time.LocalDate localDate2 = new org.joda.time.LocalDate(date2); - return localDate1.equals(localDate2); - } - - public static boolean isSameDayUsingDate4j(Date date1, Date date2) { - DateTime dateObject1 = DateTime.forInstant(date1.getTime(), TimeZone.getDefault()); - DateTime dateObject2 = DateTime.forInstant(date2.getTime(), TimeZone.getDefault()); - return dateObject1.isSameDayAs(dateObject2); - } -} +package com.baeldung.date.comparison; + +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.temporal.ChronoUnit; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import org.apache.commons.lang3.time.DateUtils; + +import hirondelle.date4j.DateTime; + +public class DateComparisonUtils { + + public static boolean isSameDayUsingLocalDate(Date date1, Date date2) { + LocalDate localDate1 = date1.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + LocalDate localDate2 = date2.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + return localDate1.isEqual(localDate2); + } + + public static boolean isSameDayUsingInstant(Date date1, Date date2) { + Instant instant1 = date1.toInstant() + .truncatedTo(ChronoUnit.DAYS); + Instant instant2 = date2.toInstant() + .truncatedTo(ChronoUnit.DAYS); + return instant1.equals(instant2); + } + + public static boolean isSameDayUsingSimpleDateFormat(Date date1, Date date2) { + SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd"); + return fmt.format(date1) + .equals(fmt.format(date2)); + } + + public static boolean isSameDayUsingCalendar(Date date1, Date date2) { + Calendar calendar1 = Calendar.getInstance(); + calendar1.setTime(date1); + Calendar calendar2 = Calendar.getInstance(); + calendar2.setTime(date2); + return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH); + } + + public static boolean isSameDayUsingApacheCommons(Date date1, Date date2) { + return DateUtils.isSameDay(date1, date2); + } + + public static boolean isSameDayUsingJoda(Date date1, Date date2) { + org.joda.time.LocalDate localDate1 = new org.joda.time.LocalDate(date1); + org.joda.time.LocalDate localDate2 = new org.joda.time.LocalDate(date2); + return localDate1.equals(localDate2); + } + + public static boolean isSameDayUsingDate4j(Date date1, Date date2) { + DateTime dateObject1 = DateTime.forInstant(date1.getTime(), TimeZone.getDefault()); + DateTime dateObject2 = DateTime.forInstant(date2.getTime(), TimeZone.getDefault()); + return dateObject1.isSameDayAs(dateObject2); + } +} diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/CalendarUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/CalendarUtils.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/CalendarUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/CalendarUtils.java diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/DateUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/DateUtils.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/DateUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/DateUtils.java diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/DateUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/sql/DateUtils.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/DateUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/sql/DateUtils.java diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimeUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/sql/TimeUtils.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimeUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/sql/TimeUtils.java diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTime.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTime.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTime.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTime.java diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtils.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtils.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/main/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtils.java rename to core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtils.java diff --git a/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/timer/DatabaseMigrationTask.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/timer/DatabaseMigrationTask.java new file mode 100644 index 0000000000..322c1d2f4e --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/timer/DatabaseMigrationTask.java @@ -0,0 +1,19 @@ +package com.baeldung.timer; + +import java.util.List; +import java.util.TimerTask; + +public class DatabaseMigrationTask extends TimerTask { + private List oldDatabase; + private List newDatabase; + + public DatabaseMigrationTask(List oldDatabase, List newDatabase) { + this.oldDatabase = oldDatabase; + this.newDatabase = newDatabase; + } + + @Override + public void run() { + newDatabase.addAll(oldDatabase); + } +} diff --git a/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/timer/NewsletterTask.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/timer/NewsletterTask.java new file mode 100644 index 0000000000..16dd6c12ff --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/timer/NewsletterTask.java @@ -0,0 +1,14 @@ +package com.baeldung.timer; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.TimerTask; + +public class NewsletterTask extends TimerTask { + @Override + public void run() { + System.out.println("Email sent at: " + + LocalDateTime.ofInstant(Instant.ofEpochMilli(scheduledExecutionTime()), ZoneId.systemDefault())); + } +} diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/date/comparison/DateComparisonUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/date/comparison/DateComparisonUtilsUnitTest.java similarity index 98% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/date/comparison/DateComparisonUtilsUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/date/comparison/DateComparisonUtilsUnitTest.java index faa2b18c91..477c348ea2 100644 --- a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/date/comparison/DateComparisonUtilsUnitTest.java +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/date/comparison/DateComparisonUtilsUnitTest.java @@ -1,57 +1,57 @@ -package com.baeldung.date.comparison; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Date; - -import org.junit.Test; - -public class DateComparisonUtilsUnitTest { - - private Date day1Morning = toDate(LocalDateTime.of(2019, 10, 19, 6, 30, 40)); - private Date day1Evening = toDate(LocalDateTime.of(2019, 10, 19, 18, 30, 50)); - private Date day2Morning = toDate(LocalDateTime.of(2019, 10, 20, 6, 30, 50)); - - private Date toDate(LocalDateTime localDateTime) { - return Date.from(localDateTime.atZone(ZoneId.systemDefault()) - .toInstant()); - } - - @Test - public void givenDatesWithDifferentTime_whenIsSameDay_thenReturnsTrue() { - assertTrue(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day1Evening)); - assertTrue(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day1Evening)); - assertTrue(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day1Evening)); - assertTrue(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day1Evening)); - assertTrue(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day1Evening)); - assertTrue(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day1Evening)); - assertTrue(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day1Evening)); - } - - @Test - public void givenDates_whenIsDifferentDay_thenReturnsFalse() { - assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day2Morning)); - assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Evening, day2Morning)); - - assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day2Morning)); - assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Evening, day2Morning)); - - assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day2Morning)); - assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Evening, day2Morning)); - - assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day2Morning)); - assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Evening, day2Morning)); - - assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day2Morning)); - assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Evening, day2Morning)); - - assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day2Morning)); - assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Evening, day2Morning)); - - assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day2Morning)); - assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Evening, day2Morning)); - } -} +package com.baeldung.date.comparison; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +import org.junit.Test; + +public class DateComparisonUtilsUnitTest { + + private Date day1Morning = toDate(LocalDateTime.of(2019, 10, 19, 6, 30, 40)); + private Date day1Evening = toDate(LocalDateTime.of(2019, 10, 19, 18, 30, 50)); + private Date day2Morning = toDate(LocalDateTime.of(2019, 10, 20, 6, 30, 50)); + + private Date toDate(LocalDateTime localDateTime) { + return Date.from(localDateTime.atZone(ZoneId.systemDefault()) + .toInstant()); + } + + @Test + public void givenDatesWithDifferentTime_whenIsSameDay_thenReturnsTrue() { + assertTrue(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day1Evening)); + assertTrue(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day1Evening)); + assertTrue(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day1Evening)); + assertTrue(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day1Evening)); + assertTrue(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day1Evening)); + assertTrue(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day1Evening)); + assertTrue(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day1Evening)); + } + + @Test + public void givenDates_whenIsDifferentDay_thenReturnsFalse() { + assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Evening, day2Morning)); + + assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Evening, day2Morning)); + + assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Evening, day2Morning)); + + assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Evening, day2Morning)); + + assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Evening, day2Morning)); + + assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Evening, day2Morning)); + + assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day2Morning)); + assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Evening, day2Morning)); + } +} diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/jvmtimezone/ModifyDefaultTimezoneUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/jvmtimezone/ModifyDefaultTimezoneUnitTest.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/jvmtimezone/ModifyDefaultTimezoneUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/jvmtimezone/ModifyDefaultTimezoneUnitTest.java diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/jvmtimezone/ModifyTimezonePropertyUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/jvmtimezone/ModifyTimezonePropertyUnitTest.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/jvmtimezone/ModifyTimezonePropertyUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/jvmtimezone/ModifyTimezonePropertyUnitTest.java diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTimeUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTimeUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/offsetdatetime/ConvertToOffsetDateTimeUnitTest.java diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtilsUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-date-operations/src/test/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtilsUnitTest.java rename to core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/skipweekends/AddSubtractDaysSkippingWeekendsUtilsUnitTest.java diff --git a/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/timer/DatabaseMigrationTaskUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/timer/DatabaseMigrationTaskUnitTest.java new file mode 100644 index 0000000000..5f3ae63901 --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/timer/DatabaseMigrationTaskUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.timer; + +import org.junit.jupiter.api.Test; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; + +class DatabaseMigrationTaskUnitTest { + @Test + void givenDatabaseMigrationTask_whenTimerScheduledForNowPlusTwoSeconds_thenDataMigratedAfterTwoSeconds() throws Exception { + List oldDatabase = Arrays.asList("Harrison Ford", "Carrie Fisher", "Mark Hamill"); + List newDatabase = new ArrayList<>(); + + LocalDateTime twoSecondsLater = LocalDateTime.now().plusSeconds(2); + Date twoSecondsLaterAsDate = Date.from(twoSecondsLater.atZone(ZoneId.systemDefault()).toInstant()); + + new Timer().schedule(new DatabaseMigrationTask(oldDatabase, newDatabase), twoSecondsLaterAsDate); + + while (LocalDateTime.now().isBefore(twoSecondsLater)) { + assertThat(newDatabase).isEmpty(); + Thread.sleep(500); + } + assertThat(newDatabase).containsExactlyElementsOf(oldDatabase); + } + + @Test + void givenDatabaseMigrationTask_whenTimerScheduledInTwoSeconds_thenDataMigratedAfterTwoSeconds() throws Exception { + List oldDatabase = Arrays.asList("Harrison Ford", "Carrie Fisher", "Mark Hamill"); + List newDatabase = new ArrayList<>(); + + new Timer().schedule(new DatabaseMigrationTask(oldDatabase, newDatabase), 2000); + + LocalDateTime twoSecondsLater = LocalDateTime.now().plusSeconds(2); + + while (LocalDateTime.now().isBefore(twoSecondsLater)) { + assertThat(newDatabase).isEmpty(); + Thread.sleep(500); + } + assertThat(newDatabase).containsExactlyElementsOf(oldDatabase); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java new file mode 100644 index 0000000000..ffbe39c2bc --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.timer; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.Timer; + +class NewsletterTaskUnitTest { + private final Timer timer = new Timer(); + + @AfterEach + void afterEach() { + timer.cancel(); + } + + @Test + void givenNewsletterTask_whenTimerScheduledEachSecondFixedDelay_thenNewsletterSentEachSecond() throws Exception { + timer.schedule(new NewsletterTask(), 0, 1000); + + for (int i = 0; i < 3; i++) { + Thread.sleep(1000); + } + } + + @Test + void givenNewsletterTask_whenTimerScheduledEachSecondFixedRate_thenNewsletterSentEachSecond() throws Exception { + timer.scheduleAtFixedRate(new NewsletterTask(), 0, 1000); + + for (int i = 0; i < 3; i++) { + Thread.sleep(1000); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-datetime-java8-2/pom.xml b/core-java-modules/core-java-datetime-java8-2/pom.xml new file mode 100644 index 0000000000..34323fe76c --- /dev/null +++ b/core-java-modules/core-java-datetime-java8-2/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + core-java-datetime-java8 + ${project.parent.version} + core-java-datetime-java8 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + joda-time + joda-time + ${joda-time.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + log4j + log4j + ${log4j.version} + test + + + + + core-java-datetime-java8 + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 1.9 + 1.9 + 2.10 + + 3.6.1 + + + diff --git a/core-java-modules/core-java-datetime-java8-2/src/main/java/com/baeldung/localdate/LocalDateExample.java b/core-java-modules/core-java-datetime-java8-2/src/main/java/com/baeldung/localdate/LocalDateExample.java new file mode 100644 index 0000000000..f4c9e5431f --- /dev/null +++ b/core-java-modules/core-java-datetime-java8-2/src/main/java/com/baeldung/localdate/LocalDateExample.java @@ -0,0 +1,31 @@ +package com.baeldung.localdate; + +import java.time.LocalDate; +import java.time.Month; +import java.time.format.DateTimeFormatter; + +public class LocalDateExample { + public LocalDate getCustomDateOne(int year, int month, int dayOfMonth) { + return LocalDate.of(year, month, dayOfMonth); + } + + public LocalDate getCustomDateTwo(int year, Month month, int dayOfMonth) { + return LocalDate.of(year, month, dayOfMonth); + } + + public LocalDate getDateFromEpochDay(long epochDay) { + return LocalDate.ofEpochDay(epochDay); + } + + public LocalDate getDateFromYearAndDayOfYear(int year, int dayOfYear) { + return LocalDate.ofYearDay(year, dayOfYear); + } + + public LocalDate getDateFromString(String date) { + return LocalDate.parse(date); + } + + public LocalDate getDateFromStringAndFormatter(String date, String pattern) { + return LocalDate.parse(date, DateTimeFormatter.ofPattern(pattern)); + } +} diff --git a/core-java-modules/core-java-datetime-java8-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java b/core-java-modules/core-java-datetime-java8-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java new file mode 100644 index 0000000000..dff15486a4 --- /dev/null +++ b/core-java-modules/core-java-datetime-java8-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.localdate; + +import static org.junit.Assert.assertEquals; + +import java.time.Month; + +import org.junit.Test; + +public class LocalDateExampleUnitTest { + private LocalDateExample date = new LocalDateExample(); + + @Test + public void givenValues_whenUsingOfMethod_thenLocalDate() { + assertEquals("2020-01-08", date.getCustomDateOne(2020, 1, 8)); + } + + @Test + public void givenValuesWithMonthEnum_whenUsingOfMethod_thenLocalDate() { + assertEquals("2020-01-08", date.getCustomDateTwo(2020, Month.JANUARY, 8)); + } + + @Test + public void givenValues_whenUsingEpochDay_thenLocalDate() { + assertEquals("2020-01-08", date.getDateFromEpochDay(18269)); + } + + @Test + public void givenValues_whenUsingYearDay_thenLocalDate() { + assertEquals("2020-01-08", date.getDateFromYearAndDayOfYear(2020, 8)); + } + + @Test + public void givenValues_whenUsingParse_thenLocalDate() { + assertEquals("2020-01-08", date.getDateFromString("2020-01-08")); + } + + @Test + public void givenValuesWithFormatter_whenUsingParse_thenLocalDate() { + assertEquals("2020-01-08", date.getDateFromStringAndFormatter("8-Jan-2020", "d-MMM-yyyy")); + } +} diff --git a/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/file/FileClassUnitTest.java b/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/file/FileClassUnitTest.java index a4317af372..1883f40681 100644 --- a/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/file/FileClassUnitTest.java +++ b/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/file/FileClassUnitTest.java @@ -1,5 +1,6 @@ package com.baeldung.file; +import org.junit.Ignore; import org.junit.Test; import java.io.*; @@ -73,6 +74,7 @@ public class FileClassUnitTest { assertFalse(writable); } + @Ignore @Test public void givenWriteOnlyFile_whenCreateNewFile_thenCantReadFile() { File parentDir = makeDir("writeDir"); diff --git a/core-java-modules/core-java-jar/pom.xml b/core-java-modules/core-java-jar/pom.xml index a3e8941622..fe94a6d8a8 100644 --- a/core-java-modules/core-java-jar/pom.xml +++ b/core-java-modules/core-java-jar/pom.xml @@ -207,8 +207,8 @@ maven-javadoc-plugin ${maven-javadoc-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} @@ -397,6 +397,8 @@ 3.1.1 2.0.3.RELEASE 1.6.0 + 1.8 + 1.8 diff --git a/core-java-modules/core-java-jndi/pom.xml b/core-java-modules/core-java-jndi/pom.xml index 13504886d6..bb4299ae75 100644 --- a/core-java-modules/core-java-jndi/pom.xml +++ b/core-java-modules/core-java-jndi/pom.xml @@ -9,44 +9,49 @@ core-java-jndi - com.baeldung - parent-modules + com.baeldung.core-java-modules + core-java-modules 1.0.0-SNAPSHOT - ../../ org.junit.jupiter junit-jupiter + ${jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-api 5.5.1 test org.springframework spring-core - 5.0.9.RELEASE + ${spring.version} org.springframework spring-context - 5.0.9.RELEASE + ${spring.version} org.springframework spring-jdbc - 5.0.9.RELEASE + ${spring.version} org.springframework spring-test - 5.0.9.RELEASE + ${spring.version} test com.h2database h2 - 1.4.199 + ${h2.version} @@ -56,11 +61,19 @@ org.apache.maven.plugins maven-compiler-plugin - 1.8 - 1.8 + ${source.version} + ${target.version} + + + 5.0.9.RELEASE + 1.4.199 + 5.5.1 + 1.8 + 1.8 + diff --git a/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java b/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java index 49d4facffb..434fa41252 100644 --- a/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java +++ b/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java @@ -1,5 +1,12 @@ package com.baeldung.jndi.exceptions; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import javax.naming.InitialContext; +import javax.naming.NameNotFoundException; +import javax.naming.NoInitialContextException; + +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; @@ -7,15 +14,10 @@ import org.junit.jupiter.api.TestMethodOrder; import org.springframework.jndi.JndiTemplate; import org.springframework.mock.jndi.SimpleNamingContextBuilder; -import javax.naming.InitialContext; -import javax.naming.NameNotFoundException; -import javax.naming.NoInitialContextException; - -import static org.junit.jupiter.api.Assertions.assertThrows; - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class JndiExceptionsUnitTest { + @Disabled @Test @Order(1) void givenNoContext_whenLookupObject_thenThrowNoInitialContext() { diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml index ddf52d8fef..e708502dee 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml @@ -16,7 +16,7 @@ com.baeldung.servicemodule servicemodule - 1.0 + ${servicemodule.version} @@ -29,4 +29,8 @@ + + 1.0 + + diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml index 78a9d1eaad..3c03643a2c 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml @@ -19,10 +19,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 11 - 11 + ${source.version} + ${target.version} @@ -31,6 +31,9 @@ UTF-8 + 3.8.0 + 11 + 11 \ No newline at end of file diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule/pom.xml index ece85fd5dc..3fe6f735eb 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule/pom.xml @@ -2,7 +2,6 @@ 4.0.0 - com.baeldung.servicemodule servicemodule jar diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml index 734774af0e..a042ee4562 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml @@ -8,8 +8,8 @@ 1.0 - decoupling-pattern2 - com.baeldung.decoupling-pattern2 + com.baeldung.decoupling-pattern2 + decoupling-pattern2 1.0-SNAPSHOT @@ -17,12 +17,12 @@ com.baeldung.servicemodule servicemodule - 1.0 + ${servicemodule.version} com.baeldung.providermodule providermodule - 1.0 + ${providermodule.version} @@ -34,5 +34,10 @@ + + + 1.0 + 1.0 + \ No newline at end of file diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml index 2f84c69fd6..f6b4e5b0df 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml @@ -20,14 +20,20 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 11 - 11 + ${source.version} + ${target.version} + + + 3.8.0 + 11 + 11 + \ No newline at end of file diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml index 5ec36c581e..20e97fca0f 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml @@ -8,8 +8,8 @@ 1.0 - decoupling-pattern2 - com.baeldung.decoupling-pattern2 + com.baeldung.decoupling-pattern2 + decoupling-pattern2 1.0-SNAPSHOT @@ -17,7 +17,7 @@ com.baeldung.servicemodule servicemodule - 1.0 + ${servicemodule.version} @@ -30,4 +30,9 @@ + + 1.0 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml index 9249ea5d89..f65ebb0b55 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml @@ -3,13 +3,12 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung.servicemodule servicemodule 1.0 - decoupling-pattern2 - >com.baeldung.decoupling-pattern2 + com.baeldung.decoupling-pattern2 + decoupling-pattern2 1.0-SNAPSHOT diff --git a/core-java-modules/core-java-jpms/pom.xml b/core-java-modules/core-java-jpms/pom.xml new file mode 100644 index 0000000000..dfb3c71229 --- /dev/null +++ b/core-java-modules/core-java-jpms/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + core-java-jpms + 0.0.1-SNAPSHOT + core-java-jpms + pom + + + com.baeldung.core-java-modules + core-java-modules + 1.0.0-SNAPSHOT + + + + decoupling-pattern1 + decoupling-pattern2 + + + diff --git a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoUnitTest.java b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoManualTest.java similarity index 88% rename from core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoUnitTest.java rename to core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoManualTest.java index 0c50651af0..d56dea62f4 100644 --- a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoUnitTest.java +++ b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoManualTest.java @@ -2,7 +2,7 @@ package com.baeldung.exitvshalt; import org.junit.Test; -public class JvmExitDemoUnitTest { +public class JvmExitDemoManualTest { JvmExitAndHaltDemo jvmExitAndHaltDemo = new JvmExitAndHaltDemo(); diff --git a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoUnitTest.java b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoManualTest.java similarity index 88% rename from core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoUnitTest.java rename to core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoManualTest.java index 9f08e95c6a..4fe0999a9c 100644 --- a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoUnitTest.java +++ b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoManualTest.java @@ -2,7 +2,7 @@ package com.baeldung.exitvshalt; import org.junit.Test; -public class JvmHaltDemoUnitTest { +public class JvmHaltDemoManualTest { JvmExitAndHaltDemo jvmExitAndHaltDemo = new JvmExitAndHaltDemo(); diff --git a/core-java-modules/core-java-lang-2/pom.xml b/core-java-modules/core-java-lang-2/pom.xml index 5657e64b17..4702b7350b 100644 --- a/core-java-modules/core-java-lang-2/pom.xml +++ b/core-java-modules/core-java-lang-2/pom.xml @@ -18,7 +18,7 @@ commons-beanutils commons-beanutils - 1.9.4 + ${commons.beanutils.version} org.openjdk.jmh @@ -57,6 +57,7 @@ 1.19 1.19 3.12.2 + 1.9.4 diff --git a/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/powerset/PowerSetUtility.java b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/powerset/PowerSetUtility.java index fd4c1933f6..336276786a 100644 --- a/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/powerset/PowerSetUtility.java +++ b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/powerset/PowerSetUtility.java @@ -1,7 +1,5 @@ package com.baeldung.powerset; -import com.google.common.collect.Sets; - import javax.annotation.Nullable; import java.util.AbstractSet; import java.util.ArrayList; @@ -163,7 +161,7 @@ public class PowerSetUtility { return unMapIndex(powerSetIndices); } - private List> iterativePowerSetByLoopOverNumbersWithReverseLexicographicalOrder(int n) { + private List> iterativePowerSetByLoopOverNumbers(int n) { List> powerSet = new ArrayList<>(); for (int i = 0; i < (1 << n); i++) { List subset = new ArrayList<>(n); @@ -174,7 +172,7 @@ public class PowerSetUtility { return powerSet; } - private List> iterativePowerSetByLoopOverNumbersWithGrayCodeOrder(int n) { + private List> iterativePowerSetByLoopOverNumbersWithMinimalChange(int n) { List> powerSet = new ArrayList<>(); for (int i = 0; i < (1 << n); i++) { List subset = new ArrayList<>(n); @@ -195,32 +193,16 @@ public class PowerSetUtility { public List> iterativePowerSetByLoopOverNumbers(Set set) { initializeMap(set); - List> sets = iterativePowerSetByLoopOverNumbersWithReverseLexicographicalOrder(set.size()); + List> sets = iterativePowerSetByLoopOverNumbers(set.size()); return unMapListBinary(sets); } public List> iterativePowerSetByLoopOverNumbersMinimalChange(Set set) { initializeMap(set); - List> sets = iterativePowerSetByLoopOverNumbersWithGrayCodeOrder(set.size()); + List> sets = iterativePowerSetByLoopOverNumbersWithMinimalChange(set.size()); return unMapListBinary(sets); } - public static int getRankInLexicographicalOrder(List subset) { - int rank = 0; - for (int i = 0; i < subset.size(); i++) - if (subset.get(i)) - rank += (1 << (subset.size() - i - 1)); - return rank; - } - - public static List getSubsetForRankInLexicographicalOrder(int rank, int sizeOfSet) { - Boolean[] subset = new Boolean[sizeOfSet]; - for(int j = 0; j < sizeOfSet; j++) { - subset[sizeOfSet - j - 1] = ((rank & (1 << j)) > 0); - } - return Arrays.asList(subset); - } - private Set> recursivePowerSetIndexRepresentation(int idx, int n) { if (idx == n) { Set> empty = new HashSet<>(); diff --git a/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/powerset/PowerSetUtilityUnitTest.java b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/powerset/PowerSetUtilityUnitTest.java index 0a20c36692..8b7c338479 100644 --- a/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/powerset/PowerSetUtilityUnitTest.java +++ b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/powerset/PowerSetUtilityUnitTest.java @@ -137,7 +137,7 @@ public class PowerSetUtilityUnitTest { } @Test - public void givenSet_WhenPowerSetIsCalculatedIterativePowerSetByLoopOverNumbersMinimalChange_ThenItContainsAllSubsetsInGrayOrder() { + public void givenSet_WhenPowerSetIsCalculatedIterativePowerSetByLoopOverNumbersWithMinimalChange_ThenItContainsAllSubsets() { Set set = RandomSetOfStringGenerator.generateRandomSet(); List> powerSet = new PowerSetUtility().iterativePowerSetByLoopOverNumbersMinimalChange(set); @@ -172,42 +172,6 @@ public class PowerSetUtilityUnitTest { } } - @Test - public void givenSubset_WhenPowerSetIsInLexicographicalOrder_ReturnCorrectRank() { - int n = new Random().nextInt(5) + 5; //a number in [5, 10) - for(int i = 0; i < ( 1 << n); i++) { - Boolean[] subset = new Boolean[n]; - for(int j=0; j < n; j++) { - subset[n - j - 1] = ((i & (1 << j)) > 0); - } - Assertions.assertEquals(i, PowerSetUtility.getRankInLexicographicalOrder(Arrays.asList(subset))); - } - } - - @Test - public void givenRanking_WhenPowerSetIsInLexicographicalOrder_ReturnTheSubset() { - int n = new Random().nextInt(5) + 5; //a number in [5, 10) - List> powerSet = new ArrayList<>(); - for(int i = 0; i < (1 << n); i++) { - powerSet.add(PowerSetUtility.getSubsetForRankInLexicographicalOrder(i, n)); - } - //To make sure that the size of power set is (2 power n) - MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << n))); - //To make sure that number of occurrence of each index is (2 power n-1) - Map counter = new HashMap<>(); - for (List subset : powerSet) { - for (int i = 0; i < subset.size(); i++) { - if(subset.get(i)) { - int num = counter.getOrDefault(i, 0); - counter.put(i, num + 1); - } - } - } - counter.forEach((k, v) -> Assertions.assertEquals((1 << (n - 1)), v.intValue())); - //To make sure that one subset is not generated twice - Assertions.assertEquals(powerSet.size(), new HashSet<>(powerSet).size()); - } - static class RandomSetOfStringGenerator { private static List fruits = Arrays.asList("Apples", "Avocados", "Banana", "Blueberry", "Cherry", "Clementine", "Cucumber", "Date", "Fig", "Grapefruit"/*, "Grape", "Kiwi", "Lemon", "Mango", "Mulberry", "Melon", "Nectarine", "Olive", "Orange"*/); diff --git a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java index 6b292ad8ab..728c83a107 100644 --- a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java +++ b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; public class TernaryOperatorUnitTest { @Test - public void givenACondition_whenUsingTernaryOperator_thenItEvaluatesConditionAndReturnsAValue() { + public void whenUsingTernaryOperator_thenConditionIsEvaluatedAndValueReturned() { int number = 10; String msg = number > 10 ? "Number is greater than 10" : "Number is less than or equal to 10"; @@ -14,7 +14,7 @@ public class TernaryOperatorUnitTest { } @Test - public void givenATrueCondition_whenUsingTernaryOperator_thenOnlyExpression1IsEvaluated() { + public void whenConditionIsTrue_thenOnlyFirstExpressionIsEvaluated() { int exp1 = 0, exp2 = 0; int result = 12 > 10 ? ++exp1 : ++exp2; @@ -24,7 +24,7 @@ public class TernaryOperatorUnitTest { } @Test - public void givenAFalseCondition_whenUsingTernaryOperator_thenOnlyExpression2IsEvaluated() { + public void whenConditionIsFalse_thenOnlySecondExpressionIsEvaluated() { int exp1 = 0, exp2 = 0; int result = 8 > 10 ? ++exp1 : ++exp2; diff --git a/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java index 47473c29ea..f9fbc5dc3a 100644 --- a/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java +++ b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java @@ -1,6 +1,8 @@ package com.baeldung.optional; +import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; public class Person { private String name; @@ -21,7 +23,7 @@ public class Person { } public Optional getAge() { - return Optional.ofNullable(age); + return Optional.of(age); } public void setAge(int age) { @@ -36,4 +38,37 @@ public class Person { return Optional.ofNullable(password); } + public static List search(List people, String name, Optional age) { + // Null checks for people and name + return people.stream() + .filter(p -> p.getName().equals(name)) + .filter(p -> p.getAge().get() >= age.orElse(0)) + .collect(Collectors.toList()); + } + + public static List search(List people, String name, Integer age) { + // Null checks for people and name + final Integer ageFilter = age != null ? age : 0; + + return people.stream() + .filter(p -> p.getName().equals(name)) + .filter(p -> p.getAge().get() >= ageFilter) + .collect(Collectors.toList()); + } + + public static List search(List people, String name) { + return doSearch(people, name, 0); + } + + public static List search(List people, String name, int age) { + return doSearch(people, name, age); + } + + private static List doSearch(List people, String name, int age) { + // Null checks for people and name + return people.stream() + .filter(p -> p.getName().equals(name)) + .filter(p -> p.getAge().get().intValue() >= age) + .collect(Collectors.toList()); + } } diff --git a/core-java-modules/core-java-reflection/pom.xml b/core-java-modules/core-java-reflection/pom.xml index b3c3390df8..64086ef5b8 100644 --- a/core-java-modules/core-java-reflection/pom.xml +++ b/core-java-modules/core-java-reflection/pom.xml @@ -37,8 +37,8 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} -parameters @@ -48,5 +48,7 @@ 3.8.0 3.10.0 + 1.8 + 1.8 \ No newline at end of file diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetExample.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetExample.java new file mode 100644 index 0000000000..a20ee527f8 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetExample.java @@ -0,0 +1,7 @@ +package com.baeldung.reflection.exception.invocationtarget; + +public class InvocationTargetExample { + public int divideByZeroExample() { + return 1 / 0; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetUnitTest.java new file mode 100644 index 0000000000..b4cabebcef --- /dev/null +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.reflection.exception.invocationtarget; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.jupiter.api.Test; + +public class InvocationTargetUnitTest { + + @Test + public void whenCallingMethodThrowsException_thenAssertCauseOfInvocationTargetException() throws Exception { + + InvocationTargetExample targetExample = new InvocationTargetExample(); + Method method = InvocationTargetExample.class.getMethod("divideByZeroExample"); + + Exception exception = assertThrows(InvocationTargetException.class, () -> method.invoke(targetExample)); + + assertEquals(ArithmeticException.class, exception.getCause().getClass()); + } +} diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index a5dd31c762..43dc040591 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -25,7 +25,7 @@ com.google.guava guava - 28.1-jre + ${guava.version} @@ -62,7 +62,7 @@ 3.8.1 3.6.1 - 27.0.1-jre + 28.1-jre 5.3.1 diff --git a/core-java-modules/core-java-text/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java b/core-java-modules/core-java-text/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java new file mode 100644 index 0000000000..304b9f2f1d --- /dev/null +++ b/core-java-modules/core-java-text/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.regex.matcher; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.Test; + +public class MatcherUnitTest { + + @Test + public void whenFindFourDigitWorks_thenCorrect() { + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); + Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); + + assertTrue(m.find()); + assertEquals(8, m.start()); + assertEquals("2019", m.group()); + assertEquals(12, m.end()); + + assertTrue(m.find()); + assertEquals(25, m.start()); + assertEquals("2020", m.group()); + assertEquals(29, m.end()); + + assertFalse(m.find()); + } + + @Test + public void givenStartIndex_whenFindFourDigitWorks_thenCorrect() { + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); + Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); + + assertTrue(m.find(20)); + assertEquals(25, m.start()); + assertEquals("2020", m.group()); + assertEquals(29, m.end()); + } + + @Test + public void whenMatchFourDigitWorks_thenFail() { + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); + Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); + assertFalse(m.matches()); + } + + @Test + public void whenMatchFourDigitWorks_thenCorrect() { + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); + Matcher m = stringPattern.matcher("2019"); + + assertTrue(m.matches()); + assertEquals(0, m.start()); + assertEquals("2019", m.group()); + assertEquals(4, m.end()); + + assertTrue(m.matches());// matches will always return the same return + } + +} diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml index 341363f8ed..2442d81559 100644 --- a/core-java-modules/core-java/pom.xml +++ b/core-java-modules/core-java/pom.xml @@ -207,8 +207,8 @@ maven-javadoc-plugin ${maven-javadoc-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} @@ -397,6 +397,8 @@ 3.1.1 2.0.3.RELEASE 1.6.0 + 1.8 + 1.8 diff --git a/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml b/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml index fa2d92d67f..e8a8203f33 100644 --- a/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml @@ -17,17 +17,17 @@ com.baeldung.entitymodule entitymodule - 1.0 + ${entitymodule.version} com.baeldung.daomodule daomodule - 1.0 + ${daomodule.version} com.baeldung.userdaomodule userdaomodule - 1.0 + ${userdaomodule.version} @@ -43,6 +43,9 @@ 9 9 + 1.0 + 1.0 + 1.0 \ No newline at end of file diff --git a/core-java-modules/multimodulemavenproject/pom.xml b/core-java-modules/multimodulemavenproject/pom.xml index 1d4aebf32e..dcf9f7311e 100644 --- a/core-java-modules/multimodulemavenproject/pom.xml +++ b/core-java-modules/multimodulemavenproject/pom.xml @@ -45,10 +45,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 1.9 - 1.9 + ${source.version} + ${target.version} @@ -56,6 +56,9 @@ + 3.8.0 + 1.9 + 1.9 UTF-8 3.12.2 diff --git a/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml b/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml index 19012708cf..8f4cc3d945 100644 --- a/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml @@ -17,12 +17,12 @@ com.baeldung.entitymodule entitymodule - 1.0 + ${entitymodule.version} com.baeldung.daomodule daomodule - 1.0 + ${daomodule.version} @@ -38,6 +38,8 @@ 9 9 + 1.0 + 1.0 \ No newline at end of file diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 1dadbf1efa..904cec2815 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -14,11 +14,110 @@ - pre-jpms - core-java-optional + core-java + + + + + core-java-8 + core-java-8-2 + + + + + + + + core-java-annotations + core-java-arrays + core-java-arrays-2 + + core-java-collections + core-java-collections-2 + core-java-collections-3 + core-java-collections-array-list + core-java-collections-list + core-java-collections-list-2 + core-java-collections-list-3 + core-java-collections-set + + core-java-concurrency-2 + core-java-concurrency-advanced + core-java-concurrency-advanced-2 + core-java-concurrency-advanced-3 + core-java-concurrency-basic + core-java-concurrency-basic-2 + core-java-concurrency-collections + + + core-java-date-operations-2 + + + + core-java-exceptions + core-java-exceptions-2 + + core-java-function + + core-java-io + core-java-io-2 + core-java-io-apis + core-java-io-conversions + + core-java-jar + core-java-jndi + + core-java-jvm + + core-java-lambdas + core-java-lang + core-java-lang-2 + core-java-lang-math + core-java-lang-oop + core-java-lang-oop-2 + core-java-lang-oop-3 + core-java-lang-oop-4 core-java-lang-operators + core-java-lang-syntax + core-java-lang-syntax-2 + + core-java-networking core-java-networking-2 - core-java-date-operations + core-java-nio + core-java-nio-2 + + core-java-optional + + + core-java-perf + + core-java-reflection + + core-java-security + core-java-streams + core-java-streams-2 + core-java-streams-3 + core-java-string-algorithms + core-java-string-algorithms-2 + core-java-string-algorithms-3 + core-java-string-apis + core-java-string-conversions + core-java-string-conversions-2 + core-java-string-operations + core-java-string-operations-2 + core-java-strings + core-java-sun + + core-java-text + + + + pre-jpms diff --git a/core-java-modules/pre-jpms/pom.xml b/core-java-modules/pre-jpms/pom.xml index cb23427138..9833dc2ff7 100644 --- a/core-java-modules/pre-jpms/pom.xml +++ b/core-java-modules/pre-jpms/pom.xml @@ -29,16 +29,16 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} org.apache.maven.plugins maven-dependency-plugin - 3.1.1 + ${dependency.plugin.version} copy-dependencies @@ -69,5 +69,12 @@ + + + 3.1.1 + 3.8.0 + 1.8 + 1.8 + diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt new file mode 100644 index 0000000000..a41e213c44 --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt @@ -0,0 +1,54 @@ +package com.baeldung.sequeces + +import org.junit.Test +import kotlin.test.assertEquals +import java.time.Instant + +class SequencesTest { + + @Test + fun shouldBuildSequenceWhenUsingFromElements() { + val seqOfElements = sequenceOf("first" ,"second", "third") + .toList() + assertEquals(3, seqOfElements.count()) + } + + @Test + fun shouldBuildSequenceWhenUsingFromFunction() { + val seqFromFunction = generateSequence(Instant.now()) {it.plusSeconds(1)} + .take(3) + .toList() + assertEquals(3, seqFromFunction.count()) + } + + @Test + fun shouldBuildSequenceWhenUsingFromChunks() { + val seqFromChunks = sequence { + yield(1) + yieldAll((2..5).toList()) + }.toList() + assertEquals(5, seqFromChunks.count()) + } + + @Test + fun shouldBuildSequenceWhenUsingFromCollection() { + val seqFromIterable = (1..10) + .asSequence() + .toList() + assertEquals(10, seqFromIterable.count()) + } + + @Test + fun shouldShowNoCountDiffWhenUsingWithAndWithoutSequence() { + val withSequence = (1..10).asSequence() + .filter{it % 2 == 1} + .map { it * 2 } + .toList() + val withoutSequence = (1..10) + .filter{it % 2 == 1} + .map { it * 2 } + .toList() + assertEquals(withSequence.count(), withoutSequence.count()) + } + +} \ No newline at end of file diff --git a/core-scala/pom.xml b/core-scala/pom.xml index d6793cf4c6..d72727dd39 100644 --- a/core-scala/pom.xml +++ b/core-scala/pom.xml @@ -28,7 +28,7 @@ net.alchim31.maven scala-maven-plugin - 3.3.2 + ${scala.plugin.version} @@ -49,6 +49,7 @@ 2.12.7 + 3.3.2 diff --git a/data-structures/pom.xml b/data-structures/pom.xml index e8f4628062..f4a8ea3a14 100644 --- a/data-structures/pom.xml +++ b/data-structures/pom.xml @@ -12,6 +12,21 @@ 1.0.0-SNAPSHOT + + + github.release.repo + https://raw.github.com/bulldog2011/bulldog-repo/master/repo/releases/ + + + + + + com.leansoft + bigqueue + 0.7.0 + + + diff --git a/data-structures/src/test/java/com/baeldung/bigqueue/BigQueueLiveTest.java b/data-structures/src/test/java/com/baeldung/bigqueue/BigQueueLiveTest.java new file mode 100644 index 0000000000..c0305a7ca3 --- /dev/null +++ b/data-structures/src/test/java/com/baeldung/bigqueue/BigQueueLiveTest.java @@ -0,0 +1,82 @@ +package com.baeldung.bigqueue; + +import com.leansoft.bigqueue.BigQueueImpl; +import com.leansoft.bigqueue.IBigQueue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@RunWith(JUnit4.class) +public class BigQueueLiveTest { + + private IBigQueue bigQueue; + + @Before + public void setup() throws IOException { + String queueDir = System.getProperty("user.home"); + String queueName = "baeldung-queue"; + bigQueue = new BigQueueImpl(queueDir, queueName); + } + + @After + public void emptyQueue() throws IOException { + bigQueue.removeAll(); + bigQueue.gc(); + bigQueue.close(); + } + + @Test + public void whenAddingRecords_ThenTheSizeIsCorrect() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + + assertEquals(100, bigQueue.size()); + } + + @Test + public void whenAddingRecords_ThenTheyCanBeRetrieved() throws IOException { + bigQueue.enqueue(String.valueOf("new_record").getBytes()); + + String record = new String(bigQueue.dequeue()); + assertEquals("new_record", record); + } + + @Test + public void whenDequeueingRecords_ThenTheyAreConsumed() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + bigQueue.dequeue(); + + assertEquals(99, bigQueue.size()); + } + + @Test + public void whenPeekingRecords_ThenSizeDoesntChange() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + String firstRecord = new String(bigQueue.peek()); + + assertEquals("1", firstRecord); + assertEquals(100, bigQueue.size()); + } + + @Test + public void whenEmptyingTheQueue_ThenItSizeIs0() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + bigQueue.removeAll(); + + assertEquals(0, bigQueue.size()); + } + +} diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index 0e84fa1516..c143b86ff8 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -44,12 +44,13 @@ org.apache.httpcomponents httpclient - 4.3.5 + ${httpclient.version} 0.9.1 + 4.3.5 diff --git a/ethereum/pom.xml b/ethereum/pom.xml index 6fc31208d2..da0a7ebda8 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -175,10 +175,10 @@ maven-compiler-plugin - 3.1 + ${compiler.plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} @@ -215,5 +215,8 @@ 1.2.3 1.7.25 2.0.4.RELEASE + 3.1 + 1.8 + 1.8 diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml index e79b43c5e5..37e423b3af 100644 --- a/google-web-toolkit/pom.xml +++ b/google-web-toolkit/pom.xml @@ -63,7 +63,7 @@ net.ltgt.gwt.maven gwt-maven-plugin - 1.0-rc-8 + ${gwt.plugin.version} @@ -78,7 +78,7 @@ true - 1.8 + ${maven.compiler.source} @@ -98,7 +98,7 @@ maven-surefire-plugin - 2.17 + ${surefire.plugin.version} true @@ -119,6 +119,8 @@ UTF-8 UTF-8 2.8.2 + 1.0-rc-8 + 2.17 diff --git a/guest/core-kotlin/pom.xml b/guest/core-kotlin/pom.xml index 2d4a0c6144..ad0368c6ab 100644 --- a/guest/core-kotlin/pom.xml +++ b/guest/core-kotlin/pom.xml @@ -46,19 +46,19 @@ org.jetbrains.spek spek-api - 1.1.5 + ${spek.api.version} test org.jetbrains.spek spek-subject-extension - 1.1.5 + ${spek.subject.version} test org.jetbrains.spek spek-junit-platform-engine - 1.1.5 + ${spek.junit.version} test @@ -195,6 +195,9 @@ 5.2.0 3.10.0 3.7.0 + 1.1.5 + 1.1.5 + 1.1.5 diff --git a/intelliJ/remote-debugging/pom.xml b/intelliJ/remote-debugging/pom.xml index d18625e8f6..43b9a44d13 100644 --- a/intelliJ/remote-debugging/pom.xml +++ b/intelliJ/remote-debugging/pom.xml @@ -16,6 +16,7 @@ 1.8 + 3.1.2 @@ -31,7 +32,7 @@ org.awaitility awaitility - 3.1.2 + ${awaitility.version} test diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml index 912a2cabac..a2d9443d67 100644 --- a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml +++ b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml @@ -12,12 +12,16 @@ java-ee-8-security-api 1.0-SNAPSHOT + + + 4.0.4 + com.unboundid unboundid-ldapsdk - 4.0.4 + ${unboundid.ldapsdk.version} diff --git a/java-numbers-2/pom.xml b/java-numbers-2/pom.xml index ba40ef0a38..5c81b00756 100644 --- a/java-numbers-2/pom.xml +++ b/java-numbers-2/pom.xml @@ -21,6 +21,11 @@ jmh-generator-annprocess ${jmh-generator.version} + + it.unimi.dsi + dsiutils + ${dsiutils.version} + @@ -33,4 +38,8 @@ + + 2.6.0 + + diff --git a/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java b/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java index 68382c26ea..7af8c5d58d 100644 --- a/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java +++ b/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java @@ -7,7 +7,7 @@ public class BruteForcePrimeChecker implements PrimeChecker { @Override public boolean isPrime(Integer number) { - return number > 2 ? IntStream.range(2, number) + return number > 1 ? IntStream.range(2, number) .noneMatch(n -> (number % n == 0)) : false; } diff --git a/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java b/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java index 3dc372ad22..3019c76eb4 100644 --- a/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java +++ b/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java @@ -6,7 +6,7 @@ public class OptimisedPrimeChecker implements PrimeChecker { @Override public boolean isPrime(Integer number) { - return number > 2 ? IntStream.rangeClosed(2, (int) Math.sqrt(number)) + return number > 1 ? IntStream.rangeClosed(2, (int) Math.sqrt(number)) .noneMatch(n -> (number % n == 0)) : false; } diff --git a/java-numbers-2/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java index 9f8ba8defd..6e425b3051 100644 --- a/java-numbers-2/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java +++ b/java-numbers-2/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java @@ -11,22 +11,24 @@ public class PrimeCheckerUnitTest { @Test public void whenCheckIsPrime_thenTrue() { - assertTrue(primeChecker.isPrime(13l)); + assertTrue(primeChecker.isPrime(2L)); + assertTrue(primeChecker.isPrime(13L)); assertTrue(primeChecker.isPrime(1009L)); assertTrue(primeChecker.isPrime(74207281L)); } @Test public void whenCheckIsPrime_thenFalse() { - assertTrue(!primeChecker.isPrime(50L)); - assertTrue(!primeChecker.isPrime(1001L)); - assertTrue(!primeChecker.isPrime(74207282L)); + assertFalse(primeChecker.isPrime(50L)); + assertFalse(primeChecker.isPrime(1001L)); + assertFalse(primeChecker.isPrime(74207282L)); } private final BruteForcePrimeChecker bfPrimeChecker = new BruteForcePrimeChecker(); @Test public void whenBFCheckIsPrime_thenTrue() { + assertTrue(bfPrimeChecker.isPrime(2)); assertTrue(bfPrimeChecker.isPrime(13)); assertTrue(bfPrimeChecker.isPrime(1009)); } @@ -41,6 +43,7 @@ public class PrimeCheckerUnitTest { @Test public void whenOptCheckIsPrime_thenTrue() { + assertTrue(optimisedPrimeChecker.isPrime(2)); assertTrue(optimisedPrimeChecker.isPrime(13)); assertTrue(optimisedPrimeChecker.isPrime(1009)); } @@ -55,6 +58,7 @@ public class PrimeCheckerUnitTest { @Test public void whenPrimesCheckIsPrime_thenTrue() { + assertTrue(primesPrimeChecker.isPrime(2)); assertTrue(primesPrimeChecker.isPrime(13)); assertTrue(primesPrimeChecker.isPrime(1009)); } diff --git a/java-numbers-3/pom.xml b/java-numbers-3/pom.xml index 3dd8e16bc7..e3c64064c7 100644 --- a/java-numbers-3/pom.xml +++ b/java-numbers-3/pom.xml @@ -12,6 +12,14 @@ 0.0.1-SNAPSHOT ../parent-java + + + + it.unimi.dsi + dsiutils + 2.6.0 + + java-numbers-3 diff --git a/java-numbers-3/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java b/java-numbers-3/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java new file mode 100644 index 0000000000..50a072371e --- /dev/null +++ b/java-numbers-3/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java @@ -0,0 +1,103 @@ +package com.baeldung.randomnumbers; + +import java.security.SecureRandom; +import java.util.Random; +import java.util.SplittableRandom; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.IntStream; + +import org.apache.commons.math3.random.RandomDataGenerator; + +import it.unimi.dsi.util.XoRoShiRo128PlusRandom; + +public class RandomNumbersGenerator { + + public Integer generateRandomWithMathRandom(int max, int min) { + return (int) ((Math.random() * (max - min)) + min); + } + + public Integer generateRandomWithNextInt() { + Random random = new Random(); + int randomWithNextInt = random.nextInt(); + return randomWithNextInt; + } + + public Integer generateRandomWithNextIntWithinARange(int min, int max) { + Random random = new Random(); + int randomWintNextIntWithinARange = random.nextInt(max - min) + min; + return randomWintNextIntWithinARange; + } + + public IntStream generateRandomUnlimitedIntStream() { + Random random = new Random(); + IntStream unlimitedIntStream = random.ints(); + return unlimitedIntStream; + } + + public IntStream generateRandomLimitedIntStream(long streamSize) { + Random random = new Random(); + IntStream limitedIntStream = random.ints(streamSize); + return limitedIntStream; + } + + public IntStream generateRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) { + Random random = new Random(); + IntStream limitedIntStreamWithinARange = random.ints(streamSize, min, max); + return limitedIntStreamWithinARange; + } + + public Integer generateRandomWithThreadLocalRandom() { + int randomWithThreadLocalRandom = ThreadLocalRandom.current() + .nextInt(); + return randomWithThreadLocalRandom; + } + + public Integer generateRandomWithThreadLocalRandomInARange(int min, int max) { + int randomWithThreadLocalRandomInARange = ThreadLocalRandom.current() + .nextInt(min, max); + return randomWithThreadLocalRandomInARange; + } + + public Integer generateRandomWithThreadLocalRandomFromZero(int max) { + int randomWithThreadLocalRandomFromZero = ThreadLocalRandom.current() + .nextInt(max); + return randomWithThreadLocalRandomFromZero; + } + + public Integer generateRandomWithSplittableRandom(int min, int max) { + SplittableRandom splittableRandom = new SplittableRandom(); + int randomWithSplittableRandom = splittableRandom.nextInt(min, max); + return randomWithSplittableRandom; + } + + public IntStream generateRandomWithSplittableRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) { + SplittableRandom splittableRandom = new SplittableRandom(); + IntStream limitedIntStreamWithinARangeWithSplittableRandom = splittableRandom.ints(streamSize, min, max); + return limitedIntStreamWithinARangeWithSplittableRandom; + } + + public Integer generateRandomWithSecureRandom() { + SecureRandom secureRandom = new SecureRandom(); + int randomWithSecureRandom = secureRandom.nextInt(); + return randomWithSecureRandom; + } + + public Integer generateRandomWithSecureRandomWithinARange(int min, int max) { + SecureRandom secureRandom = new SecureRandom(); + int randomWithSecureRandomWithinARange = secureRandom.nextInt(max - min) + min; + return randomWithSecureRandomWithinARange; + } + + public Integer generateRandomWithRandomDataGenerator(int min, int max) { + RandomDataGenerator randomDataGenerator = new RandomDataGenerator(); + int randomWithRandomDataGenerator = randomDataGenerator.nextInt(min, max); + return randomWithRandomDataGenerator; + } + + public Integer generateRandomWithXoRoShiRo128PlusRandom(int min, int max) { + XoRoShiRo128PlusRandom xoroRandom = new XoRoShiRo128PlusRandom(); + int randomWithXoRoShiRo128PlusRandom = xoroRandom.nextInt(max - min) + min; + return randomWithXoRoShiRo128PlusRandom; + } + +} diff --git a/java-numbers-3/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java new file mode 100644 index 0000000000..bdd955a4ee --- /dev/null +++ b/java-numbers-3/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java @@ -0,0 +1,154 @@ +package com.baeldung.randomnumbers; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.stream.IntStream; + +import org.junit.Test; + +public class RandomNumbersGeneratorUnitTest { + + private static final int MIN_RANGE = 1; + private static final int MAX_RANGE = 10; + private static final int MIN_RANGE_NEGATIVE = -10; + private static final int ITERATIONS = 50; + private static final long STREAM_SIZE = 50; + + @Test + public void whenGenerateRandomWithMathRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumer = generator.generateRandomWithMathRandom(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumer, MIN_RANGE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithNextInt_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithNextInt(); + assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } + } + + @Test + public void whenGenerateRandomWithNextIntWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithNextIntWithinARange(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomUnlimitedIntStream_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + IntStream stream = generator.generateRandomUnlimitedIntStream(); + assertNotNull(stream); + Integer randomNumber = stream.findFirst() + .getAsInt(); + assertNotNull(randomNumber); + assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } + + @Test + public void whenGenerateRandomLimitedIntStream_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + generator.generateRandomLimitedIntStream(STREAM_SIZE) + .forEach(randomNumber -> assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE))); + } + + @Test + public void whenGenerateRandomLimitedIntStreamWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + generator.generateRandomLimitedIntStreamWithinARange(MIN_RANGE, MAX_RANGE, STREAM_SIZE) + .forEach(randomNumber -> assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE))); + } + + @Test + public void whenGenerateRandomWithThreadLocalRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithThreadLocalRandom(); + assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } + } + + @Test + public void whenGenerateRandomWithThreadLocalRandomInARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithThreadLocalRandomInARange(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithThreadLocalRandomFromZero_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithThreadLocalRandomFromZero(MAX_RANGE); + assertTrue(isInRange(randomNumber, 0, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithSplittableRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithSplittableRandom(MIN_RANGE_NEGATIVE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE_NEGATIVE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithSplittableRandomLimitedIntStreamWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + generator.generateRandomWithSplittableRandomLimitedIntStreamWithinARange(MIN_RANGE, MAX_RANGE, STREAM_SIZE) + .forEach(randomNumber -> assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE))); + } + + @Test + public void whenGenerateRandomWithSecureRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithSecureRandom(); + assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } + } + + @Test + public void whenGenerateRandomWithSecureRandomWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithSecureRandomWithinARange(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithRandomDataGenerator_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithRandomDataGenerator(MIN_RANGE, MAX_RANGE); + // RandomDataGenerator top is inclusive + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE + 1)); + } + } + + @Test + public void whenGenerateRandomWithXoRoShiRo128PlusRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithXoRoShiRo128PlusRandom(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)); + } + } + + private boolean isInRange(int number, int min, int max) { + return min <= number && number < max; + } + +} diff --git a/jee-7/pom.xml b/jee-7/pom.xml index 635d820c2b..a2593e46a5 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -118,7 +118,7 @@ javax.mvc javax.mvc-api - 20160715 + ${mvc.api.version} org.glassfish.ozark @@ -215,7 +215,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} @@ -506,6 +506,8 @@ + 1.0.0 + 20160715 1.8 3.0.0 7.0 diff --git a/jee-kotlin/pom.xml b/jee-kotlin/pom.xml index 80c5ea4e22..9191885bd4 100644 --- a/jee-kotlin/pom.xml +++ b/jee-kotlin/pom.xml @@ -253,7 +253,7 @@ org.wildfly.arquillian wildfly-arquillian-container-remote - 2.2.0.Final + ${wildfly.arquillian.version} test @@ -261,6 +261,7 @@ + 2.2.0.Final UTF-8 false 8.0 diff --git a/jhipster/jhipster-microservice/car-app/pom.xml b/jhipster/jhipster-microservice/car-app/pom.xml index 86d94d0a44..c53ea8358e 100644 --- a/jhipster/jhipster-microservice/car-app/pom.xml +++ b/jhipster/jhipster-microservice/car-app/pom.xml @@ -17,6 +17,7 @@ + 1.0.0 -Djava.security.egd=file:/dev/./urandom -Xmx256m 3.6.2 2.0.0 @@ -433,7 +434,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} diff --git a/jhipster/jhipster-microservice/dealer-app/pom.xml b/jhipster/jhipster-microservice/dealer-app/pom.xml index 3051399ae6..a0bcc73e31 100644 --- a/jhipster/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster/jhipster-microservice/dealer-app/pom.xml @@ -92,6 +92,7 @@ 1.4.10.Final 1.1.0.Final v0.21.3 + 1.0.0 @@ -427,7 +428,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} diff --git a/jhipster/jhipster-microservice/gateway-app/pom.xml b/jhipster/jhipster-microservice/gateway-app/pom.xml index 4e2c19ed2d..c6dcbb3f3e 100644 --- a/jhipster/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster/jhipster-microservice/gateway-app/pom.xml @@ -96,6 +96,7 @@ 1.4.10.Final 1.1.0.Final v0.21.3 + 1.0.0 @@ -469,7 +470,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml index 12dead99df..04f790faf5 100644 --- a/jhipster/jhipster-monolithic/pom.xml +++ b/jhipster/jhipster-monolithic/pom.xml @@ -302,7 +302,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} @@ -398,8 +398,8 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} org.mapstruct @@ -881,6 +881,9 @@ + 1.8 + 1.8 + 1.0.0 -Djava.security.egd=file:/dev/./urandom -Xmx256m 3.6.2 2.0.0 diff --git a/jhipster/jhipster-uaa/gateway/pom.xml b/jhipster/jhipster-uaa/gateway/pom.xml index 0f815bedad..1b85877a9b 100644 --- a/jhipster/jhipster-uaa/gateway/pom.xml +++ b/jhipster/jhipster-uaa/gateway/pom.xml @@ -236,7 +236,7 @@ org.zalando problem-spring-web - 0.24.0-RC.0 + ${spring.web.version} org.springframework.security.oauth @@ -559,7 +559,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} @@ -1012,6 +1012,8 @@ + 1.0.0 + 0.24.0-RC.0 3.0.0 1.8 diff --git a/jhipster/jhipster-uaa/uaa/pom.xml b/jhipster/jhipster-uaa/uaa/pom.xml index 2c4dd9d0f0..27a056820d 100644 --- a/jhipster/jhipster-uaa/uaa/pom.xml +++ b/jhipster/jhipster-uaa/uaa/pom.xml @@ -232,7 +232,7 @@ org.zalando problem-spring-web - 0.24.0-RC.0 + ${spring.web.version} org.springframework.security.oauth @@ -543,7 +543,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} @@ -834,6 +834,8 @@ + 1.0.0 + 0.24.0-RC.0 3.0.0 1.8 diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml index dfd1dc363f..0d6e589377 100644 --- a/kotlin-libraries/pom.xml +++ b/kotlin-libraries/pom.xml @@ -33,19 +33,19 @@ org.jetbrains.spek spek-api - 1.1.5 + ${spek.version} test org.jetbrains.spek spek-subject-extension - 1.1.5 + ${spek.version} test org.jetbrains.spek spek-junit-platform-engine - 1.1.5 + ${spek.version} test @@ -166,6 +166,7 @@ 2.6 2.3.0 0.7.3 + 1.1.5 diff --git a/kotlin-quasar/pom.xml b/kotlin-quasar/pom.xml index a12d27c565..f5fbce6ed7 100644 --- a/kotlin-quasar/pom.xml +++ b/kotlin-quasar/pom.xml @@ -103,7 +103,7 @@ maven-dependency-plugin - 3.1.1 + ${dependency.plugin.version} getClasspathFilenames @@ -116,7 +116,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.1 + ${surefire.plugin.version} -Dco.paralleluniverse.fibers.verifyInstrumentation=true -javaagent:${co.paralleluniverse:quasar-core:jar} @@ -125,7 +125,7 @@ org.codehaus.mojo exec-maven-plugin - 1.3.2 + ${exec.plugin.version} target/classes echo @@ -145,6 +145,9 @@ 1.3.31 1.7.21 1.1.7 + 3.1.1 + 2.22.1 + 1.3.2 diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java index 6749f7fe0a..aa29e4c441 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java @@ -7,6 +7,8 @@ import com.github.jknack.handlebars.Template; import com.github.jknack.handlebars.io.ClassPathTemplateLoader; import com.github.jknack.handlebars.io.TemplateLoader; import java.io.IOException; + +import org.junit.Ignore; import org.junit.Test; /** @@ -18,6 +20,7 @@ public class BuiltinHelperUnitTest { private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html"); + @Ignore @Test public void whenUsedWith_ThenContextChanges() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); @@ -30,6 +33,7 @@ public class BuiltinHelperUnitTest { assertThat(templateString).isEqualTo("\n

I live in World

\n"); } + @Ignore @Test public void whenUsedWithMustacheStyle_ThenContextChanges() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); @@ -42,6 +46,7 @@ public class BuiltinHelperUnitTest { assertThat(templateString).isEqualTo("\n

I live in World

\n"); } + @Ignore @Test public void whenUsedEach_ThenIterates() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); @@ -58,6 +63,7 @@ public class BuiltinHelperUnitTest { + "\nSpring is my friend.\n"); } + @Ignore @Test public void whenUsedEachMustacheStyle_ThenIterates() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); @@ -74,6 +80,7 @@ public class BuiltinHelperUnitTest { + "\nSpring is my friend.\n"); } + @Ignore @Test public void whenUsedIf_ThenPutsCondition() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); @@ -86,6 +93,7 @@ public class BuiltinHelperUnitTest { assertThat(templateString).isEqualTo("\n

Baeldung is busy.

\n"); } + @Ignore @Test public void whenUsedIfMustacheStyle_ThenPutsCondition() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java index 36f78f486e..56449f59e4 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java @@ -7,6 +7,8 @@ import com.github.jknack.handlebars.Template; import com.github.jknack.handlebars.io.ClassPathTemplateLoader; import com.github.jknack.handlebars.io.TemplateLoader; import java.io.IOException; + +import org.junit.Ignore; import org.junit.Test; /** @@ -18,6 +20,7 @@ public class ReusingTemplatesUnitTest { private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html"); + @Ignore @Test public void whenOtherTemplateIsReferenced_ThenCanReuse() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); @@ -30,6 +33,7 @@ public class ReusingTemplatesUnitTest { assertThat(templateString).isEqualTo("

Hi Baeldung!

\n

This is the page Baeldung

"); } + @Ignore @Test public void whenBlockIsDefined_ThenCanOverrideWithPartial() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index c8980fd309..6942aa736d 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -23,10 +23,16 @@ lombok ${lombok.version}
+ + org.cactoos + cactoos + ${cactoos.version} + 1.78 1.18.6 + 0.43 - + \ No newline at end of file diff --git a/libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java new file mode 100644 index 0000000000..717c63ae63 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java @@ -0,0 +1,28 @@ +package com.baeldung.cactoos; + +import java.util.Collection; +import java.util.List; + +import org.cactoos.collection.Filtered; +import org.cactoos.iterable.IterableOf; +import org.cactoos.list.ListOf; +import org.cactoos.scalar.And; +import org.cactoos.text.FormattedText; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CactoosCollectionUtils { + + final Logger LOGGER = LoggerFactory.getLogger(CactoosCollectionUtils.class); + + public void iterateCollection(List strings) throws Exception { + new And((String input) -> LOGGER.info(new FormattedText("%s\n", input).asString()), strings).value(); + } + + public Collection getFilteredList(List strings) { + Collection filteredStrings = new ListOf<>( + new Filtered<>(string -> string.length() == 5, new IterableOf<>(strings))); + return filteredStrings; + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java new file mode 100644 index 0000000000..3e2903ebf4 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java @@ -0,0 +1,37 @@ +package com.baeldung.cactoos; + +import java.io.IOException; + +import org.cactoos.text.FormattedText; +import org.cactoos.text.IsBlank; +import org.cactoos.text.Lowered; +import org.cactoos.text.TextOf; +import org.cactoos.text.Upper; + +public class CactoosStringUtils { + + public String createString() throws IOException { + String testString = new TextOf("Test String").asString(); + return testString; + } + + public String createdFormattedString(String stringToFormat) throws IOException { + String formattedString = new FormattedText("Hello %s", stringToFormat).asString(); + return formattedString; + } + + public String toLowerCase(String testString) throws IOException { + String lowerCaseString = new Lowered(new TextOf(testString)).asString(); + return lowerCaseString; + } + + public String toUpperCase(String testString) throws Exception { + String upperCaseString = new Upper(new TextOf(testString)).asString(); + return upperCaseString; + } + + public boolean isBlank(String testString) throws Exception { + return new IsBlank(new TextOf(testString)) != null; + } + +} diff --git a/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java new file mode 100644 index 0000000000..c6bcbd7df7 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.cactoos; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; + +import org.junit.Test; + +public class CactoosCollectionUtilsUnitTest { + + @Test + public void whenFilteredClassIsCalledWithSpecificArgs_thenCorrespondingFilteredCollectionShouldBeReturned() throws IOException { + + CactoosCollectionUtils obj = new CactoosCollectionUtils(); + + // when + List strings = new ArrayList() { + { + add("Hello"); + add("John"); + add("Smith"); + add("Eric"); + add("Dizzy"); + } + }; + int size = obj.getFilteredList(strings).size(); + + // then + assertEquals(3, size); + + } + +} diff --git a/libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java new file mode 100644 index 0000000000..67dd6d91e4 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.cactoos; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; + +import org.junit.Test; + +public class CactoosStringUtilsUnitTest { + + @Test + public void whenFormattedTextIsPassedWithArgs_thenFormattedStringIsReturned() throws IOException { + + CactoosStringUtils obj = new CactoosStringUtils(); + + // when + String formattedString = obj.createdFormattedString("John"); + + // then + assertEquals("Hello John", formattedString); + + } + + @Test + public void whenStringIsPassesdToLoweredOrUpperClass_thenCorrespondingStringIsReturned() throws Exception { + + CactoosStringUtils obj = new CactoosStringUtils(); + + // when + String lowerCaseString = obj.toLowerCase("TeSt StrIng"); + String upperCaseString = obj.toUpperCase("TeSt StrIng"); + + // then + assertEquals("test string", lowerCaseString); + assertEquals("TEST STRING", upperCaseString); + + } + + @Test + public void whenEmptyStringIsPassesd_thenIsBlankReturnsTrue() throws Exception { + + CactoosStringUtils obj = new CactoosStringUtils(); + + // when + boolean isBlankEmptyString = obj.isBlank(""); + boolean isBlankNull = obj.isBlank(null); + + // then + assertEquals(true, isBlankEmptyString); + assertEquals(true, isBlankNull); + + } + +} diff --git a/libraries-data-db/pom.xml b/libraries-data-db/pom.xml index 682a6ed185..f028ffe8c3 100644 --- a/libraries-data-db/pom.xml +++ b/libraries-data-db/pom.xml @@ -183,7 +183,7 @@ io.ebean ebean-maven-plugin - 11.11.2 + ${ebean.plugin.version} @@ -202,6 +202,7 @@
+ 11.11.2 16.5.1 3.0.0 1.8 diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 2086ecb614..1267982c49 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -74,19 +74,19 @@ commons-cli commons-cli - 1.2 + ${commons.cli.version} provided commons-io commons-io - 2.1 + ${commons.io.version} provided commons-httpclient commons-httpclient - 3.0.1 + ${httpclient.version} provided @@ -133,7 +133,7 @@ org.apache.maven.plugins maven-assembly-plugin - 2.3 + ${assembly.plugin.version} src/main/resources/assembly/hadoop-job.xml @@ -158,6 +158,10 @@
+ 2.3 + 1.2 + 2.1 + 3.0.1 1.2.2 1.0.0 2.4.0 diff --git a/libraries-http/pom.xml b/libraries-http/pom.xml index 6261456486..cbc74ce132 100644 --- a/libraries-http/pom.xml +++ b/libraries-http/pom.xml @@ -71,7 +71,7 @@ com.google.code.gson gson - 2.8.5 + ${gson.version} @@ -116,6 +116,7 @@ + 2.8.5 4.5.3 2.9.8 3.6.2 diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index c84f8dda76..3ffbb291a0 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -127,7 +127,7 @@ org.asciidoctor asciidoctor-maven-plugin - 1.5.7.1 + ${asciidoctor.version} @@ -154,7 +154,8 @@ - 1.9.9 + 1.5.7.1 + 1.9.9 1.9.0 1.9.0 1.9.27 diff --git a/libraries/pom.xml b/libraries/pom.xml index 13f91711fd..b5340d1ebb 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -523,7 +523,7 @@ org.apache.maven.plugins maven-shade-plugin - 2.2 + ${shade.plugin.version} package @@ -556,6 +556,7 @@ + 2.2 0.7.0 3.2.7 1.2 diff --git a/linux-bash/functions/src/main/bash/functions.sh b/linux-bash/functions/src/main/bash/functions.sh new file mode 100755 index 0000000000..41ff0ca434 --- /dev/null +++ b/linux-bash/functions/src/main/bash/functions.sh @@ -0,0 +1,208 @@ +#!/bin/bash + +# Subsection 2.1 +simple_function() { + for ((i=0;i<5;++i)) do + echo -n " "$i" "; + done +} + +function simple_function_no_parantheses { + for ((i=0;i<5;++i)) do + echo -n " "$i" "; + done +} + +function simple_for_loop() + for ((i=0;i<5;++i)) do + echo -n " "$i" "; + done + +function simple_comparison() + if [[ "$1" -lt 5 ]]; then + echo "$1 is smaller than 5" + else + echo "$1 is greater than 5" + fi + +# Subsection 2.2 +function simple_inputs() { + echo "This is the first argument [$1]" + echo "This is the second argument [$2]" + echo "Calling function with $# aruments" +} + +# Subsection 2.3 +global_sum=0 +function global_sum_outputs() { + global_sum=$(($1+$2)) +} + +function cs_sum_outputs() { + sum=$(($1+$2)) + echo $sum +} + +# Subsection 2.4 +function arg_ref_sum_outputs() { + declare -n sum_ref=$3 + sum_ref=$(($1+$2)) +} + +# Subsection 3.1 +variable="baeldung" +function variable_scope2() { + echo "Variable inside function variable_scope2: [$variable]" + local variable="ipsum" +} + +function variable_scope() { + local variable="lorem" + echo "Variable inside function variable_scope: [$variable]" + variable_scope2 +} + +# Subsection 3.2 +subshell_sum=0 +function simple_subshell_sum() ( + subshell_sum=$(($1+$2)) + echo "Value of sum in function with global variables: [$subshell_sum]" +) + +function simple_subshell_ref_sum() ( + declare -n sum_ref=$3 + sum_ref=$(($1+$2)) + echo "Value of sum in function with ref arguments: [$sum_ref]" +) + +# Subsection 3.3 +function redirection_in() { + while read input; + do + echo "$input" + done +} < infile + +function redirection_in_ps() { + read + while read -a input; + do + echo "User[${input[2]}]->File[${input[8]}]" + done +} < <(ls -ll /) + +function redirection_out_ps() { + declare -a output=("baeldung" "lorem" "ipsum" "caracg") + for element in "${output[@]}" + do + echo "$element" + done +} > >(grep "g") + +function redirection_out() { + declare -a output=("baeldung" "lorem" "ipsum") + for element in "${output[@]}" + do + echo "$element" + done +} > outfile + +# Subsection 3.4 +function fibonnaci_recursion() { + argument=$1 + if [[ "$argument" -eq 0 ]] || [[ "$argument" -eq 1 ]]; then + echo $argument + else + first=$(fibonnaci_recursion $(($argument-1))) + second=$(fibonnaci_recursion $(($argument-2))) + echo $(( $first + $second )) + fi +} + +# main menu entry point +echo "****Functions samples menu*****" +PS3="Your choice (1,2,3 etc.):" +options=("function_definitions" "function_input_args" "function_outputs" \ + "function_variables" "function_subshells" "function_redirections" \ + "function_recursion" "quit") +select option in "${options[@]}" +do + case $option in + "function_definitions") + echo -e "\n" + echo "**Different ways to define a function**" + echo -e "No function keyword:" + simple_function + echo -e "\nNo function parantheses:" + simple_function_no_parantheses + echo -e "\nOmitting curly braces:" + simple_for_loop + echo -e "\n" + ;; + "function_input_args") + echo -e "\n" + echo "**Passing inputs to a function**" + simple_inputs lorem ipsum + echo -e "\n" + ;; + "function_outputs") + echo -e "\n" + echo "**Getting outputs from a function**" + global_sum_outputs 1 2 + echo -e ">1+2 using global variables: [$global_sum]" + cs_sum=$(cs_sum_outputs 1 2) + echo -e ">1+2 using command substitution: [$cs_sum]" + arg_ref_sum_outputs 1 2 arg_ref_sum + echo -e ">1+2 using argument references: [$arg_ref_sum]" + echo -e "\n" + ;; + "function_variables") + echo -e "\n" + echo "**Overriding variable scopes**" + echo "Global value of variable: [$variable]" + variable_scope + echo -e "\n" + ;; + "function_subshells") + echo -e "\n" + echo "**Running function in subshell**" + echo "Global value of sum: [$subshell_sum]" + simple_subshell_sum 1 2 + echo "Value of sum after subshell function with \ +global variables: [$subshell_sum]" + subshell_sum_arg_ref=0 + simple_subshell_ref_sum 1 2 subshell_sum_arg_ref + echo "Value of sum after subshell function with \ +ref arguments: [$subshell_sum_arg_ref]" + echo -e "\n" + ;; + "function_redirections") + echo -e "\n" + echo "**Function redirections**" + echo -e ">Function input redirection from file:" + redirection_in + echo -e ">Function input redirection from command:" + redirection_in_ps + echo -e ">Function output redirection to file:" + redirection_out + cat outfile + echo -e ">Function output redirection to command:" + red_ps=$(redirection_out_ps) + echo "$red_ps" + echo -e "\n" + ;; + "function_recursion") + echo -e "\n" + echo "**Function recursion**" + fibo_res1=$(fibonnaci_recursion 7) + echo "The 7th Fibonnaci number: [$fibo_res1]" + fibo_res2=$(fibonnaci_recursion 15) + echo "The 15th Fibonnaci number: [$fibo_res2]" + echo -e "\n" + ;; + "quit") + break + ;; + *) echo "Invalid option";; + esac +done \ No newline at end of file diff --git a/linux-bash/functions/src/main/bash/infile b/linux-bash/functions/src/main/bash/infile new file mode 100644 index 0000000000..b1fa680af4 --- /dev/null +++ b/linux-bash/functions/src/main/bash/infile @@ -0,0 +1,3 @@ +Honda Insight 2010 +Honda Element 2006 +Chevrolet Avalanche 2002 diff --git a/logging-modules/flogger/pom.xml b/logging-modules/flogger/pom.xml index c27e2c8d7a..f553a4a961 100644 --- a/logging-modules/flogger/pom.xml +++ b/logging-modules/flogger/pom.xml @@ -15,26 +15,26 @@ com.google.flogger flogger - 0.4 + ${flogger.version} com.google.flogger flogger-system-backend - 0.4 + ${flogger.version} runtime com.google.flogger flogger-slf4j-backend - 0.4 + ${flogger.version} com.google.flogger flogger-log4j-backend - 0.4 + ${flogger.version} com.sun.jmx @@ -54,13 +54,18 @@ log4j log4j - 1.2.17 + ${log4j.version} log4j apache-log4j-extras - 1.2.17 + ${log4j.version} + + 0.4 + 1.2.17 + + \ No newline at end of file diff --git a/machine-learning/pom.xml b/machine-learning/pom.xml index 7bc0332012..24162b7b9c 100644 --- a/machine-learning/pom.xml +++ b/machine-learning/pom.xml @@ -19,6 +19,15 @@ 1.7 1.3.50 0.9.1 + 3.1.0 + 3.0.2 + 3.0.2 + 3.8.0 + 2.22.1 + 2.5.2 + 2.8.2 + 3.7.1 + 3.0.0 @@ -63,41 +72,41 @@ maven-clean-plugin - 3.1.0 + ${clean.plugin.version} maven-resources-plugin - 3.0.2 + ${resources.plugin.version} maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} maven-surefire-plugin - 2.22.1 + ${surefire.plugin.version} maven-jar-plugin - 3.0.2 + ${jar.plugin.version} maven-install-plugin - 2.5.2 + ${install.plugin.version} maven-deploy-plugin - 2.8.2 + ${deploy.plugin.version} maven-site-plugin - 3.7.1 + ${site.plugin.version} maven-project-info-reports-plugin - 3.0.0 + ${report.plugin.version} diff --git a/maven-all/compiler-plugin-java-9/pom.xml b/maven-all/compiler-plugin-java-9/pom.xml index 1975e1f7cd..6baadb451c 100644 --- a/maven-all/compiler-plugin-java-9/pom.xml +++ b/maven-all/compiler-plugin-java-9/pom.xml @@ -12,13 +12,19 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 9 - 9 + ${source.version} + ${target.version} + + 3.8.0 + 9 + 9 + + \ No newline at end of file diff --git a/maven-all/maven-custom-plugin/usage-example/pom.xml b/maven-all/maven-custom-plugin/usage-example/pom.xml index 542a02b3eb..bd2b16475e 100644 --- a/maven-all/maven-custom-plugin/usage-example/pom.xml +++ b/maven-all/maven-custom-plugin/usage-example/pom.xml @@ -8,16 +8,21 @@ 0.0.1-SNAPSHOT pom + + 3.9 + 4.12 + + org.apache.commons commons-lang3 - 3.9 + ${commons.lang3.version} junit junit - 4.12 + ${junit.version} test diff --git a/maven-all/maven-war-plugin/pom.xml b/maven-all/maven-war-plugin/pom.xml index 233a9f3571..915be306ca 100644 --- a/maven-all/maven-war-plugin/pom.xml +++ b/maven-all/maven-war-plugin/pom.xml @@ -14,7 +14,7 @@ maven-war-plugin - 3.1.0 + ${war.plugin.version} false @@ -26,6 +26,7 @@ false + 3.1.0 \ No newline at end of file diff --git a/maven-all/pom.xml b/maven-all/pom.xml new file mode 100644 index 0000000000..3a79a2a686 --- /dev/null +++ b/maven-all/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + maven-all + 0.0.1-SNAPSHOT + maven-all + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + maven + maven-custom-plugin/counter-maven-plugin + maven-war-plugin + profiles + versions-maven-plugin + + + diff --git a/maven-all/versions-maven-plugin/pom.xml b/maven-all/versions-maven-plugin/pom.xml index 3ce25d16f9..9793f55b28 100644 --- a/maven-all/versions-maven-plugin/pom.xml +++ b/maven-all/versions-maven-plugin/pom.xml @@ -12,19 +12,19 @@ commons-io commons-io - 2.3 + ${commons.io.version} org.apache.commons commons-collections4 - 4.0 + ${commons.collections4.version} org.apache.commons commons-lang3 - 3.0 + ${commons.lang3.version} @@ -36,7 +36,7 @@ commons-beanutils commons-beanutils - 1.9.1 + ${commons.beanutils.version} @@ -45,7 +45,7 @@ org.codehaus.mojo versions-maven-plugin - 2.7 + ${versions.plugin.version} org.apache.commons:commons-collections4 @@ -71,6 +71,11 @@ 1.15 + 2.3 + 2.7 + 1.9.1 + 3.0 + 4.0 \ No newline at end of file diff --git a/maven-archetype/src/main/resources/archetype-resources/pom.xml b/maven-archetype/src/main/resources/archetype-resources/pom.xml index a5c813652d..2a73687e2c 100644 --- a/maven-archetype/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetype/src/main/resources/archetype-resources/pom.xml @@ -14,6 +14,8 @@ ${liberty-plugin-version} 9080 9443 + 2.0 + 2.1 @@ -65,14 +67,14 @@ javax.enterprise cdi-api - 2.0 + ${cdi.api.version} provided javax.ws.rs javax.ws.rs-api - 2.1 + ${rsapi.api.version} provided diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml b/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml index 42b06bbebd..a4a6575906 100644 --- a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml @@ -12,23 +12,26 @@ com.baeldung.multimodule-maven-project multimodule-maven-project 1.0 + 1.0 + 1.0 + 1.0 com.baeldung.entitymodule entitymodule - 1.0 + ${entitymodule.version} com.baeldung.daomodule daomodule - 1.0 + ${daomodule.version} com.baeldung.userdaomodule userdaomodule - 1.0 + ${userdaomodule.version} diff --git a/maven-java-11/multimodule-maven-project/pom.xml b/maven-java-11/multimodule-maven-project/pom.xml index a79dff93d3..65f5b7a814 100644 --- a/maven-java-11/multimodule-maven-project/pom.xml +++ b/maven-java-11/multimodule-maven-project/pom.xml @@ -26,13 +26,13 @@ junit junit - 4.12 + ${junit.version} test org.assertj assertj-core - 3.12.2 + ${assertj.version} test @@ -44,10 +44,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 11 - 11 + ${source.version} + ${target.version} @@ -56,6 +56,11 @@ UTF-8 + 4.12 + 3.12.2 + 3.8.0 + 11 + 11 diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml index 3eb5897f8b..cfa59bdc39 100644 --- a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml @@ -14,16 +14,21 @@ 1.0 + + 1.0 + 1.0 + + com.baeldung.entitymodule entitymodule - 1.0 + ${entitymodule.version}1.0 com.baeldung.daomodule daomodule - 1.0 + ${daomodule.version} junit diff --git a/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-polyglot/maven-polyglot-json-extension/pom.xml index 0043bae151..15166046c1 100644 --- a/maven-polyglot/maven-polyglot-json-extension/pom.xml +++ b/maven-polyglot/maven-polyglot-json-extension/pom.xml @@ -34,7 +34,7 @@ org.codehaus.plexus plexus-component-metadata - 1.7.1 + ${plexus.component.version} @@ -48,6 +48,7 @@ 3.5.4 + 1.7.1 \ No newline at end of file diff --git a/maven-polyglot/pom.xml b/maven-polyglot/pom.xml new file mode 100644 index 0000000000..eb4e629a96 --- /dev/null +++ b/maven-polyglot/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + maven-polyglot + 0.0.1-SNAPSHOT + maven-polyglot + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + maven-polyglot-json-extension + + + + diff --git a/micronaut/pom.xml b/micronaut/pom.xml index 13639c11ff..2cb05cc1b9 100644 --- a/micronaut/pom.xml +++ b/micronaut/pom.xml @@ -49,7 +49,7 @@ javax.annotation javax.annotation-api - 1.3.2 + ${annotation.api.version} compile @@ -60,19 +60,19 @@ ch.qos.logback logback-classic - 1.2.3 + ${lombok.version} runtime junit junit - 4.12 + ${junit.version} test io.projectreactor reactor-core - 3.1.6.RELEASE + ${reactor.version} @@ -81,7 +81,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.1.0 + ${shade.plugin.version} package @@ -102,7 +102,7 @@ org.codehaus.mojo exec-maven-plugin - 1.6.0 + ${exec.plugin.version} java @@ -118,7 +118,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.7.0 + ${compiler.plugin.version} ${jdk.version} ${jdk.version} @@ -142,6 +142,13 @@ com.baeldung.micronaut.helloworld.server.ServerApplication 1.0.0.RC2 1.8 + 1.3.2 + 1.2.3 + 4.12 + 3.1.6.RELEASE + 3.7.0 + 1.6.0 + 3.1.0 diff --git a/micronaut/src/main/resources/application.yml b/micronaut/src/main/resources/application.yml index 4119026dd6..32daacd4aa 100644 --- a/micronaut/src/main/resources/application.yml +++ b/micronaut/src/main/resources/application.yml @@ -2,4 +2,4 @@ micronaut: application: name: hello-world-server server: - port: 9080 \ No newline at end of file + port: ${random.port} \ No newline at end of file diff --git a/netflix/README.md b/netflix-modules/README.md similarity index 89% rename from netflix/README.md rename to netflix-modules/README.md index 0af07d37a8..4afea527df 100644 --- a/netflix/README.md +++ b/netflix-modules/README.md @@ -1,4 +1,4 @@ -## Netflix +## Netflix Modules This module contains articles about Netflix. diff --git a/netflix/genie/pom.xml b/netflix-modules/genie/pom.xml similarity index 92% rename from netflix/genie/pom.xml rename to netflix-modules/genie/pom.xml index 2288c5338a..835bbf2b50 100644 --- a/netflix/genie/pom.xml +++ b/netflix-modules/genie/pom.xml @@ -10,7 +10,7 @@ com.baeldung - netflix + netflix-modules 1.0.0-SNAPSHOT diff --git a/netflix/genie/src/main/resources/com/baeldung/netflix/genie/docker/docker-compose.yml b/netflix-modules/genie/src/main/resources/com/baeldung/netflix/genie/docker/docker-compose.yml similarity index 100% rename from netflix/genie/src/main/resources/com/baeldung/netflix/genie/docker/docker-compose.yml rename to netflix-modules/genie/src/main/resources/com/baeldung/netflix/genie/docker/docker-compose.yml diff --git a/netflix/genie/src/main/resources/com/baeldung/netflix/genie/docker/init_demo.py b/netflix-modules/genie/src/main/resources/com/baeldung/netflix/genie/docker/init_demo.py similarity index 100% rename from netflix/genie/src/main/resources/com/baeldung/netflix/genie/docker/init_demo.py rename to netflix-modules/genie/src/main/resources/com/baeldung/netflix/genie/docker/init_demo.py diff --git a/netflix/genie/src/main/resources/com/baeldung/netflix/genie/docker/run_spark_submit_job.py b/netflix-modules/genie/src/main/resources/com/baeldung/netflix/genie/docker/run_spark_submit_job.py similarity index 100% rename from netflix/genie/src/main/resources/com/baeldung/netflix/genie/docker/run_spark_submit_job.py rename to netflix-modules/genie/src/main/resources/com/baeldung/netflix/genie/docker/run_spark_submit_job.py diff --git a/netflix/pom.xml b/netflix-modules/pom.xml similarity index 89% rename from netflix/pom.xml rename to netflix-modules/pom.xml index 6cf81cd7ab..5a082e8f1a 100644 --- a/netflix/pom.xml +++ b/netflix-modules/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - netflix + netflix-modules 1.0.0-SNAPSHOT - Netflix + Netflix Modules pom Module for Netflix projects diff --git a/ninja/pom.xml b/ninja/pom.xml index 8ec2422d9f..b66225f693 100644 --- a/ninja/pom.xml +++ b/ninja/pom.xml @@ -13,6 +13,9 @@ 6.5.0 9.4.18.v20190429 + 3.3.4 + 2.1.3 + 1.4.186 @@ -156,17 +159,17 @@ org.webjars bootstrap - 3.3.4 + ${bootstrap.version} org.webjars jquery - 2.1.3 + ${jquery.version} com.h2database h2 - 1.4.186 + ${h2.version} org.ninjaframework diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernatelogging/HibernateLoggingIntegrationTest.java b/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java similarity index 97% rename from persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernatelogging/HibernateLoggingIntegrationTest.java rename to persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java index 8ec722671d..f609c75834 100644 --- a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernatelogging/HibernateLoggingIntegrationTest.java +++ b/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.hibernatelogging; +package com.baeldung.hibernate.logging; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java index 022099eed0..6ce9bcad45 100644 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java @@ -5,9 +5,9 @@ import java.util.List; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.PagingAndSortingRepository; -import com.baeldung.multipledb.model.product.ProductMultipleDB; +import com.baeldung.multipledb.model.product.Product; -public interface ProductRepository extends PagingAndSortingRepository { +public interface ProductRepository extends PagingAndSortingRepository { - List findAllByPrice(double price, Pageable pageable); + List findAllByPrice(double price, Pageable pageable); } diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/ProductMultipleDB.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java similarity index 80% rename from persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/ProductMultipleDB.java rename to persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java index 8bdff340ac..eaf471043c 100644 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/ProductMultipleDB.java +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java @@ -6,7 +6,7 @@ import javax.persistence.Table; @Entity @Table(schema = "products") -public class ProductMultipleDB { +public class Product { @Id private int id; @@ -15,19 +15,19 @@ public class ProductMultipleDB { private double price; - public ProductMultipleDB() { + public Product() { super(); } - private ProductMultipleDB(int id, String name, double price) { + private Product(int id, String name, double price) { super(); this.id = id; this.name = name; this.price = price; } - public static ProductMultipleDB from(int id, String name, double price) { - return new ProductMultipleDB(id, name, price); + public static Product from(int id, String name, double price) { + return new Product(id, name, price); } public int getId() { diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java index cdbb307d7f..831790af95 100644 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java @@ -23,7 +23,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; import com.baeldung.multipledb.dao.product.ProductRepository; -import com.baeldung.multipledb.model.product.ProductMultipleDB; +import com.baeldung.multipledb.model.product.Product; @RunWith(SpringRunner.class) @SpringBootTest(classes=MultipleDbApplication.class) @@ -36,22 +36,22 @@ public class ProductRepositoryIntegrationTest { @Before @Transactional("productTransactionManager") public void setUp() { - productRepository.save(ProductMultipleDB.from(1001, "Book", 21)); - productRepository.save(ProductMultipleDB.from(1002, "Coffee", 10)); - productRepository.save(ProductMultipleDB.from(1003, "Jeans", 30)); - productRepository.save(ProductMultipleDB.from(1004, "Shirt", 32)); - productRepository.save(ProductMultipleDB.from(1005, "Bacon", 10)); + productRepository.save(Product.from(1001, "Book", 21)); + productRepository.save(Product.from(1002, "Coffee", 10)); + productRepository.save(Product.from(1003, "Jeans", 30)); + productRepository.save(Product.from(1004, "Shirt", 32)); + productRepository.save(Product.from(1005, "Bacon", 10)); } @Test public void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() { Pageable pageRequest = PageRequest.of(0, 2); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(2)); assertTrue(result.stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .allMatch(id -> Arrays.asList(1001, 1002) .contains(id))); } @@ -60,11 +60,11 @@ public class ProductRepositoryIntegrationTest { public void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() { Pageable pageRequest = PageRequest.of(1, 2); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(2)); assertTrue(result.stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .allMatch(id -> Arrays.asList(1003, 1004) .contains(id))); } @@ -73,11 +73,11 @@ public class ProductRepositoryIntegrationTest { public void whenRequestingLastPage_ThenReturnLastPageWithRemData() { Pageable pageRequest = PageRequest.of(2, 2); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(1)); assertTrue(result.stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .allMatch(id -> Arrays.asList(1005) .contains(id))); } @@ -86,12 +86,12 @@ public class ProductRepositoryIntegrationTest { public void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() { Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name")); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(3)); assertThat(result.getContent() .stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .collect(Collectors.toList()), equalTo(Arrays.asList(1005, 1001, 1002))); } @@ -101,12 +101,12 @@ public class ProductRepositoryIntegrationTest { Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price") .descending()); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(3)); assertThat(result.getContent() .stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001))); } @@ -117,12 +117,12 @@ public class ProductRepositoryIntegrationTest { .descending() .and(Sort.by("name"))); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(5)); assertThat(result.getContent() .stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001, 1005, 1002))); } @@ -131,11 +131,11 @@ public class ProductRepositoryIntegrationTest { public void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() { Pageable pageRequest = PageRequest.of(0, 2); - List result = productRepository.findAllByPrice(10, pageRequest); + List result = productRepository.findAllByPrice(10, pageRequest); assertThat(result, hasSize(2)); assertTrue(result.stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .allMatch(id -> Arrays.asList(1002, 1005) .contains(id))); } diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java index e202e45b32..7d3a881827 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java @@ -15,6 +15,7 @@ import org.springframework.dao.annotation.PersistenceExceptionTranslationPostPro import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; @@ -39,12 +40,12 @@ public class PersistenceJPAConfig { // beans @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java index fde1857ca2..72031a2232 100644 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java @@ -14,6 +14,7 @@ import org.springframework.dao.annotation.PersistenceExceptionTranslationPostPro import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; @@ -91,12 +92,12 @@ public class PersistenceTransactionalTestConfig { // beans @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); diff --git a/pom.xml b/pom.xml index dc87307a85..bbc14aa011 100644 --- a/pom.xml +++ b/pom.xml @@ -332,19 +332,23 @@ parent-spring-5 parent-java parent-kotlin - + + akka-http akka-streams + algorithms-genetic algorithms-miscellaneous-1 algorithms-miscellaneous-2 algorithms-miscellaneous-3 algorithms-miscellaneous-4 algorithms-miscellaneous-5 - algorithms-sorting algorithms-searching + algorithms-sorting + algorithms-sorting-2 animal-sniffer-mvn-plugin annotations antlr + apache-avro apache-bval apache-curator @@ -365,12 +369,18 @@ apache-tika apache-velocity apache-zookeeper + asciidoctor asm + atomix + aws aws-lambda + aws-reactive + axon + azure bazel @@ -380,83 +390,18 @@ cas cdi checker-plugin - cloud-foundry-uaa/cf-uaa-oauth2-client - cloud-foundry-uaa/cf-uaa-oauth2-resource-server + + cloud-foundry-uaa code-generation + core-groovy core-groovy-2 core-groovy-collections - - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 - core-java-modules/core-java-annotations - core-java-modules/core-java-streams - core-java-modules/core-java-streams-2 - core-java-modules/core-java-streams-3 - - core-java-modules/core-java-function - core-java-modules/core-java-lang-math - - - core-java-modules/core-java-text - core-java-modules/core-java-lambdas - - - core-java-modules/core-java-arrays - core-java-modules/core-java-arrays-2 - core-java-modules/core-java-collections - core-java-modules/core-java-collections-2 - core-java-modules/core-java-collections-3 - core-java-modules/core-java-collections-list - core-java-modules/core-java-collections-list-2 - core-java-modules/core-java-collections-list-3 - core-java-modules/core-java-collections-array-list - core-java-modules/core-java-collections-set - core-java-modules/core-java-concurrency-basic - core-java-modules/core-java-concurrency-basic-2 - core-java-modules/core-java-concurrency-collections - core-java-modules/core-java-io - core-java-modules/core-java-io-2 - core-java-modules/core-java-io-apis - core-java-modules/core-java-io-conversions - core-java-modules/core-java-nio - core-java-modules/core-java-nio-2 - core-java-modules/core-java-security - core-java-modules/core-java-exceptions - core-java-modules/core-java-lang-syntax - core-java-modules/core-java-lang-syntax-2 - core-java-modules/core-java-lang - core-java-modules/core-java-lang-2 - core-java-modules/core-java-lang-oop - core-java-modules/core-java-lang-oop-2 - core-java-modules/core-java-lang-oop-3 - core-java-modules/core-java-lang-oop-4 + core-java-modules - core-java-modules/core-java-networking - core-java-modules/core-java-perf - core-java-modules/core-java-reflection - core-java-modules/core-java-sun - core-java-modules/core-java-string-conversions - core-java-modules/core-java-string-conversions-2 - core-java-modules/core-java-string-operations - core-java-modules/core-java-string-operations-2 - core-java-modules/core-java-string-algorithms - core-java-modules/core-java-string-algorithms-2 - core-java-modules/core-java-string-apis - core-java-modules/core-java-strings - core-java-modules/core-java - core-java-modules/core-java-jar - core-java-modules/core-java-jvm core-kotlin-modules core-scala + couchbase custom-pmd @@ -478,15 +423,16 @@ google-cloud google-web-toolkit + graphql/graphql-java grpc gson guava - guava-io guava-collections guava-collections-map guava-collections-set + guava-io guava-modules guice @@ -501,12 +447,16 @@ immutables jackson-modules + java-blockchain + java-collections-conversions java-collections-conversions-2 java-collections-maps java-collections-maps-2 - java-jdi + + javafx + java-jdi java-lite java-math java-math-2 @@ -517,12 +467,10 @@ java-spi java-vavr-stream java-websocket - javafx javax-servlets javaxval jaxb - + jee-7 jee-7-security jee-kotlin jersey @@ -544,52 +492,52 @@ kotlin-libraries kotlin-libraries-2 + kotlin-quasar - libraries libraries-2 libraries-3 + libraries-apache-commons + libraries-apache-commons-collections + libraries-apache-commons-io libraries-data libraries-data-2 libraries-data-db libraries-data-io - libraries-apache-commons - libraries-apache-commons-collections - libraries-apache-commons-io - libraries-primitive - libraries-testing - libraries-security - libraries-server libraries-http libraries-io + libraries-primitive + libraries-security + libraries-server + libraries-testing linkrest logging-modules lombok + lombok-custom lucene + machine-learning mapstruct - - maven-all/maven - maven-all/maven-custom-plugin/counter-maven-plugin - maven-all/maven-war-plugin - maven-all/profiles - maven-all/versions-maven-plugin + + maven-all maven-archetype - - maven-polyglot/maven-polyglot-json-extension - + + maven-polyglot + mesos-marathon metrics - + micronaut microprofile msf4j - + mustache mybatis + + netflix-modules ninja - netflix open-liberty + oauth2-framework-impl optaplanner orika osgi @@ -597,11 +545,12 @@ patterns pdf performance-tests + persistence-modules protobuffer - persistence-modules quarkus + rabbitmq @@ -609,32 +558,12 @@ reactor-core resteasy restx - - rule-engines rsocket + rule-engines rxjava-core + rxjava-libraries rxjava-observables rxjava-operators - rxjava-libraries - software-security/sql-injection-samples - - tensorflow-java - spf4j - spring-boot-config-jpa-error - spring-boot-flowable - spring-boot-mvc-2 - spring-boot-performance - spring-boot-properties - spring-mvc-basics - spring-security-modules/spring-security-kerberos - oauth2-framework-impl - - spring-boot-nashorn - java-blockchain - machine-learning - webrtc - wildfly - quarkus-extension @@ -670,8 +599,6 @@ - netflix - parent-boot-1 parent-boot-2 parent-spring-4 @@ -680,12 +607,14 @@ parent-kotlin saas + software-security/sql-injection-samples + spark-java + spf4j spring-4 spring-5 - spring-5-webflux spring-5-data-reactive spring-5-mvc spring-5-reactive @@ -694,55 +623,63 @@ spring-5-reactive-oauth spring-5-reactive-security spring-5-security - spring-5-security-oauth spring-5-security-cognito + spring-5-security-oauth + spring-5-webflux spring-activiti spring-akka spring-amqp spring-aop spring-apache-camel + spring-batch spring-bom spring-boot spring-boot-admin spring-boot-angular + spring-boot-artifacts spring-boot-autoconfiguration spring-boot-bootstrap spring-boot-camel - spring-boot-config-jpa-error spring-boot-client - + spring-boot-config-jpa-error spring-boot-crud spring-boot-ctx-fluent spring-boot-custom-starter + spring-boot-data + spring-boot-deployment + spring-boot-di + spring-boot-environment + spring-boot-flowable spring-boot-jasypt spring-boot-keycloak spring-boot-kotlin + spring-boot-libraries spring-boot-logging-log4j2 spring-boot-mvc + spring-boot-mvc-2 spring-boot-mvc-birt - spring-boot-environment - spring-boot-deployment + spring-boot-nashorn + spring-boot-parent + spring-boot-performance + spring-boot-properties + spring-boot-property-exp + + spring-boot-rest spring-boot-runtime spring-boot-runtime/disabling-console-jul spring-boot-runtime/disabling-console-log4j2 spring-boot-runtime/disabling-console-logback - spring-boot-artifacts - spring-boot-rest - spring-boot-data - spring-boot-parent - spring-boot-property-exp spring-boot-security spring-boot-springdoc spring-boot-testing spring-boot-vue - spring-caching - spring-boot-libraries + spring-caching spring-cloud spring-cloud-bus @@ -756,9 +693,9 @@ spring-data-rest spring-data-rest-querydsl + spring-di spring-dispatcher-servlet spring-drools - spring-di spring-ehcache spring-ejb @@ -783,60 +720,41 @@ spring-mobile spring-mockito - spring-websockets + + spring-mvc-basics + spring-mvc-basics-2 + spring-mvc-basics-3 spring-mvc-basics-4 + spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java spring-mvc-kotlin - spring-mvc-basics-2 - spring-mvc-basics-3 - spring-mvc-views + spring-mvc-velocity + spring-mvc-views spring-mvc-webflow spring-mvc-xml spring-protobuf - - spring-quartz spring-reactive-kotlin spring-reactor spring-remoting - spring-rest-http spring-rest-angular spring-rest-compress - spring-rest-testing spring-rest-hal-browser + spring-rest-http spring-rest-query-language spring-rest-shell spring-rest-simple spring-resttemplate + spring-rest-testing spring-roo + spring-scheduling - spring-security-modules/spring-security-acl - spring-security-modules/spring-security-angular/server - spring-security-modules/spring-security-cache-control - spring-security-modules/spring-security-core - spring-security-modules/spring-security-mvc - spring-security-modules/spring-security-mvc-boot - spring-security-modules/spring-security-mvc-custom - spring-security-modules/spring-security-mvc-digest-auth - spring-security-modules/spring-security-mvc-jsonview - spring-security-modules/spring-security-mvc-ldap - spring-security-modules/spring-security-mvc-login - spring-security-modules/spring-security-mvc-persisted-remember-me - spring-security-modules/spring-security-mvc-socket - spring-security-modules/spring-security-oidc - - spring-security-modules/spring-security-rest - spring-security-modules/spring-security-rest-basic-auth - spring-security-modules/spring-security-rest-custom - spring-security-modules/spring-security-sso - spring-security-modules/spring-security-stormpath - spring-security-modules/spring-security-thymeleaf - spring-security-modules/spring-security-x509 + spring-security-modules spring-session spring-shell spring-sleuth @@ -848,17 +766,20 @@ spring-swagger-codegen spring-thymeleaf + spring-thymeleaf-2 spring-vault spring-vertx spring-webflux-amqp + spring-websockets static-analysis stripe structurizr struts-2 + tensorflow-java testing-modules twilio @@ -871,17 +792,11 @@ video-tutorials vraptor + webrtc wicket - + wildfly xml xstream - - tensorflow-java - spring-boot-flowable - spring-security-modules/spring-security-kerberos - - spring-boot-nashorn - java-blockchain @@ -924,9 +839,6 @@ parent-java parent-kotlin - core-java-modules/core-java-concurrency-advanced - core-java-modules/core-java-concurrency-advanced-2 - core-java-modules/core-java-concurrency-advanced-3 core-kotlin core-kotlin-2 @@ -935,12 +847,6 @@ jws libraries - persistence-modules/hibernate5 - persistence-modules/hibernate-mapping - persistence-modules/java-jpa - persistence-modules/java-jpa-2 - persistence-modules/java-mongodb - persistence-modules/jnosql vaadin vavr @@ -976,19 +882,23 @@ parent-spring-5 parent-java parent-kotlin - + + akka-http akka-streams + algorithms-genetic algorithms-miscellaneous-1 algorithms-miscellaneous-2 algorithms-miscellaneous-3 algorithms-miscellaneous-4 algorithms-miscellaneous-5 - algorithms-sorting algorithms-searching + algorithms-sorting + algorithms-sorting-2 animal-sniffer-mvn-plugin annotations antlr + apache-avro apache-bval apache-curator @@ -1009,90 +919,39 @@ apache-tika apache-velocity apache-zookeeper + asciidoctor asm + atomix + aws aws-lambda + aws-reactive + axon + azure + bazel + blade bootique cas cdi checker-plugin - cloud-foundry-uaa/cf-uaa-oauth2-client - cloud-foundry-uaa/cf-uaa-oauth2-resource-server + + cloud-foundry-uaa code-generation + core-groovy core-groovy-2 core-groovy-collections - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 - core-java-modules/core-java-annotations - core-java-modules/core-java-streams - core-java-modules/core-java-streams-2 - core-java-modules/core-java-streams-3 - - core-java-modules/core-java-function - core-java-modules/core-java-lang-math - - - core-java-modules/core-java-text - - - core-java-modules/core-java-arrays - core-java-modules/core-java-arrays-2 - core-java-modules/core-java-collections - core-java-modules/core-java-collections-2 - core-java-modules/core-java-collections-3 - core-java-modules/core-java-collections-list - core-java-modules/core-java-collections-list-2 - core-java-modules/core-java-collections-list-3 - core-java-modules/core-java-collections-array-list - core-java-modules/core-java-collections-set - core-java-modules/core-java-concurrency-basic - core-java-modules/core-java-concurrency-basic-2 - core-java-modules/core-java-concurrency-collections - core-java-modules/core-java-io - core-java-modules/core-java-io-2 - core-java-modules/core-java-io-apis - core-java-modules/core-java-io-conversions - core-java-modules/core-java-nio - core-java-modules/core-java-nio-2 - core-java-modules/core-java-security - core-java-modules/core-java-exceptions - core-java-modules/core-java-lang-syntax - core-java-modules/core-java-lang-syntax-2 - core-java-modules/core-java-lang - core-java-modules/core-java-lang-2 - core-java-modules/core-java-lang-oop - core-java-modules/core-java-lang-oop-2 - core-java-modules/core-java-lang-oop-3 - core-java-modules/core-java-lang-oop-4 + core-java-modules - core-java-modules/core-java-networking - core-java-modules/core-java-perf - core-java-modules/core-java-sun - core-java-modules/core-java-string-conversions - core-java-modules/core-java-string-conversions-2 - core-java-modules/core-java-string-operations - core-java-modules/core-java-string-operations-2 - core-java-modules/core-java-string-algorithms - core-java-modules/core-java-string-algorithms-2 - core-java-modules/core-java-string-apis - core-java-modules/core-java-strings core-kotlin-modules core-scala + couchbase custom-pmd @@ -1114,15 +973,16 @@ google-cloud google-web-toolkit + graphql/graphql-java grpc gson guava - guava-io guava-collections guava-collections-map guava-collections-set + guava-io guava-modules guice @@ -1137,15 +997,19 @@ immutables jackson-modules + java-blockchain + java-collections-conversions java-collections-conversions-2 java-collections-maps java-collections-maps-2 + + + javafx java-jdi - java-ee-8-security-api java-lite java-math - java-math-2 + java-math-2 java-numbers java-numbers-2 java-numbers-3 @@ -1153,12 +1017,10 @@ java-spi java-vavr-stream java-websocket - javafx javax-servlets javaxval jaxb - + jee-7 jee-7-security jee-kotlin jersey @@ -1179,50 +1041,53 @@ kotlin-libraries + kotlin-libraries-2 + kotlin-quasar - libraries + libraries-2 libraries-3 + libraries-apache-commons + libraries-apache-commons-collections + libraries-apache-commons-io libraries-data libraries-data-2 libraries-data-db libraries-data-io - libraries-apache-commons - libraries-apache-commons-collections - libraries-apache-commons-io - libraries-testing + libraries-http + libraries-io + libraries-primitive libraries-security libraries-server - libraries-http + libraries-testing linkrest logging-modules lombok + lombok-custom lucene + machine-learning mapstruct - - maven-all/maven - maven-all/maven-custom-plugin/counter-maven-plugin - maven-all/maven-war-plugin - maven-all/profiles - maven-all/versions-maven-plugin - + + maven-all maven-archetype - - maven-polyglot/maven-polyglot-json-extension - + + maven-polyglot + mesos-marathon metrics - + micronaut microprofile msf4j - + mustache mybatis + + netflix-modules ninja - netflix open-liberty + oauth2-framework-impl optaplanner orika osgi @@ -1230,10 +1095,12 @@ patterns pdf performance-tests + persistence-modules protobuffer - persistence-modules + quarkus + rabbitmq @@ -1241,20 +1108,12 @@ reactor-core resteasy restx - - rule-engines rsocket + rule-engines rxjava-core + rxjava-libraries rxjava-observables rxjava-operators - rxjava-libraries - oauth2-framework-impl - spf4j - spring-boot-performance - spring-boot-properties - spring-mvc-basics - - @@ -1290,7 +1149,10 @@ parent-kotlin saas + software-security/sql-injection-samples + spark-java + spf4j spring-4 @@ -1303,48 +1165,64 @@ spring-5-reactive-oauth spring-5-reactive-security spring-5-security - spring-5-security-oauth spring-5-security-cognito + spring-5-security-oauth + spring-5-webflux + spring-activiti spring-akka spring-amqp spring-aop spring-apache-camel + spring-batch spring-bom spring-boot spring-boot-admin spring-boot-angular + spring-boot-artifacts spring-boot-autoconfiguration spring-boot-bootstrap spring-boot-camel spring-boot-client + spring-boot-config-jpa-error spring-boot-crud spring-boot-ctx-fluent spring-boot-custom-starter + spring-boot-data + spring-boot-deployment + spring-boot-di + spring-boot-environment + spring-boot-flowable spring-boot-jasypt spring-boot-keycloak + spring-boot-kotlin + spring-boot-libraries spring-boot-logging-log4j2 spring-boot-mvc + spring-boot-mvc-2 spring-boot-mvc-birt - spring-boot-environment - spring-boot-deployment + spring-boot-nashorn + spring-boot-parent + spring-boot-performance + spring-boot-properties + spring-boot-property-exp + + spring-boot-rest spring-boot-runtime spring-boot-runtime/disabling-console-jul spring-boot-runtime/disabling-console-log4j2 spring-boot-runtime/disabling-console-logback - spring-boot-artifacts - spring-boot-rest - spring-boot-data - spring-boot-parent - spring-boot-property-exp spring-boot-security spring-boot-springdoc + spring-boot-testing spring-boot-vue + spring-caching + spring-cloud spring-cloud-bus @@ -1357,9 +1235,9 @@ spring-data-rest spring-data-rest-querydsl + spring-di spring-dispatcher-servlet spring-drools - spring-di spring-ehcache spring-ejb @@ -1384,60 +1262,41 @@ spring-mobile spring-mockito - spring-websockets + + spring-mvc-basics + spring-mvc-basics-2 + spring-mvc-basics-3 + spring-mvc-basics-4 + spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java spring-mvc-kotlin - spring-mvc-basics-2 - spring-mvc-basics-3 - spring-mvc-basics-4 - spring-mvc-views + spring-mvc-velocity + spring-mvc-views spring-mvc-webflow spring-mvc-xml spring-protobuf - - spring-quartz spring-reactive-kotlin spring-reactor spring-remoting - spring-rest-http spring-rest-angular spring-rest-compress - spring-rest-testing spring-rest-hal-browser + spring-rest-http spring-rest-query-language spring-rest-shell spring-rest-simple spring-resttemplate + spring-rest-testing spring-roo spring-scheduling - spring-security-modules/spring-security-acl - spring-security-modules/spring-security-angular/server - spring-security-modules/spring-security-cache-control - spring-security-modules/spring-security-core - spring-security-modules/spring-security-mvc - spring-security-modules/spring-security-mvc-boot - spring-security-modules/spring-security-mvc-custom - spring-security-modules/spring-security-mvc-digest-auth - spring-security-modules/spring-security-mvc-ldap - spring-security-modules/spring-security-mvc-login - spring-security-modules/spring-security-mvc-persisted-remember-me - spring-security-modules/spring-security-mvc-socket - spring-security-modules/spring-security-oidc - - spring-security-modules/spring-security-rest - spring-security-modules/spring-security-rest-basic-auth - spring-security-modules/spring-security-rest-custom - spring-security-modules/spring-security-sso - spring-security-modules/spring-security-stormpath - spring-security-modules/spring-security-thymeleaf - spring-security-modules/spring-security-x509 + spring-security-modules spring-session spring-shell spring-sleuth @@ -1449,17 +1308,20 @@ spring-swagger-codegen spring-thymeleaf + spring-thymeleaf-2 spring-vault spring-vertx spring-webflux-amqp + spring-websockets static-analysis stripe structurizr struts-2 + tensorflow-java testing-modules twilio @@ -1472,8 +1334,9 @@ video-tutorials vraptor + webrtc wicket - + wildfly xml xstream @@ -1510,11 +1373,6 @@ parent-java parent-kotlin - core-java-modules/core-java - core-java-modules/core-java-jar - core-java-modules/core-java-concurrency-advanced - core-java-modules/core-java-concurrency-advanced-2 - core-java-modules/core-java-concurrency-advanced-3 core-kotlin core-kotlin-2 @@ -1524,13 +1382,6 @@ libraries - persistence-modules/hibernate5 - persistence-modules/hibernate-mapping - persistence-modules/java-jpa - persistence-modules/java-jpa-2 - persistence-modules/java-mongodb - persistence-modules/jnosql - vaadin vavr diff --git a/slack/pom.xml b/slack/pom.xml new file mode 100644 index 0000000000..ebe5ce2f60 --- /dev/null +++ b/slack/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + com.baeldung.examples + slack + 1.0 + slack + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.hubspot.slack + slack-base + ${slack.version} + + + com.hubspot.slack + slack-java-client + ${slack.version} + + + + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven-jar-plugin.version} + + + + true + com.baeldung.examples.slack.MainClass + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + com.baeldung.examples.slack.MainClass + + + + + + + 1.4 + 2.4 + + + diff --git a/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java b/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java new file mode 100644 index 0000000000..7a3f5cd607 --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java @@ -0,0 +1,42 @@ +package com.baeldung.examples.slack; + +import java.io.IOException; +import java.nio.file.FileSystems; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DiskSpaceErrorChecker implements ErrorChecker { + private static final Logger LOG = LoggerFactory.getLogger(DiskSpaceErrorChecker.class); + + private final ErrorReporter errorReporter; + + private final double limit; + + public DiskSpaceErrorChecker(ErrorReporter errorReporter, double limit) { + this.errorReporter = errorReporter; + this.limit = limit; + } + + @Override + public void check() { + LOG.info("Checking disk space"); + FileSystems.getDefault().getFileStores().forEach(fileStore -> { + try { + long totalSpace = fileStore.getTotalSpace(); + long usableSpace = fileStore.getUsableSpace(); + double usablePercentage = ((double) usableSpace) / totalSpace; + LOG.debug("File store {} has {} of {} ({}) usable space", + fileStore, usableSpace, totalSpace, usablePercentage); + + if (totalSpace > 0 && usablePercentage < limit) { + String error = String.format("File store %s only has %d%% usable disk space", + fileStore.name(), (int)(usablePercentage * 100)); + errorReporter.reportProblem(error); + } + } catch (IOException e) { + LOG.error("Error getting disk space for file store {}", fileStore, e); + } + }); + } +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java b/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java new file mode 100644 index 0000000000..08db9a7817 --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.slack; + +public interface ErrorChecker { + void check(); +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java b/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java new file mode 100644 index 0000000000..ba6165af9b --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.slack; + +public interface ErrorReporter { + void reportProblem(String problem); +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/MainClass.java b/slack/src/main/java/com/baeldung/examples/slack/MainClass.java new file mode 100644 index 0000000000..ac25e97cf6 --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/MainClass.java @@ -0,0 +1,41 @@ +package com.baeldung.examples.slack; + +import java.io.IOException; +import java.util.Timer; +import java.util.TimerTask; + +import com.hubspot.slack.client.SlackClient; +import com.hubspot.slack.client.SlackClientFactory; +import com.hubspot.slack.client.SlackClientRuntimeConfig; + +public class MainClass { + public static final long MINUTES = 1000 * 60; + + public static void main(String[] args) throws IOException { + SlackClientRuntimeConfig runtimeConfig = SlackClientRuntimeConfig.builder() + .setTokenSupplier(() -> "") + .build(); + + SlackClient slackClient = SlackClientFactory.defaultFactory().build(runtimeConfig); + + ErrorReporter slackChannelErrorReporter = new SlackChannelErrorReporter(slackClient, "general"); + ErrorReporter slackUserErrorReporter = new SlackUserErrorReporter(slackClient, "testuser@baeldung.com"); + + ErrorChecker diskSpaceErrorChecker10pct = new DiskSpaceErrorChecker(slackChannelErrorReporter, 0.1); + ErrorChecker diskSpaceErrorChecker2pct = new DiskSpaceErrorChecker(slackUserErrorReporter, 0.02); + + Timer timer = new Timer(); + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + diskSpaceErrorChecker10pct.check(); + } + }, 0, 5 * MINUTES); + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + diskSpaceErrorChecker2pct.check(); + } + }, 0, 5 * MINUTES); + } +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java b/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java new file mode 100644 index 0000000000..f7abcecc2e --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java @@ -0,0 +1,30 @@ +package com.baeldung.examples.slack; + +import com.hubspot.slack.client.SlackClient; +import com.hubspot.slack.client.methods.params.chat.ChatPostMessageParams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SlackChannelErrorReporter implements ErrorReporter { + private static final Logger LOG = LoggerFactory.getLogger(SlackChannelErrorReporter.class); + + private final SlackClient slackClient; + + private final String channel; + + public SlackChannelErrorReporter(SlackClient slackClient, String channel) { + this.slackClient = slackClient; + this.channel = channel; + } + + @Override + public void reportProblem(String problem) { + LOG.debug("Sending message to channel {}: {}", channel, problem); + slackClient.postMessage( + ChatPostMessageParams.builder() + .setText(problem) + .setChannelId(channel) + .build() + ).join().unwrapOrElseThrow(); + } +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java b/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java new file mode 100644 index 0000000000..8fa4f9016b --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java @@ -0,0 +1,52 @@ +package com.baeldung.examples.slack; + +import java.util.List; + +import com.hubspot.slack.client.SlackClient; +import com.hubspot.slack.client.methods.params.chat.ChatPostMessageParams; +import com.hubspot.slack.client.methods.params.conversations.ConversationCreateParams; +import com.hubspot.slack.client.methods.params.im.ImOpenParams; +import com.hubspot.slack.client.methods.params.users.UserEmailParams; +import com.hubspot.slack.client.methods.params.users.UsersInfoParams; +import com.hubspot.slack.client.models.response.im.ImOpenResponse; +import com.hubspot.slack.client.models.response.users.UsersInfoResponse; +import com.hubspot.slack.client.models.users.SlackUser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SlackUserErrorReporter implements ErrorReporter { + private static final Logger LOG = LoggerFactory.getLogger(SlackUserErrorReporter.class); + + private final SlackClient slackClient; + + private final String user; + + public SlackUserErrorReporter(SlackClient slackClient, String user) { + this.slackClient = slackClient; + this.user = user; + } + + @Override + public void reportProblem(String problem) { + LOG.debug("Sending message to user {}: {}", user, problem); + UsersInfoResponse usersInfoResponse = slackClient + .lookupUserByEmail(UserEmailParams.builder() + .setEmail(user) + .build() + ).join().unwrapOrElseThrow(); + + ImOpenResponse imOpenResponse = slackClient.openIm(ImOpenParams.builder() + .setUserId(usersInfoResponse.getUser().getId()) + .build() + ).join().unwrapOrElseThrow(); + + imOpenResponse.getChannel().ifPresent(channel -> { + slackClient.postMessage( + ChatPostMessageParams.builder() + .setText(problem) + .setChannelId(channel.getId()) + .build() + ).join().unwrapOrElseThrow(); + }); + } +} diff --git a/slack/src/main/resources/logback.xml b/slack/src/main/resources/logback.xml new file mode 100644 index 0000000000..c8c077ba1d --- /dev/null +++ b/slack/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-boot-admin/pom.xml b/spring-boot-admin/pom.xml index ab2b92102c..8dbce0fd6c 100644 --- a/spring-boot-admin/pom.xml +++ b/spring-boot-admin/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT + ../parent-boot-2 diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/FilePropertyInjectionUnitTest.java b/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/FilePropertyInjectionUnitTest.java new file mode 100644 index 0000000000..874f632401 --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/FilePropertyInjectionUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.properties.testproperty; + +import org.assertj.core.api.Assertions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@TestPropertySource("/foo.properties") +public class FilePropertyInjectionUnitTest { + + @Value("${foo}") + private String foo; + + @Test + public void whenFilePropertyProvided_thenProperlyInjected() { + assertThat(foo).isEqualTo("bar"); + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/PropertyInjectionUnitTest.java b/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/PropertyInjectionUnitTest.java new file mode 100644 index 0000000000..9492e18322 --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/PropertyInjectionUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.properties.testproperty; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@TestPropertySource(properties = {"foo=bar"}) +public class PropertyInjectionUnitTest { + + @Value("${foo}") + private String foo; + + @Test + public void whenPropertyProvided_thenProperlyInjected() { + assertThat(foo).isEqualTo("bar"); + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/SpringBootPropertyInjectionIntegrationTest.java b/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/SpringBootPropertyInjectionIntegrationTest.java new file mode 100644 index 0000000000..fdca7e814d --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/SpringBootPropertyInjectionIntegrationTest.java @@ -0,0 +1,23 @@ +package com.baeldung.properties.testproperty; + +import com.baeldung.properties.reloading.SpringBootPropertiesTestApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(properties = {"foo=bar"}, classes = SpringBootPropertiesTestApplication.class) +public class SpringBootPropertyInjectionIntegrationTest { + + @Value("${foo}") + private String foo; + + @Test + public void whenSpringBootPropertyProvided_thenProperlyInjected() { + assertThat(foo).isEqualTo("bar"); + } +} diff --git a/spring-boot-properties/src/test/resources/configprops-test.properties b/spring-boot-properties/src/test/resources/configprops-test.properties index 5eed93a22b..3fc1195b98 100644 --- a/spring-boot-properties/src/test/resources/configprops-test.properties +++ b/spring-boot-properties/src/test/resources/configprops-test.properties @@ -24,3 +24,5 @@ item.size=21 #Additional properties additional.unit=km additional.max=100 + +key.something=val \ No newline at end of file diff --git a/spring-boot-properties/src/test/resources/foo.properties b/spring-boot-properties/src/test/resources/foo.properties new file mode 100644 index 0000000000..b5ae2aedd4 --- /dev/null +++ b/spring-boot-properties/src/test/resources/foo.properties @@ -0,0 +1,2 @@ +foo=bar +key.something=val \ No newline at end of file diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 2152a0a00d..b8ebd27e13 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -7,16 +7,17 @@ spring-boot war This is simple boot application for Spring boot actuator test + 0.0.1-SNAPSHOT - com.baeldung parent-boot-2 + com.baeldung 0.0.1-SNAPSHOT ../parent-boot-2 - + org.junit.jupiter @@ -198,6 +199,16 @@
+ + org.apache.maven.plugins + maven-resources-plugin + + + @ + + false + + @@ -251,6 +262,7 @@ 5.2.4 18.0 2.2.4 + @ diff --git a/spring-boot/src/main/java/com/baeldung/buildproperties/Application.java b/spring-boot/src/main/java/com/baeldung/buildproperties/Application.java new file mode 100644 index 0000000000..405cec3eac --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/buildproperties/Application.java @@ -0,0 +1,18 @@ +package com.baeldung.buildproperties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication +@ComponentScan(basePackages = "com.baeldung.buildproperties") +@PropertySource("classpath:build.properties") +//@PropertySource("classpath:build.yml") +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java b/spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java new file mode 100644 index 0000000000..2a0d27188e --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java @@ -0,0 +1,21 @@ +package com.baeldung.buildproperties; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +@Service +public class BuildInfoService { + @Value("${application-description}") + private String applicationDescription; + + @Value("${application-version}") + private String applicationVersion; + + public String getApplicationDescription() { + return applicationDescription; + } + + public String getApplicationVersion() { + return applicationVersion; + } +} diff --git a/spring-boot/src/main/resources/build.properties b/spring-boot/src/main/resources/build.properties new file mode 100644 index 0000000000..1612b8086d --- /dev/null +++ b/spring-boot/src/main/resources/build.properties @@ -0,0 +1,2 @@ +application-description=@project.description@ +application-version=@project.version@ \ No newline at end of file diff --git a/spring-boot/src/main/resources/build.yml b/spring-boot/src/main/resources/build.yml new file mode 100644 index 0000000000..528d2e3440 --- /dev/null +++ b/spring-boot/src/main/resources/build.yml @@ -0,0 +1,2 @@ +application-description: ^project.description^ +application-version: ^project.version^ \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java new file mode 100644 index 0000000000..cb056fe56d --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.buildproperties; + +import static org.junit.Assert.assertThat; + +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +class BuildInfoServiceIntegrationTest { + + @Autowired + private BuildInfoService service; + + @Test + void whenGetApplicationDescription_thenSuccess() { + assertThat(service.getApplicationDescription(), Matchers.is("This is simple boot application for Spring boot actuator test")); + assertThat(service.getApplicationVersion(), Matchers.is("0.0.1-SNAPSHOT")); + } +} diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java index 5d02d34f53..c32e36d7e3 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java @@ -1,19 +1,17 @@ package org.baeldung.boot.repository; -import static org.junit.Assert.assertThat; - import org.baeldung.boot.DemoApplicationIntegrationTest; import org.baeldung.demo.model.Foo; import org.baeldung.demo.repository.FooRepository; - -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.is; - import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + @Transactional public class FooRepositoryIntegrationTest extends DemoApplicationIntegrationTest { @Autowired @@ -28,8 +26,10 @@ public class FooRepositoryIntegrationTest extends DemoApplicationIntegrationTest @Test public void testFindByName() { Foo foo = fooRepository.findByName("Bar"); + assertThat(foo, notNullValue()); - assertThat(foo.getId(), is(2)); + assertThat(foo.getId(), notNullValue()); + assertThat(foo.getName(), is("Bar")); } } diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java index baa4f70e83..b22282e896 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java @@ -1,9 +1,5 @@ package org.baeldung.boot.repository; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertThat; - import org.baeldung.boot.DemoApplicationIntegrationTest; import org.baeldung.demo.model.Foo; import org.baeldung.demo.repository.FooRepository; @@ -11,6 +7,10 @@ import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; + @Transactional public class HibernateSessionIntegrationTest extends DemoApplicationIntegrationTest { @Autowired @@ -18,13 +18,12 @@ public class HibernateSessionIntegrationTest extends DemoApplicationIntegrationT @Test public void whenSavingWithCurrentSession_thenThrowNoException() { - Foo foo = new Foo("Exception Solved"); - fooRepository.save(foo); - foo = null; - foo = fooRepository.findByName("Exception Solved"); + fooRepository.save(new Foo("Exception Solved")); + + Foo foo = fooRepository.findByName("Exception Solved"); assertThat(foo, notNullValue()); - assertThat(foo.getId(), is(1)); + assertThat(foo.getId(), notNullValue()); assertThat(foo.getName(), is("Exception Solved")); } } diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml index 10cd49cc04..0f62c031cf 100644 --- a/spring-cloud/spring-cloud-gateway/pom.xml +++ b/spring-cloud/spring-cloud-gateway/pom.xml @@ -68,6 +68,10 @@ spring-boot-starter-test test
+ + org.springframework.boot + spring-boot-devtools + diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplication.java new file mode 100644 index 0000000000..e209b6cdf0 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.springcloudgateway.custompredicates; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; + +@SpringBootApplication +public class CustomPredicatesApplication { + + public static void main(String[] args) { + new SpringApplicationBuilder(CustomPredicatesApplication.class) + .profiles("customroutes") + .run(args); + } + +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/config/CustomPredicatesConfig.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/config/CustomPredicatesConfig.java new file mode 100644 index 0000000000..0e88b29bcf --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/config/CustomPredicatesConfig.java @@ -0,0 +1,38 @@ +package com.baeldung.springcloudgateway.custompredicates.config; + +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.springcloudgateway.custompredicates.factories.GoldenCustomerRoutePredicateFactory; +import com.baeldung.springcloudgateway.custompredicates.factories.GoldenCustomerRoutePredicateFactory.Config; +import com.baeldung.springcloudgateway.custompredicates.service.GoldenCustomerService; + +@Configuration +public class CustomPredicatesConfig { + + + @Bean + public GoldenCustomerRoutePredicateFactory goldenCustomer(GoldenCustomerService goldenCustomerService) { + return new GoldenCustomerRoutePredicateFactory(goldenCustomerService); + } + + + //@Bean + public RouteLocator routes(RouteLocatorBuilder builder, GoldenCustomerRoutePredicateFactory gf ) { + + return builder.routes() + .route("dsl_golden_route", r -> r.path("/dsl_api/**") + .filters(f -> f.stripPrefix(1)) + .uri("https://httpbin.org") + .predicate(gf.apply(new Config(true, "customerId")))) + .route("dsl_common_route", r -> r.path("/dsl_api/**") + .filters(f -> f.stripPrefix(1)) + .uri("https://httpbin.org") + .predicate(gf.apply(new Config(false, "customerId")))) + .build(); + } + +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/factories/GoldenCustomerRoutePredicateFactory.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/factories/GoldenCustomerRoutePredicateFactory.java new file mode 100644 index 0000000000..cb5c3a0b50 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/factories/GoldenCustomerRoutePredicateFactory.java @@ -0,0 +1,102 @@ +/** + * + */ +package com.baeldung.springcloudgateway.custompredicates.factories; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; + +import javax.validation.constraints.NotEmpty; + +import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory; +import org.springframework.http.HttpCookie; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.server.ServerWebExchange; + +import com.baeldung.springcloudgateway.custompredicates.service.GoldenCustomerService; + +/** + * @author Philippe + * + */ +public class GoldenCustomerRoutePredicateFactory extends AbstractRoutePredicateFactory { + + private final GoldenCustomerService goldenCustomerService; + + public GoldenCustomerRoutePredicateFactory(GoldenCustomerService goldenCustomerService ) { + super(Config.class); + this.goldenCustomerService = goldenCustomerService; + } + + + @Override + public List shortcutFieldOrder() { + return Arrays.asList("isGolden","customerIdCookie"); + } + + + @Override + public Predicate apply(Config config) { + + return (ServerWebExchange t) -> { + List cookies = t.getRequest() + .getCookies() + .get(config.getCustomerIdCookie()); + + boolean isGolden; + if ( cookies == null || cookies.isEmpty()) { + isGolden = false; + } + else { + String customerId = cookies.get(0).getValue(); + isGolden = goldenCustomerService.isGoldenCustomer(customerId); + } + + return config.isGolden()?isGolden:!isGolden; + }; + } + + + @Validated + public static class Config { + boolean isGolden = true; + + @NotEmpty + String customerIdCookie = "customerId"; + + + public Config() {} + + public Config( boolean isGolden, String customerIdCookie) { + this.isGolden = isGolden; + this.customerIdCookie = customerIdCookie; + } + + public boolean isGolden() { + return isGolden; + } + + public void setGolden(boolean value) { + this.isGolden = value; + } + + /** + * @return the customerIdCookie + */ + public String getCustomerIdCookie() { + return customerIdCookie; + } + + /** + * @param customerIdCookie the customerIdCookie to set + */ + public void setCustomerIdCookie(String customerIdCookie) { + this.customerIdCookie = customerIdCookie; + } + + + + } + +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/service/GoldenCustomerService.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/service/GoldenCustomerService.java new file mode 100644 index 0000000000..82bf2e6ae9 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/service/GoldenCustomerService.java @@ -0,0 +1,26 @@ +/** + * + */ +package com.baeldung.springcloudgateway.custompredicates.service; + +import org.springframework.stereotype.Component; + +/** + * @author Philippe + * + */ +@Component +public class GoldenCustomerService { + + public boolean isGoldenCustomer(String customerId) { + + // TODO: Add some AI logic to check is this customer deserves a "golden" status ;^) + if ( "baeldung".equalsIgnoreCase(customerId)) { + return true; + } + else { + return false; + } + } + +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application-customroutes.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application-customroutes.yml new file mode 100644 index 0000000000..859aa60bda --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application-customroutes.yml @@ -0,0 +1,26 @@ +spring: + cloud: + gateway: + routes: + - id: golden_route + uri: https://httpbin.org + predicates: + - Path=/api/** + - GoldenCustomer=true + filters: + - StripPrefix=1 + - AddRequestHeader=GoldenCustomer,true + - id: common_route + uri: https://httpbin.org + predicates: + - Path=/api/** + - name: GoldenCustomer + args: + golden: false + customerIdCookie: customerId + filters: + - StripPrefix=1 + - AddRequestHeader=GoldenCustomer,false + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/gatewayapp/CustomFiltersLiveTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/gatewayapp/CustomFiltersLiveTest.java index a4bb3f8068..f49f8c68b6 100644 --- a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/gatewayapp/CustomFiltersLiveTest.java +++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/gatewayapp/CustomFiltersLiveTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; import org.assertj.core.api.Condition; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; @@ -27,6 +28,7 @@ public class CustomFiltersLiveTest { @LocalServerPort String port; + @Autowired private WebTestClient client; @BeforeEach diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplicationLiveTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplicationLiveTest.java new file mode 100644 index 0000000000..d9988ceb5e --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplicationLiveTest.java @@ -0,0 +1,67 @@ +package com.baeldung.springcloudgateway.custompredicates; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +import java.net.URI; + +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; +import org.junit.Before; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; + +/** + * This test requires + */ +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("customroutes") +public class CustomPredicatesApplicationLiveTest { + + @LocalServerPort + String serverPort; + + @Autowired + private TestRestTemplate restTemplate; + + @Test + void givenNormalCustomer_whenCallHeadersApi_thenResponseForNormalCustomer() throws JSONException { + + String url = "http://localhost:" + serverPort + "/api/headers"; + ResponseEntity response = restTemplate.getForEntity(url, String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + JSONObject json = new JSONObject(response.getBody()); + JSONObject headers = json.getJSONObject("headers"); + assertThat(headers.getString("Goldencustomer")).isEqualTo("false"); + + } + + @Test + void givenGoldenCustomer_whenCallHeadersApi_thenResponseForGoldenCustomer() throws JSONException { + + String url = "http://localhost:" + serverPort + "/api/headers"; + RequestEntity request = RequestEntity + .get(URI.create(url)) + .header("Cookie", "customerId=baeldung") + .build(); + + ResponseEntity response = restTemplate.exchange(request, String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + JSONObject json = new JSONObject(response.getBody()); + JSONObject headers = json.getJSONObject("headers"); + assertThat(headers.getString("Goldencustomer")).isEqualTo("true"); + + } + +} diff --git a/spring-core-2/src/main/java/com/baeldung/scopes/ScopesConfig.java b/spring-core-2/src/main/java/com/baeldung/scopes/ScopesConfig.java new file mode 100644 index 0000000000..2291baa62d --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/scopes/ScopesConfig.java @@ -0,0 +1,49 @@ +package com.baeldung.scopes; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; +import org.springframework.context.annotation.ScopedProxyMode; +import org.springframework.web.context.annotation.ApplicationScope; +import org.springframework.web.context.annotation.RequestScope; +import org.springframework.web.context.annotation.SessionScope; + +@Configuration +public class ScopesConfig { + + @Bean + @Scope("singleton") + public Person personSingleton() { + return new Person(); + } + + @Bean + @Scope("prototype") + public Person personPrototype() { + return new Person(); + } + + @Bean + @RequestScope + public HelloMessageGenerator requestScopedBean() { + return new HelloMessageGenerator(); + } + + @Bean + @SessionScope + public HelloMessageGenerator sessionScopedBean() { + return new HelloMessageGenerator(); + } + + @Bean + @ApplicationScope + public HelloMessageGenerator applicationScopedBean() { + return new HelloMessageGenerator(); + } + + @Bean + @Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS) + public HelloMessageGenerator websocketScopedBean() { + return new HelloMessageGenerator(); + } +} diff --git a/spring-exceptions/README.md b/spring-exceptions/README.md index f8c7553f05..2136402d49 100644 --- a/spring-exceptions/README.md +++ b/spring-exceptions/README.md @@ -1,4 +1,4 @@ -## Spring `Exception`s +## Spring Exceptions This module contains articles about Spring `Exception`s diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/userHome.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/userHome.jsp new file mode 100644 index 0000000000..38c08d5a18 --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/userHome.jsp @@ -0,0 +1,55 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> + + + + + User Form + + + +
+ +

New User

+
${message}
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + +
+
+ + diff --git a/spring-mvc-views/src/main/java/com/baeldung/config/DataSourceConfig.java b/spring-mvc-views/src/main/java/com/baeldung/themes/config/DataSourceConfig.java similarity index 94% rename from spring-mvc-views/src/main/java/com/baeldung/config/DataSourceConfig.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/config/DataSourceConfig.java index 803c30f29d..3b1abfd459 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/config/DataSourceConfig.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/config/DataSourceConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.config; +package com.baeldung.themes.config; import org.springframework.context.annotation.Bean; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; @@ -27,7 +27,7 @@ public class DataSourceConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource); - em.setPackagesToScan("com.baeldung.domain"); + em.setPackagesToScan("com.baeldung.themes.domain"); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); return em; } diff --git a/spring-mvc-views/src/main/java/com/baeldung/config/InitSecurity.java b/spring-mvc-views/src/main/java/com/baeldung/themes/config/InitSecurity.java similarity index 82% rename from spring-mvc-views/src/main/java/com/baeldung/config/InitSecurity.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/config/InitSecurity.java index 2bf659f476..929e49cb79 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/config/InitSecurity.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/config/InitSecurity.java @@ -1,4 +1,4 @@ -package com.baeldung.config; +package com.baeldung.themes.config; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; diff --git a/spring-mvc-views/src/main/java/com/baeldung/config/SecurityConfig.java b/spring-mvc-views/src/main/java/com/baeldung/themes/config/SecurityConfig.java similarity index 98% rename from spring-mvc-views/src/main/java/com/baeldung/config/SecurityConfig.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/config/SecurityConfig.java index 2e0a413cf3..78a52d4f8b 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/config/SecurityConfig.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/config/SecurityConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.config; +package com.baeldung.themes.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; diff --git a/spring-mvc-views/src/main/java/com/baeldung/config/ThemeMVCConfig.java b/spring-mvc-views/src/main/java/com/baeldung/themes/config/ThemeMVCConfig.java similarity index 94% rename from spring-mvc-views/src/main/java/com/baeldung/config/ThemeMVCConfig.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/config/ThemeMVCConfig.java index 86f6f54195..1d3f94258e 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/config/ThemeMVCConfig.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/config/ThemeMVCConfig.java @@ -1,6 +1,6 @@ -package com.baeldung.config; +package com.baeldung.themes.config; -import com.baeldung.theme.resolver.UserPreferenceThemeResolver; +import com.baeldung.themes.resolver.UserPreferenceThemeResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; diff --git a/spring-mvc-views/src/main/java/com/baeldung/config/WebInitializer.java b/spring-mvc-views/src/main/java/com/baeldung/themes/config/WebInitializer.java similarity index 96% rename from spring-mvc-views/src/main/java/com/baeldung/config/WebInitializer.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/config/WebInitializer.java index 5516fb7b3c..3fbe8d043d 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/config/WebInitializer.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/config/WebInitializer.java @@ -1,4 +1,4 @@ -package com.baeldung.config; +package com.baeldung.themes.config; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; diff --git a/spring-mvc-views/src/main/java/com/baeldung/controllers/AppController.java b/spring-mvc-views/src/main/java/com/baeldung/themes/controllers/AppController.java similarity index 85% rename from spring-mvc-views/src/main/java/com/baeldung/controllers/AppController.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/controllers/AppController.java index 31343492e1..ed398fa60a 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/controllers/AppController.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/controllers/AppController.java @@ -1,4 +1,4 @@ -package com.baeldung.controllers; +package com.baeldung.themes.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/spring-mvc-views/src/main/java/com/baeldung/domain/UserPreference.java b/spring-mvc-views/src/main/java/com/baeldung/themes/domain/UserPreference.java similarity index 93% rename from spring-mvc-views/src/main/java/com/baeldung/domain/UserPreference.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/domain/UserPreference.java index 81034de947..89f8ea1a36 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/domain/UserPreference.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/domain/UserPreference.java @@ -1,4 +1,4 @@ -package com.baeldung.domain; +package com.baeldung.themes.domain; import javax.persistence.Entity; import javax.persistence.Id; diff --git a/spring-mvc-views/src/main/java/com/baeldung/repository/UserPreferenceRepository.java b/spring-mvc-views/src/main/java/com/baeldung/themes/repository/UserPreferenceRepository.java similarity index 66% rename from spring-mvc-views/src/main/java/com/baeldung/repository/UserPreferenceRepository.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/repository/UserPreferenceRepository.java index 77e5da0498..d4e4ff0a5e 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/repository/UserPreferenceRepository.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/repository/UserPreferenceRepository.java @@ -1,6 +1,6 @@ -package com.baeldung.repository; +package com.baeldung.themes.repository; -import com.baeldung.domain.UserPreference; +import com.baeldung.themes.domain.UserPreference; import org.springframework.data.repository.PagingAndSortingRepository; public interface UserPreferenceRepository extends PagingAndSortingRepository { diff --git a/spring-mvc-views/src/main/java/com/baeldung/theme/resolver/UserPreferenceThemeResolver.java b/spring-mvc-views/src/main/java/com/baeldung/themes/resolver/UserPreferenceThemeResolver.java similarity index 95% rename from spring-mvc-views/src/main/java/com/baeldung/theme/resolver/UserPreferenceThemeResolver.java rename to spring-mvc-views/src/main/java/com/baeldung/themes/resolver/UserPreferenceThemeResolver.java index 4c59734d41..ff160110fd 100644 --- a/spring-mvc-views/src/main/java/com/baeldung/theme/resolver/UserPreferenceThemeResolver.java +++ b/spring-mvc-views/src/main/java/com/baeldung/themes/resolver/UserPreferenceThemeResolver.java @@ -1,7 +1,7 @@ -package com.baeldung.theme.resolver; +package com.baeldung.themes.resolver; -import com.baeldung.domain.UserPreference; -import com.baeldung.repository.UserPreferenceRepository; +import com.baeldung.themes.domain.UserPreference; +import com.baeldung.themes.repository.UserPreferenceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; diff --git a/spring-roo/pom.xml b/spring-roo/pom.xml index 456642b1f0..448574ed19 100644 --- a/spring-roo/pom.xml +++ b/spring-roo/pom.xml @@ -413,7 +413,7 @@ spring-roo-repository Spring Roo Repository - http://repo.spring.io/spring-roo + https://repo.spring.io/spring-roo diff --git a/spring-scheduling/pom.xml b/spring-scheduling/pom.xml index a337de39b7..8726fea438 100644 --- a/spring-scheduling/pom.xml +++ b/spring-scheduling/pom.xml @@ -5,7 +5,7 @@ spring-scheduling 0.1-SNAPSHOT spring-scheduling - war + jar com.baeldung diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml new file mode 100644 index 0000000000..168fab85c0 --- /dev/null +++ b/spring-security-modules/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + spring-security-modules + 0.0.1-SNAPSHOT + spring-security-modules + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + spring-security-acl + spring-security-angular/server + spring-security-cache-control + spring-security-core + spring-security-cors + spring-security-kerberos + spring-security-mvc + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth + spring-security-mvc-jsonview + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc-socket + spring-security-oidc + + + spring-security-rest + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-sso + spring-security-stormpath + spring-security-thymeleaf + spring-security-x509 + + + diff --git a/spring-security-modules/spring-security-cors/pom.xml b/spring-security-modules/spring-security-cors/pom.xml index 91e8f5adb6..2acb99368f 100644 --- a/spring-security-modules/spring-security-cors/pom.xml +++ b/spring-security-modules/spring-security-cors/pom.xml @@ -3,15 +3,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-security-cors - 0.0.1-SNAPSHOT spring-security-cors jar Spring Security CORS com.baeldung - parent-modules - 1.0.0-SNAPSHOT + spring-security-modules + 0.0.1-SNAPSHOT diff --git a/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerTest.java b/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerUnitTest.java similarity index 97% rename from spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerTest.java rename to spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerUnitTest.java index a471eb922f..7567573040 100644 --- a/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerTest.java +++ b/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerUnitTest.java @@ -18,7 +18,7 @@ import com.baeldung.springbootsecuritycors.basicauth.SpringBootSecurityApplicati @RunWith(SpringRunner.class) @SpringBootTest(classes = { SpringBootSecurityApplication.class }) -public class ResourceControllerTest { +public class ResourceControllerUnitTest { private MockMvc mockMvc; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/SecurityWebApplicationInitializer.java b/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/SecurityWebApplicationInitializer.java new file mode 100644 index 0000000000..33978962bb --- /dev/null +++ b/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/SecurityWebApplicationInitializer.java @@ -0,0 +1,10 @@ +package org.baeldung.security; + +import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; + +public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { + + public SecurityWebApplicationInitializer() { + super(SecurityJavaConfig.class); + } +} diff --git a/spring-security-sso/spring-security-sso-auth-server/README.md b/spring-security-sso/spring-security-sso-auth-server/README.md deleted file mode 100644 index 845fb50a93..0000000000 --- a/spring-security-sso/spring-security-sso-auth-server/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles - -- [Simple Single Sign-On with Spring Security OAuth2](https://www.baeldung.com/sso-spring-security-oauth2) diff --git a/spring-security-sso/spring-security-sso-ui-2/README.md b/spring-security-sso/spring-security-sso-ui-2/README.md deleted file mode 100644 index aed217bdf0..0000000000 --- a/spring-security-sso/spring-security-sso-ui-2/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Simple Single Sign-On with Spring Security OAuth2](https://www.baeldung.com/sso-spring-security-oauth2) diff --git a/spring-security-sso/spring-security-sso-ui/README.md b/spring-security-sso/spring-security-sso-ui/README.md deleted file mode 100644 index 845fb50a93..0000000000 --- a/spring-security-sso/spring-security-sso-ui/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles - -- [Simple Single Sign-On with Spring Security OAuth2](https://www.baeldung.com/sso-spring-security-oauth2) diff --git a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java new file mode 100644 index 0000000000..ed50732183 --- /dev/null +++ b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.mockito; + +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; + +import java.util.List; + +public class MockitoAnnotationsUninitializedUnitTest { + + @Mock + List mockedList; + + @Test(expected = NullPointerException.class) + public void whenMockitoAnnotationsUninitialized_thenNPEThrown() { + Mockito.when(mockedList.size()).thenReturn(1); + } +} diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jmockit/LoginControllerIntegrationTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jmockit/LoginControllerIntegrationTest.java index 4dbe94991f..df3eeccca2 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jmockit/LoginControllerIntegrationTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jmockit/LoginControllerIntegrationTest.java @@ -130,30 +130,33 @@ public class LoginControllerIntegrationTest { }; } + @Test public void partialMocking() { - // use partial mock - final LoginService partialLoginService = new LoginService(); + LoginService partialLoginService = new LoginService(); partialLoginService.setLoginDao(loginDao); loginController.loginService = partialLoginService; - final UserForm userForm = new UserForm(); + UserForm userForm = new UserForm(); userForm.username = "foo"; - // let service's login use implementation so let's mock DAO call - new Expectations() {{ - loginDao.login(userForm); - result = 1; - // no expectation for loginService.login + + new Expectations(partialLoginService) {{ + // let's mock DAO call + loginDao.login(userForm); result = 1; + + // no expectation for login method so that real implementation is used + + // mock setCurrentUser call partialLoginService.setCurrentUser("foo"); }}; String login = loginController.login(userForm); Assert.assertEquals("OK", login); - // verify mocked call - new FullVerifications(partialLoginService) { - }; - new FullVerifications(loginDao) { - }; + // verify mocked call + new Verifications() {{ + partialLoginService.setCurrentUser("foo"); + }}; + } } diff --git a/testing-modules/testing-libraries/src/main/java/com/baeldung/cucumberhooks/books/Book.java b/testing-modules/testing-libraries/src/main/java/com/baeldung/cucumberhooks/books/Book.java new file mode 100644 index 0000000000..dc8f1dcf64 --- /dev/null +++ b/testing-modules/testing-libraries/src/main/java/com/baeldung/cucumberhooks/books/Book.java @@ -0,0 +1,35 @@ +package com.baeldung.cucumberhooks.books; + +public class Book { + + private String title; + private String author; + + public Book(String title, String author) { + this.title = title; + this.author = author; + } + + public Book() {} + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + @Override + public String toString() { + return "Book [title=" + title + ", author=" + author + "]"; + } +} diff --git a/testing-modules/testing-libraries/src/main/java/com/baeldung/cucumberhooks/books/BookStore.java b/testing-modules/testing-libraries/src/main/java/com/baeldung/cucumberhooks/books/BookStore.java new file mode 100644 index 0000000000..cc4e42d28f --- /dev/null +++ b/testing-modules/testing-libraries/src/main/java/com/baeldung/cucumberhooks/books/BookStore.java @@ -0,0 +1,28 @@ +package com.baeldung.cucumberhooks.books; + +import java.util.*; +import java.util.stream.Collectors; + +public class BookStore { + private List books = new ArrayList<>(); + + public void addBook(Book book) { + books.add(book); + } + + public void addAllBooks(Collection books) { + this.books.addAll(books); + } + + public List booksByAuthor(String author) { + return books.stream() + .filter(book -> Objects.equals(author, book.getAuthor())) + .collect(Collectors.toList()); + } + + public Optional bookByTitle(String title) { + return books.stream() + .filter(book -> book.getTitle().equals(title)) + .findFirst(); + } +} diff --git a/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationTest.java b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationTest.java new file mode 100644 index 0000000000..4db8157c21 --- /dev/null +++ b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationTest.java @@ -0,0 +1,55 @@ +package com.baeldung.cucumberhooks.books; + +import io.cucumber.core.api.Scenario; +import io.cucumber.java.After; +import io.cucumber.java.AfterStep; +import io.cucumber.java.Before; +import io.cucumber.java.BeforeStep; +import io.cucumber.java8.En; +import io.cucumber.junit.Cucumber; +import io.cucumber.junit.CucumberOptions; +import org.junit.runner.RunWith; + +@RunWith(Cucumber.class) +@CucumberOptions(features = "classpath:features/book-store-with-hooks.feature", + glue = "com.baeldung.cucumberhooks.books" +) +public class BookStoreWithHooksIntegrationTest implements En { + + public BookStoreWithHooksIntegrationTest() { + Before(1, () -> startBrowser()); + } + + @Before(order=2, value="@Screenshots") + public void beforeScenario(Scenario scenario) { + takeScreenshot(); + } + + @After + public void afterScenario(Scenario scenario) { + takeScreenshot(); + } + + @BeforeStep + public void beforeStep(Scenario scenario) { + takeScreenshot(); + } + + @AfterStep + public void afterStep(Scenario scenario) { + takeScreenshot(); + closeBrowser(); + } + + public void takeScreenshot() { + //code to take and save screenshot + } + + public void startBrowser() { + //code to open browser + } + + public void closeBrowser() { + //code to close browser + } +} diff --git a/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksRunSteps.java b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksRunSteps.java new file mode 100644 index 0000000000..8ebda5ffa4 --- /dev/null +++ b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksRunSteps.java @@ -0,0 +1,44 @@ +package com.baeldung.cucumberhooks.books; + +import io.cucumber.datatable.DataTable; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; +import io.cucumber.java8.En; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class BookStoreWithHooksRunSteps implements En { + + private BookStore store; + private List foundBooks; + private Book foundBook; + + public BookStoreWithHooksRunSteps() { + store = new BookStore(); + foundBooks = new ArrayList<>(); + } + + @Given("^The following books are available in the store$") + public void haveBooksInTheStore(DataTable table) { + List> rows = table.asLists(String.class); + + for (List columns: rows) { + store.addBook(new Book(columns.get(0), columns.get(1))); + } + } + + @When("^I ask for a book by the author (.+)$") + public void searchForBooksByAuthor(String author) { + foundBooks = store.booksByAuthor(author); + } + + @Then("^The salesperson says that there are (\\d+) books$") + public void findBooks(int count) { + assertEquals(count, foundBooks.size()); + } + +} diff --git a/testing-modules/testing-libraries/src/test/resources/features/book-store-with-hooks.feature b/testing-modules/testing-libraries/src/test/resources/features/book-store-with-hooks.feature new file mode 100644 index 0000000000..78e136d68d --- /dev/null +++ b/testing-modules/testing-libraries/src/test/resources/features/book-store-with-hooks.feature @@ -0,0 +1,17 @@ +Feature: Book Store With Hooks + Background: The Book Store + Given The following books are available in the store + | The Devil in the White City | Erik Larson | + | The Lion, the Witch and the Wardrobe | C.S. Lewis | + | In the Garden of Beasts | Erik Larson | + + @Screenshots + Scenario: 1 - Find books by author + When I ask for a book by the author Erik Larson + Then The salesperson says that there are 2 books + + Scenario: 2 - Find books by author, but isn't there + When I ask for a book by the author Marcel Proust + Then The salesperson says that there are 0 books + +