diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md index 23a10258a3..00b785c1b2 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -15,5 +15,4 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Creating a Triangle with for Loops in Java](https://www.baeldung.com/java-print-triangle) - [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency) - [The K-Means Clustering Algorithm in Java](https://www.baeldung.com/java-k-means-clustering-algorithm) -- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation) - More articles: [[<-- prev]](/algorithms-miscellaneous-2) [[next -->]](/algorithms-miscellaneous-4) diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/GreedyAlgorithm.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/GreedyAlgorithm.java index d32ffb01b9..51f0e3fa6a 100644 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/GreedyAlgorithm.java +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/GreedyAlgorithm.java @@ -15,7 +15,7 @@ public class GreedyAlgorithm { this.fp = new FollowersPath(); } - public long findMostFollowersPath(String account) throws Exception { + public long findMostFollowersPath(String account) { long max = 0; SocialUser toFollow = null; @@ -31,12 +31,8 @@ public class GreedyAlgorithm { if (currentLevel < maxLevel - 1) { currentLevel++; max += findMostFollowersPath(toFollow.getUsername()); - //fp.addFollower(toFollow.getUsername(), max); - //fp.addCount(max); return max; } else { - //fp.addFollower(toFollow.getUsername(), max); - //fp.addCount(max); return max; } } diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/NonGreedyAlgorithm.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/NonGreedyAlgorithm.java index cb3d69a18e..af274a385e 100644 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/NonGreedyAlgorithm.java +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/NonGreedyAlgorithm.java @@ -13,9 +13,8 @@ public class NonGreedyAlgorithm { this.tc = tc; this.currentLevel = level; } - - - public long findMostFollowersPath(String account) throws Exception { + + public long findMostFollowersPath(String account) { List followers = tc.getFollowers(account); long total = currentLevel > 0 ? followers.size() : 0; diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/SocialConnector.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/SocialConnector.java index b8bbbdcfff..508e18c105 100644 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/SocialConnector.java +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/greedy/SocialConnector.java @@ -20,9 +20,9 @@ public class SocialConnector { return this.isCounterEnabled; } - public List getFollowers(String account) throws Exception { + public List getFollowers(String account) { if (counter < 0) - throw new Exception ("API limit reached"); + throw new IllegalStateException ("API limit reached"); else { if(this.isCounterEnabled) counter--; for(SocialUser user : users) { 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/greedy/GreedyAlgorithmUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java index 173e3f8de5..a503b006de 100644 --- a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java @@ -35,21 +35,21 @@ public class GreedyAlgorithmUnitTest { } @Test - public void greedyAlgorithmTest() throws Exception { + public void greedyAlgorithmTest() { GreedyAlgorithm ga = new GreedyAlgorithm(prepareNetwork()); assertEquals(ga.findMostFollowersPath("root"), 5); } @Test - public void nongreedyAlgorithmTest() throws Exception { + public void nongreedyAlgorithmTest() { NonGreedyAlgorithm nga = new NonGreedyAlgorithm(prepareNetwork(), 0); - Assertions.assertThrows(Exception.class, () -> { + Assertions.assertThrows(IllegalStateException.class, () -> { nga.findMostFollowersPath("root"); }); } @Test - public void nongreedyAlgorithmUnboundedTest() throws Exception { + public void nongreedyAlgorithmUnboundedTest() { SocialConnector sc = prepareNetwork(); sc.switchCounter(); NonGreedyAlgorithm nga = new NonGreedyAlgorithm(sc, 0); 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-searching/README.md b/algorithms-searching/README.md index d86c3e3de8..9b85995235 100644 --- a/algorithms-searching/README.md +++ b/algorithms-searching/README.md @@ -9,3 +9,4 @@ This module contains articles about searching algorithms. - [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search) - [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms) - [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search) +- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search) 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-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/README.md b/apache-rocketmq/README.md new file mode 100644 index 0000000000..be53f95790 --- /dev/null +++ b/apache-rocketmq/README.md @@ -0,0 +1,5 @@ +## Apache RocketMQ + +This module contains articles about Apache RocketMQ + +### Relevant Articles: diff --git a/apache-rocketmq/pom.xml b/apache-rocketmq/pom.xml new file mode 100644 index 0000000000..59c204dddf --- /dev/null +++ b/apache-rocketmq/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + apache-rocketmq + 1.0-SNAPSHOT + apache-rocketmq + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.rocketmq + rocketmq-spring-boot-starter + 2.0.4 + + + + + 1.6.0 + + diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java new file mode 100644 index 0000000000..06e88076d0 --- /dev/null +++ b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java @@ -0,0 +1,34 @@ +package com.baeldung.rocketmq.consumer; + +import com.baeldung.rocketmq.event.CartItemEvent; +import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; +import org.apache.rocketmq.spring.core.RocketMQListener; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.stereotype.Service; + +@SpringBootApplication +public class CartEventConsumer { + + public static void main(String[] args) { + SpringApplication.run(CartEventConsumer.class, args); + } + + @Service + @RocketMQMessageListener(topic = "cart-item-add-topic", consumerGroup = "cart-consumer_cart-item-add-topic") + public class CardItemAddConsumer implements RocketMQListener { + public void onMessage(CartItemEvent addItemEvent) { + System.out.println("Adding item: " + addItemEvent); + // logic + } + } + + @Service + @RocketMQMessageListener(topic = "cart-item-removed-topic", consumerGroup = "cart-consumer_cart-item-removed-topic") + public class CardItemRemoveConsumer implements RocketMQListener { + public void onMessage(CartItemEvent removeItemEvent) { + System.out.println("Removing item: " + removeItemEvent); + // logic + } + } +} diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java new file mode 100644 index 0000000000..a9d7b4a436 --- /dev/null +++ b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java @@ -0,0 +1,32 @@ +package com.baeldung.rocketmq.event; + +public class CartItemEvent { + private String itemId; + private int quantity; + + public CartItemEvent(String itemId, int quantity) { + this.itemId = itemId; + this.quantity = quantity; + } + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + @Override + public String toString() { + return "CartItemEvent{" + "itemId='" + itemId + '\'' + ", quantity=" + quantity + '}'; + } +} diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java new file mode 100644 index 0000000000..dba6ee7a46 --- /dev/null +++ b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java @@ -0,0 +1,26 @@ +package com.baeldung.rocketmq.producer; + + +import com.baeldung.rocketmq.event.CartItemEvent; +import org.apache.rocketmq.spring.core.RocketMQTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CartEventProducer implements CommandLineRunner { + + @Autowired + private RocketMQTemplate rocketMQTemplate; + + public static void main(String[] args) { + SpringApplication.run(CartEventProducer.class, args); + } + + public void run(String... args) throws Exception { + rocketMQTemplate.convertAndSend("cart-item-add-topic", new CartItemEvent("bike", 1)); + rocketMQTemplate.convertAndSend("cart-item-add-topic", new CartItemEvent("computer", 2)); + rocketMQTemplate.convertAndSend("cart-item-removed-topic", new CartItemEvent("bike", 1)); + } +} diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java new file mode 100644 index 0000000000..e5fa6e361a --- /dev/null +++ b/apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java @@ -0,0 +1,21 @@ +package com.baeldung.rocketmq.transaction; + +import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener; +import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener; +import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState; +import org.springframework.messaging.Message; + +@RocketMQTransactionListener(txProducerGroup = "test-transaction") +class TransactionListenerImpl implements RocketMQLocalTransactionListener { + @Override + public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) { + // ... local transaction process, return ROLLBACK, COMMIT or UNKNOWN + return RocketMQLocalTransactionState.UNKNOWN; + } + + @Override + public RocketMQLocalTransactionState checkLocalTransaction(Message msg) { + // ... check transaction status and return ROLLBACK, COMMIT or UNKNOWN + return RocketMQLocalTransactionState.COMMIT; + } +} diff --git a/apache-rocketmq/src/main/resources/application.properties b/apache-rocketmq/src/main/resources/application.properties new file mode 100644 index 0000000000..68d4ceaacd --- /dev/null +++ b/apache-rocketmq/src/main/resources/application.properties @@ -0,0 +1,9 @@ +rocketmq.name-server=127.0.0.1:9876 +rocketmq.producer.group=my-group +rocketmq.producer.send-message-timeout=300000 +rocketmq.producer.compress-message-body-threshold=4096 +rocketmq.producer.max-message-size=4194304 +rocketmq.producer.retry-times-when-send-async-failed=0 +rocketmq.producer.retry-next-server=true +rocketmq.producer.retry-times-when-send-failed=2 + diff --git a/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy b/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy index 65591cae8d..0612ecb955 100644 --- a/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy +++ b/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy @@ -2,10 +2,13 @@ package com.baeldung.metaprogramming.extension import com.baeldung.metaprogramming.Employee +import java.time.LocalDate +import java.time.Year + class BasicExtensions { static int getYearOfBirth(Employee self) { - return (new Date().getYear() + 1900) - self.age; + return Year.now().value - self.age } static String capitalize(String self) { diff --git a/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy index f489426700..4a8631eb95 100644 --- a/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy +++ b/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy @@ -1,6 +1,9 @@ package com.baeldung.metaprogramming -import groovy.time.TimeCategory + +import java.time.LocalDate +import java.time.Period +import java.time.Year class MetaprogrammingUnitTest extends GroovyTestCase { @@ -51,15 +54,17 @@ class MetaprogrammingUnitTest extends GroovyTestCase { void testJavaMetaClass() { String.metaClass.capitalize = { String str -> - str.substring(0, 1).toUpperCase() + str.substring(1); + str.substring(0, 1).toUpperCase() + str.substring(1) } assert "norman".capitalize() == "Norman" } -// void testEmployeeExtension() { -// Employee emp = new Employee(age: 28) -// assert emp.getYearOfBirth() == 1991 -// } + void testEmployeeExtension() { + def age = 28 + def expectedYearOfBirth = Year.now() - age + Employee emp = new Employee(age: age) + assert emp.getYearOfBirth() == expectedYearOfBirth.value + } void testJavaClassesExtensions() { 5.printCounter() @@ -115,4 +120,4 @@ class MetaprogrammingUnitTest extends GroovyTestCase { Employee employee = new Employee(1, "Norman", "Lewis", 28) employee.logEmp() } -} \ No newline at end of file +} 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 80ad7ef9b1..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 @@ -75,6 +75,7 @@ class WebserviceManualTest 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 WebserviceManualTest 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 WebserviceManualTest extends GroovyTestCase { assert e?.response?.statusCode != 200 } } -} \ No newline at end of file +} diff --git a/core-java-lambdas/README.md b/core-java-lambdas/README.md deleted file mode 100644 index 5b94953e68..0000000000 --- a/core-java-lambdas/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Java 9 java.lang.Module API](https://www.baeldung.com/java-lambda-effectively-final-local-variables) diff --git a/core-java-modules/core-java-14/pom.xml b/core-java-modules/core-java-14/pom.xml new file mode 100644 index 0000000000..48ec627416 --- /dev/null +++ b/core-java-modules/core-java-14/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + com.baeldung + core-java-14 + 1.0.0-SNAPSHOT + core-java-14 + jar + http://maven.apache.org + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source.version} + ${maven.compiler.target.version} + + + --enable-preview + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M3 + + --enable-preview + + + + + + + 14 + 14 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/serial/MySerialClass.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/serial/MySerialClass.java new file mode 100644 index 0000000000..6a013d7b59 --- /dev/null +++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/serial/MySerialClass.java @@ -0,0 +1,50 @@ +package com.baeldung.serial; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamException; +import java.io.ObjectStreamField; +import java.io.Serial; +import java.io.Serializable; + +/** + * Class showcasing the usage of the Java 14 @Serial annotation. + * + * @author Donato Rimenti + */ +public class MySerialClass implements Serializable { + + @Serial + private static final ObjectStreamField[] serialPersistentFields = null; + + @Serial + private static final long serialVersionUID = 1; + + @Serial + private void writeObject(ObjectOutputStream stream) throws IOException { + // ... + } + + @Serial + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + // ... + } + + @Serial + private void readObjectNoData() throws ObjectStreamException { + // ... + } + + @Serial + private Object writeReplace() throws ObjectStreamException { + // ... + return null; + } + + @Serial + private Object readResolve() throws ObjectStreamException { + // ... + return null; + } +} \ 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 3f6b7094bb..532f0a6144 100644 --- a/core-java-modules/core-java-arrays-2/pom.xml +++ b/core-java-modules/core-java-arrays-2/pom.xml @@ -19,6 +19,16 @@ org.apache.commons commons-lang3 ${commons-lang3.version} + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} @@ -37,9 +47,34 @@ true + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.0 + + + package + + shade + + + benchmarks + + + org.openjdk.jmh.Main + + + + + + + + 1.19 3.9 diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java new file mode 100644 index 0000000000..640d729020 --- /dev/null +++ b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java @@ -0,0 +1,72 @@ +package com.baeldung.arraysort; + +import java.util.Arrays; +import java.util.Random; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +@BenchmarkMode(Mode.AverageTime) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +@Fork(2) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +public class ArraySortingBenchmark { + + @State(Scope.Benchmark) + public static class ArrayContainer { + + @Param({ "1000", "10000", "100000", "1000000" }) + int arraySize; + + // initial unsorted array + int[] unsortedArray; + + //cloned array to sort + int[] arrayToSort; + + @Setup(Level.Trial) + public void createUnSortedArray() { + unsortedArray = new int[arraySize]; + for (int i = 0; i < arraySize; i++) { + unsortedArray[i] = new Random().nextInt(1000); + } + } + + @Setup(Level.Invocation) + public void createUnSortedArrayCopy() { + arrayToSort = unsortedArray.clone(); + } + + int[] getArrayToSort() { + return arrayToSort; + } + } + + @Benchmark + public void benchmark_arrays_parallel_sort(ArrayContainer d, Blackhole b) { + int[] arr = d.getArrayToSort(); + Arrays.parallelSort(arr); + b.consume(arr); + } + + @Benchmark + public void benchmark_arrays_sort(ArrayContainer d, Blackhole b) { + int[] arr = d.getArrayToSort(); + Arrays.sort(arr); + b.consume(arr); + } + +} diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/duplicatescounter/DuplicatesCounter.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/duplicatescounter/DuplicatesCounter.java index b5138eed7d..e0c0b723e0 100644 --- a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/duplicatescounter/DuplicatesCounter.java +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/duplicatescounter/DuplicatesCounter.java @@ -24,11 +24,21 @@ public class DuplicatesCounter { return resultMap; } - public static Map countByClassicalLoopWithMapCompute(List inputList) { + public static Map countByForEachLoopWithGetOrDefault(List inputList) { Map resultMap = new HashMap<>(); - for (T element : inputList) { - resultMap.compute(element, (k, v) -> v == null ? 1 : v + 1); - } + inputList.forEach(e -> resultMap.put(e, resultMap.getOrDefault(e, 0L) + 1L)); + return resultMap; + } + + public static Map countByForEachLoopWithMapCompute(List inputList) { + Map resultMap = new HashMap<>(); + inputList.forEach(e -> resultMap.compute(e, (k, v) -> v == null ? 1L : v + 1L)); + return resultMap; + } + + public static Map countByForEachLoopWithMapMerge(List inputList) { + Map resultMap = new HashMap<>(); + inputList.forEach(e -> resultMap.merge(e, 1L, Long::sum)); return resultMap; } diff --git a/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/duplicatescounter/DuplicatesCounterUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/duplicatescounter/DuplicatesCounterUnitTest.java index be9ccded9b..8d6825c590 100644 --- a/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/duplicatescounter/DuplicatesCounterUnitTest.java +++ b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/duplicatescounter/DuplicatesCounterUnitTest.java @@ -11,7 +11,6 @@ import static org.assertj.core.data.MapEntry.entry; class DuplicatesCounterUnitTest { - private static List INPUT_LIST = Lists.list( "expect1", "expect2", "expect2", @@ -24,10 +23,21 @@ class DuplicatesCounterUnitTest { verifyResult(result); } + @Test + void givenInput_whenCountByForEachLoopWithGetOrDefault_thenGetResultMap() { + Map result = DuplicatesCounter.countByForEachLoopWithGetOrDefault(INPUT_LIST); + verifyResult(result); + } @Test - void givenInput_whenCountByClassicalLoopWithMapCompute_thenGetResultMap() { - Map result = DuplicatesCounter.countByClassicalLoopWithMapCompute(INPUT_LIST); + void givenInput_whenCountByForEachLoopWithMapCompute_thenGetResultMap() { + Map result = DuplicatesCounter.countByForEachLoopWithMapCompute(INPUT_LIST); + verifyResult(result); + } + + @Test + void givenInput_whenCountByForEachLoopWithMapMerge_thenGetResultMap() { + Map result = DuplicatesCounter.countByForEachLoopWithMapMerge(INPUT_LIST); verifyResult(result); } diff --git a/core-java-modules/core-java-concurrency-advanced-3/pom.xml b/core-java-modules/core-java-concurrency-advanced-3/pom.xml index df9834181f..8f275f4043 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-3/pom.xml @@ -23,6 +23,37 @@ ${assertj.version} test + + + com.jcabi + jcabi-aspects + ${jcabi-aspects.version} + + + + org.aspectj + aspectjrt + ${aspectjrt.version} + runtime + + + + com.google.guava + guava + ${guava.version} + + + + org.cactoos + cactoos + ${cactoos.version} + + + + com.ea.async + ea-async + ${ea-async.version} + @@ -36,6 +67,30 @@ ${maven.compiler.target} + + com.jcabi + jcabi-maven-plugin + ${jcabi-maven-plugin.version} + + + + ajc + + + + + + org.aspectj + aspectjtools + ${aspectjtools.version} + + + org.aspectj + aspectjweaver + ${aspectjweaver.version} + + + @@ -49,6 +104,14 @@ 3.14.0 1.8 1.8 + 0.22.6 + 1.9.5 + 28.2-jre + 0.43 + 1.2.3 + 0.14.1 + 1.9.1 + 1.9.1 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-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 85% 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 ae8d21c29c..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,55 +1,65 @@ -package com.baeldung.date.comparison; - -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.ZoneId; -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 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 90% 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 db55aadcca..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,53 +1,57 @@ -package com.baeldung.date.comparison; - -import org.junit.Test; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Date; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -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.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.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 73% 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 index 8711455265..9bc2a17f28 100644 --- 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 @@ -9,12 +9,6 @@ import static org.junit.Assert.assertEquals; public class DateUtilsUnitTest { - @Test - public void givenTimeMillis_thenDateIsReturned() { - Date now = DateUtils.getNow(); - assertEquals(DateUtils.getDate(now.getTime()), now); - } - @Test public void givenDateAndPattern_thenDateIsCorrectlyReturned() throws ParseException { long milliseconds = new Date(2020 - 1900, 0, 1).getTime(); 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 80% 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 index 945086c86f..9ccaa9a845 100644 --- 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 @@ -9,11 +9,6 @@ import org.junit.Test; public class DateUtilsUnitTest { - @Test - public void givenCurrentDate_thenTodayIsReturned() { - assertEquals(DateUtils.getNow().toLocalDate(), LocalDate.now()); - } - @Test(expected = IllegalArgumentException.class) public void givenDateAsString_whenPatternIsNotRespected_thenExceptionIsThrown() { DateUtils.getDate("2020 01 01"); 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 73% 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 index 2faf8fab0e..836d0d55e7 100644 --- 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 @@ -1,22 +1,13 @@ package com.baeldung.datetime.sql; -import static org.junit.Assert.assertEquals; - import org.junit.Test; -import com.baeldung.datetime.sql.TimestampUtils; - import java.text.ParseException; -import java.util.Date; + +import static org.junit.Assert.assertEquals; public class TimestampUtilsUnitTest { - @Test - public void givenCurrentTimestamp_thenNowIsReturned() { - assertEquals(TimestampUtils.getNow() - .getTime(), new Date().getTime()); - } - @Test(expected = IllegalArgumentException.class) public void givenTimestampAsString_whenPatternIsNotRespected_thenExceptionIsThrown() { TimestampUtils.getTimestamp("2020/01/01 10:11-12"); 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/src/main/java/com/baeldung/datebasics/CreateDate.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datebasics/CreateDate.java new file mode 100644 index 0000000000..327827e03a --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datebasics/CreateDate.java @@ -0,0 +1,45 @@ +package com.baeldung.datebasics; + +import java.time.Clock; +import java.time.LocalDate; +import java.time.Month; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; + +public class CreateDate { + public LocalDate getTodaysDate() { + return LocalDate.now(); + } + + public LocalDate getTodaysDateFromClock() { + return LocalDate.now(Clock.systemDefaultZone()); + } + + public LocalDate getTodaysDateFromZone(String zone) { + return LocalDate.now(ZoneId.of(zone)); + } + + 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/src/test/java/com/baeldung/datebasics/CreateDateUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datebasics/CreateDateUnitTest.java new file mode 100644 index 0000000000..54f3285ea0 --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datebasics/CreateDateUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.datebasics; + +import static org.junit.Assert.assertEquals; + +import java.time.Month; + +import org.junit.Test; + +public class CreateDateUnitTest { + private CreateDate date = new CreateDate(); + + @Test + public void whenUsingNowMethod_thenLocalDate() { + assertEquals("2020-01-08", date.getTodaysDate()); + } + + @Test + public void whenUsingClock_thenLocalDate() { + assertEquals("2020-01-08", date.getTodaysDateFromClock()); + } + + @Test + public void givenValues_whenUsingZone_thenLocalDate() { + assertEquals("2020-01-08", date.getTodaysDateFromZone("Asia/Kolkata")); + } + + @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-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExample.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExample.java new file mode 100644 index 0000000000..bb0bad8cf4 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExample.java @@ -0,0 +1,14 @@ +package com.baeldung.finallykeyword; + +public class FinallyExample { + + public void printCount(String count) { + try { + System.out.println("The count is " + Integer.parseInt(count)); + } catch (NumberFormatException e) { + System.out.println("No count"); + } finally { + System.out.println("In finally"); + } + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExecutedCases.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExecutedCases.java new file mode 100644 index 0000000000..68a3763da0 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExecutedCases.java @@ -0,0 +1,53 @@ +package com.baeldung.finallykeyword; + +public class FinallyExecutedCases { + + public void noExceptionFinally() { + try { + System.out.println("Inside try"); + } finally { + System.out.println("Inside finally"); + } + } + + public void unhandledException() throws Exception { + try { + System.out.println("Inside try"); + throw new Exception(); + } finally { + System.out.println("Inside finally"); + } + } + + public void handledException() { + try { + System.out.println("Inside try"); + throw new Exception(); + } catch (Exception e) { + System.out.println("Inside catch"); + } finally { + System.out.println("Inside finally"); + } + } + + public String returnFromTry() { + try { + System.out.println("Inside try"); + return "from try"; + } finally { + System.out.println("Inside finally"); + } + } + + public String returnFromCatch() { + try { + System.out.println("Inside try"); + throw new Exception(); + } catch (Exception e) { + System.out.println("Inside catch"); + return "from catch"; + } finally { + System.out.println("Inside finally"); + } + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyNotExecutedCases.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyNotExecutedCases.java new file mode 100644 index 0000000000..92c0ea729d --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyNotExecutedCases.java @@ -0,0 +1,54 @@ +package com.baeldung.finallykeyword; + +public class FinallyNotExecutedCases { + + public void callingSystemExit() { + try { + System.out.println("Inside try"); + System.exit(1); + } finally { + System.out.println("Inside finally"); + } + } + + public void callingRuntimeHalt() { + try { + System.out.println("Inside try"); + Runtime.getRuntime() + .halt(1); + } finally { + System.out.println("Inside finally"); + } + } + + public void infiniteLoop() { + try { + System.out.println("Inside try"); + while (true) { + } + } finally { + System.out.println("Inside finally"); + } + } + + public void daemonThread() throws InterruptedException { + Runnable runnable = () -> { + try { + System.out.println("Inside try"); + } finally { + try { + Thread.sleep(1000); + System.out.println("Inside finally"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }; + Thread regular = new Thread(runnable); + Thread daemon = new Thread(runnable); + daemon.setDaemon(true); + regular.start(); + Thread.sleep(300); + daemon.start(); + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinally.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinally.java new file mode 100644 index 0000000000..f1a56441f2 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinally.java @@ -0,0 +1,33 @@ +package com.baeldung.finallykeyword; + +public class PitfallsWhenUsingFinally { + + public String disregardsUnCaughtException() { + try { + System.out.println("Inside try"); + throw new RuntimeException(); + } finally { + System.out.println("Inside finally"); + return "from finally"; + } + } + + public String ignoringOtherReturns() { + try { + System.out.println("Inside try"); + return "from try"; + } finally { + System.out.println("Inside finally"); + return "from finally"; + } + } + + public String throwsException() { + try { + System.out.println("Inside try"); + return "from try"; + } finally { + throw new RuntimeException(); + } + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Coordinates.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Coordinates.java new file mode 100644 index 0000000000..4a292b9b18 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Coordinates.java @@ -0,0 +1,49 @@ +package com.baeldung.methodmultiplereturnvalues; + +public class Coordinates { + + private double longitude; + private double latitude; + private String placeName; + + public Coordinates() {} + + public Coordinates(double longitude, double latitude, String placeName) { + this.longitude = longitude; + this.latitude = latitude; + this.placeName = placeName; + } + + public double calculateDistance(Coordinates c) { + + double s1 = Math.abs(this.longitude - c.longitude); + double s2 = Math.abs(this.latitude - c.latitude); + + return Math.hypot(s1, s2); + } + + public double getLongitude() { + return longitude; + } + + public void setLongitude(double longitude) { + this.longitude = longitude; + } + + public double getLatitude() { + return latitude; + } + + public void setLatitude(double latitude) { + this.latitude = latitude; + } + + public String getPlaceName() { + return placeName; + } + + public void setPlaceName(String placeName) { + this.placeName = placeName; + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArrays.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArrays.java new file mode 100644 index 0000000000..9763422618 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArrays.java @@ -0,0 +1,27 @@ +package com.baeldung.methodmultiplereturnvalues; + +class MultipleReturnValuesUsingArrays { + + + static double[] getCoordinatesDoubleArray() { + + double[] coordinates = new double[2]; + + coordinates[0] = 10; + coordinates[1] = 12.5; + + return coordinates; + } + + + static Number[] getCoordinatesNumberArray() { + + Number[] coordinates = new Number[2]; + + coordinates[0] = 10; //Integer + coordinates[1] = 12.5; //Double + + return coordinates; + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollections.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollections.java new file mode 100644 index 0000000000..ccd5a4b74e --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollections.java @@ -0,0 +1,30 @@ +package com.baeldung.methodmultiplereturnvalues; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +class MultipleReturnValuesUsingCollections { + + static List getCoordinatesList() { + + List coordinates = new ArrayList<>(); + + coordinates.add(10); + coordinates.add(12.5); + + return coordinates; + } + + static Map getCoordinatesMap() { + + Map coordinates = new HashMap<>(); + + coordinates.put("longitude", 10); + coordinates.put("latitude", 12.5); + + return coordinates; + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainer.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainer.java new file mode 100644 index 0000000000..617f0df17c --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainer.java @@ -0,0 +1,14 @@ +package com.baeldung.methodmultiplereturnvalues; + +class MultipleReturnValuesUsingContainer { + + static Coordinates getCoordinates() { + + double longitude = 10; + double latitude = 12.5; + String placeName = "home"; + + return new Coordinates(longitude, latitude, placeName); + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuples.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuples.java new file mode 100644 index 0000000000..59984f777e --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuples.java @@ -0,0 +1,17 @@ +package com.baeldung.methodmultiplereturnvalues; + +import java.util.List; + +class MultipleReturnValuesUsingTuples { + + static Tuple2 getMostDistantPoint(List coordinatesList, + Coordinates target) { + + return coordinatesList.stream() + .map(coor -> new Tuple2<>(coor, coor.calculateDistance(target))) + .max((d1, d2) -> Double.compare(d1.getSecond(), d2.getSecond())) + .get(); + + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Tuple2.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Tuple2.java new file mode 100644 index 0000000000..57ef20d572 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Tuple2.java @@ -0,0 +1,31 @@ +package com.baeldung.methodmultiplereturnvalues; + +public class Tuple2 { + + private K first; + private V second; + + public Tuple2() {} + + public Tuple2(K first, V second) { + this.first = first; + this.second = second; + } + + public K getFirst() { + return first; + } + + public V getSecond() { + return second; + } + + public void setFirst(K first) { + this.first = first; + } + + public void setSecond(V second) { + this.second = second; + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinallyUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinallyUnitTest.java new file mode 100644 index 0000000000..7e7a7241ec --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinallyUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.finallykeyword; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class PitfallsWhenUsingFinallyUnitTest { + + PitfallsWhenUsingFinally instance = new PitfallsWhenUsingFinally(); + + @Test + public void testIgnoresException() { + String result = instance.disregardsUnCaughtException(); + assertEquals("from finally", result); + } + + @Test + public void testIgnoresOtherReturns() { + String result = instance.ignoringOtherReturns(); + assertEquals("from finally", result); + } + + @Test(expected = RuntimeException.class) + public void testThrowsException() { + instance.throwsException(); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArraysUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArraysUnitTest.java new file mode 100644 index 0000000000..0cf90a8879 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArraysUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.methodmultiplereturnvalues; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +class MultipleReturnValuesUsingArraysUnitTest { + + @Test + void whenUsingArrayOfDoubles_thenMultipleDoubleFieldsAreReturned() { + + double[] coordinates = MultipleReturnValuesUsingArrays.getCoordinatesDoubleArray(); + assertEquals(10, coordinates[0]); + assertEquals(12.5, coordinates[1]); + } + + @Test + void whenUsingArrayOfNumbers_thenMultipleNumberFieldsAreReturned() { + + Number[] coordinates = MultipleReturnValuesUsingArrays.getCoordinatesNumberArray(); + assertEquals(10, coordinates[0]); + assertEquals(12.5, coordinates[1]); + + } + +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollectionsUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollectionsUnitTest.java new file mode 100644 index 0000000000..8038601986 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollectionsUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.methodmultiplereturnvalues; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class MultipleReturnValuesUsingCollectionsUnitTest { + + @Test + void whenUsingList_thenMultipleFieldsAreReturned() { + + List coordinates = MultipleReturnValuesUsingCollections.getCoordinatesList(); + assertEquals(Integer.valueOf(10), coordinates.get(0)); + assertEquals(Double.valueOf(12.5), coordinates.get(1)); + } + + @Test + void whenUsingMap_thenMultipleFieldsAreReturned() { + + Map coordinates = MultipleReturnValuesUsingCollections.getCoordinatesMap(); + assertEquals(Integer.valueOf(10), coordinates.get("longitude")); + assertEquals(Double.valueOf(12.5), coordinates.get("latitude")); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainerUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainerUnitTest.java new file mode 100644 index 0000000000..f7fd9bd108 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainerUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.methodmultiplereturnvalues; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +class MultipleReturnValuesUsingContainerUnitTest { + + @Test + void whenUsingContainerClass_thenMultipleFieldsAreReturned() { + + Coordinates coordinates = MultipleReturnValuesUsingContainer.getCoordinates(); + + assertEquals(10, coordinates.getLongitude()); + assertEquals(12.5, coordinates.getLatitude()); + assertEquals("home", coordinates.getPlaceName()); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuplesUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuplesUnitTest.java new file mode 100644 index 0000000000..52f30286bc --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuplesUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.methodmultiplereturnvalues; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +class MultipleReturnValuesUsingTuplesUnitTest { + + @Test + void whenUsingTuple_thenMultipleFieldsAreReturned() { + + List coordinatesList = new ArrayList<>(); + coordinatesList.add(new Coordinates(1, 1, "home")); + coordinatesList.add(new Coordinates(2, 2, "school")); + coordinatesList.add(new Coordinates(3, 3, "hotel")); + + Coordinates target = new Coordinates(5, 5, "gym"); + + Tuple2 mostDistantPoint = MultipleReturnValuesUsingTuples.getMostDistantPoint(coordinatesList, target); + + assertEquals(1, mostDistantPoint.getFirst().getLongitude()); + assertEquals(1, mostDistantPoint.getFirst().getLatitude()); + assertEquals("home", mostDistantPoint.getFirst().getPlaceName()); + assertEquals(5.66, BigDecimal.valueOf(mostDistantPoint.getSecond()).setScale(2, RoundingMode.HALF_UP).doubleValue()); + + } + +} 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 new file mode 100644 index 0000000000..336276786a --- /dev/null +++ b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/powerset/PowerSetUtility.java @@ -0,0 +1,302 @@ +package com.baeldung.powerset; + +import javax.annotation.Nullable; +import java.util.AbstractSet; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +public class PowerSetUtility { + + private Map map = new HashMap<>(); + private List reverseMap = new ArrayList<>(); + + //Lazy Load PowerSet class + private static class PowerSet extends AbstractSet> { + private Map map = new HashMap<>(); + private List reverseMap = new ArrayList<>(); + private Set set; + + public PowerSet(Set set) { + this.set = set; + initializeMap(); + } + + abstract class ListIterator implements Iterator { + + protected int position = 0; + private int size; + + public ListIterator(int size) { + this.size = size; + } + + @Override + public boolean hasNext() { + return position < size; + } + } + + static class Subset extends AbstractSet { + private Map map; + private List reverseMap; + private int mask; + + public Subset(Map map, List reverseMap, int mask) { + this.map = map; + this.reverseMap = reverseMap; + this.mask = mask; + } + + @Override + public Iterator iterator() { + return new Iterator() { + int remainingSetBits = mask; + + @Override + public boolean hasNext() { + return remainingSetBits != 0; + } + + @Override + public E next() { + int index = Integer.numberOfTrailingZeros(remainingSetBits); + if (index == 32) { + throw new NoSuchElementException(); + } + remainingSetBits &= ~(1 << index); + return reverseMap.get(index); + } + }; + } + + @Override + public int size() { + return Integer.bitCount(mask); + } + + @Override + public boolean contains(@Nullable Object o) { + Integer index = map.get(o); + return index != null && (mask & (1 << index)) != 0; + } + } + + @Override + public Iterator> iterator() { + return new ListIterator>(this.size()) { + @Override + public Set next() { + return new Subset<>(map, reverseMap, position++); + } + }; + } + + @Override + public int size() { + return (1 << this.set.size()); + } + + @Override + public boolean contains(@Nullable Object obj) { + if (obj instanceof Set) { + Set set = (Set) obj; + return reverseMap.containsAll(set); + } + return false; + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof PowerSet) { + PowerSet that = (PowerSet) obj; + return set.equals(that.set);//Set equals check to have the same element regardless of the order of the items + } + return super.equals(obj); + } + + + private void initializeMap() { + int mapId = 0; + for (E c : this.set) { + map.put(c, mapId++); + reverseMap.add(c); + } + } + } + + public Set> lazyLoadPowerSet(Set set) { + return new PowerSet<>(set); + } + + public Set> recursivePowerSet(Set set) { + if (set.isEmpty()) { + Set> ret = new HashSet<>(); + ret.add(set); + return ret; + } + + T element = set.iterator().next(); + Set subSetWithoutElement = getSubSetWithoutElement(set, element); + Set> powerSetSubSetWithoutElement = recursivePowerSet(subSetWithoutElement); + + Set> powerSetSubSetWithElement = addElementToAll(powerSetSubSetWithoutElement, element); + + Set> powerSet = new HashSet<>(); + powerSet.addAll(powerSetSubSetWithoutElement); + powerSet.addAll(powerSetSubSetWithElement); + return powerSet; + } + + public Set> recursivePowerSetIndexRepresentation(Collection set) { + initializeMap(set); + Set> powerSetIndices = recursivePowerSetIndexRepresentation(0, set.size()); + return unMapIndex(powerSetIndices); + } + + private List> iterativePowerSetByLoopOverNumbers(int n) { + List> powerSet = new ArrayList<>(); + for (int i = 0; i < (1 << n); i++) { + List subset = new ArrayList<>(n); + for (int j = 0; j < n; j++) + subset.add(((1 << j) & i) > 0); + powerSet.add(subset); + } + return powerSet; + } + + private List> iterativePowerSetByLoopOverNumbersWithMinimalChange(int n) { + List> powerSet = new ArrayList<>(); + for (int i = 0; i < (1 << n); i++) { + List subset = new ArrayList<>(n); + for (int j = 0; j < n; j++) { + int grayEquivalent = i ^ (i >> 1); + subset.add(((1 << j) & grayEquivalent) > 0); + } + powerSet.add(subset); + } + return powerSet; + } + + public Set> recursivePowerSetBinaryRepresentation(Collection set) { + initializeMap(set); + Set> powerSetBoolean = recursivePowerSetBinaryRepresentation(0, set.size()); + return unMapBinary(powerSetBoolean); + } + + public List> iterativePowerSetByLoopOverNumbers(Set set) { + initializeMap(set); + List> sets = iterativePowerSetByLoopOverNumbers(set.size()); + return unMapListBinary(sets); + } + + public List> iterativePowerSetByLoopOverNumbersMinimalChange(Set set) { + initializeMap(set); + List> sets = iterativePowerSetByLoopOverNumbersWithMinimalChange(set.size()); + return unMapListBinary(sets); + } + + private Set> recursivePowerSetIndexRepresentation(int idx, int n) { + if (idx == n) { + Set> empty = new HashSet<>(); + empty.add(new HashSet<>()); + return empty; + } + Set> powerSetSubset = recursivePowerSetIndexRepresentation(idx + 1, n); + Set> powerSet = new HashSet<>(powerSetSubset); + for (Set s : powerSetSubset) { + HashSet subSetIdxInclusive = new HashSet<>(s); + subSetIdxInclusive.add(idx); + powerSet.add(subSetIdxInclusive); + } + return powerSet; + } + + private Set> recursivePowerSetBinaryRepresentation(int idx, int n) { + if (idx == n) { + Set> powerSetOfEmptySet = new HashSet<>(); + powerSetOfEmptySet.add(Arrays.asList(new Boolean[n])); + return powerSetOfEmptySet; + } + Set> powerSetSubset = recursivePowerSetBinaryRepresentation(idx + 1, n); + Set> powerSet = new HashSet<>(); + for (List s : powerSetSubset) { + List subSetIdxExclusive = new ArrayList<>(s); + subSetIdxExclusive.set(idx, false); + powerSet.add(subSetIdxExclusive); + List subSetIdxInclusive = new ArrayList<>(s); + subSetIdxInclusive.set(idx, true); + powerSet.add(subSetIdxInclusive); + } + return powerSet; + } + + private void initializeMap(Collection collection) { + int mapId = 0; + for (T c : collection) { + map.put(c, mapId++); + reverseMap.add(c); + } + } + + private Set> unMapIndex(Set> sets) { + Set> ret = new HashSet<>(); + for (Set s : sets) { + HashSet subset = new HashSet<>(); + for (Integer i : s) + subset.add(reverseMap.get(i)); + ret.add(subset); + } + return ret; + } + + private Set> unMapBinary(Collection> sets) { + Set> ret = new HashSet<>(); + for (List s : sets) { + HashSet subset = new HashSet<>(); + for (int i = 0; i < s.size(); i++) + if (s.get(i)) + subset.add(reverseMap.get(i)); + ret.add(subset); + } + return ret; + } + + private List> unMapListBinary(Collection> sets) { + List> ret = new ArrayList<>(); + for (List s : sets) { + List subset = new ArrayList<>(); + for (int i = 0; i < s.size(); i++) + if (s.get(i)) + subset.add(reverseMap.get(i)); + ret.add(subset); + } + return ret; + } + + private Set> addElementToAll(Set> powerSetSubSetWithoutElement, T element) { + Set> powerSetSubSetWithElement = new HashSet<>(); + for (Set subsetWithoutElement : powerSetSubSetWithoutElement) { + Set subsetWithElement = new HashSet<>(subsetWithoutElement); + subsetWithElement.add(element); + powerSetSubSetWithElement.add(subsetWithElement); + } + return powerSetSubSetWithElement; + } + + private Set getSubSetWithoutElement(Set set, T element) { + Set subsetWithoutElement = new HashSet<>(); + for (T s : set) { + if (!s.equals(element)) + subsetWithoutElement.add(s); + } + return subsetWithoutElement; + } +} 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 new file mode 100644 index 0000000000..8b7c338479 --- /dev/null +++ b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/powerset/PowerSetUtilityUnitTest.java @@ -0,0 +1,189 @@ +package com.baeldung.powerset; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.hamcrest.collection.IsCollectionWithSize; +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; + +public class PowerSetUtilityUnitTest { + + @Test + public void givenSet_WhenGuavaLibraryGeneratePowerSet_ThenItContainsAllSubsets() { + ImmutableSet set = ImmutableSet.of("APPLE", "ORANGE", "MANGO"); + Set> powerSet = Sets.powerSet(set); + Assertions.assertEquals((1 << set.size()), powerSet.size()); + MatcherAssert.assertThat(powerSet, Matchers.containsInAnyOrder( + ImmutableSet.of(), + ImmutableSet.of("APPLE"), + ImmutableSet.of("ORANGE"), + ImmutableSet.of("APPLE", "ORANGE"), + ImmutableSet.of("MANGO"), + ImmutableSet.of("APPLE", "MANGO"), + ImmutableSet.of("ORANGE", "MANGO"), + ImmutableSet.of("APPLE", "ORANGE", "MANGO") + )); + } + + @Test + public void givenSet_WhenPowerSetIsLazyLoadGenerated_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + Set> powerSet = new PowerSetUtility().lazyLoadPowerSet(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (Set subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + } + + @Test + public void givenSet_WhenPowerSetIsCalculated_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + + Set> powerSet = new PowerSetUtility().recursivePowerSet(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (Set subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + } + + @Test + public void givenSet_WhenPowerSetIsCalculatedRecursiveByIndexRepresentation_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + + Set> powerSet = new PowerSetUtility().recursivePowerSetIndexRepresentation(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (Set subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + } + + @Test + public void givenSet_WhenPowerSetIsCalculatedRecursiveByBinaryRepresentation_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + + Set> powerSet = new PowerSetUtility().recursivePowerSetBinaryRepresentation(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (Set subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + } + + @Test + public void givenSet_WhenPowerSetIsCalculatedIterativePowerSetByLoopOverNumbers_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + + List> powerSet = new PowerSetUtility().iterativePowerSetByLoopOverNumbers(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (List subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + //To make sure that one subset is not generated twice + Assertions.assertEquals(powerSet.size(), new HashSet<>(powerSet).size()); + //To make sure that each element in each subset is occurred once + for (List subset : powerSet) { + Assertions.assertEquals(subset.size(), new HashSet<>(subset).size()); + } + } + + @Test + public void givenSet_WhenPowerSetIsCalculatedIterativePowerSetByLoopOverNumbersWithMinimalChange_ThenItContainsAllSubsets() { + + Set set = RandomSetOfStringGenerator.generateRandomSet(); + List> powerSet = new PowerSetUtility().iterativePowerSetByLoopOverNumbersMinimalChange(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (List subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + //To make sure that one subset is not generated twice + Assertions.assertEquals(powerSet.size(), new HashSet<>(powerSet).size()); + //To make sure that each element in each subset is occurred once + for (List subset : powerSet) { + Assertions.assertEquals(subset.size(), new HashSet<>(subset).size()); + } + //To make sure that difference of consecutive subsets is exactly 1 + for(int i=1; i fruits = Arrays.asList("Apples", "Avocados", "Banana", "Blueberry", "Cherry", "Clementine", "Cucumber", "Date", "Fig", + "Grapefruit"/*, "Grape", "Kiwi", "Lemon", "Mango", "Mulberry", "Melon", "Nectarine", "Olive", "Orange"*/); + + static Set generateRandomSet() { + Set set = new HashSet<>(); + Random random = new Random(); + int size = random.nextInt(fruits.size()); + while (set.size() != size) { + set.add(fruits.get(random.nextInt(fruits.size()))); + } + return set; + } + } +} 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-perf/src/test/java/com/baeldung/branchprediction/CombiningUnitTest.java b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/CombiningUnitTest.java new file mode 100644 index 0000000000..c98eef5ed1 --- /dev/null +++ b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/CombiningUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.branchprediction; + +import java.util.stream.LongStream; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CombiningUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(CombiningUnitTest.class); + + public static final int TOP = 10000000; + public static final double FRACTION = 0.1; + + @Test + public void combined() { + long[] first = LongStream.range(0, TOP) + .map(n -> Math.random() < FRACTION ? 0 : n) + .toArray(); + long[] second = LongStream.range(0, TOP) + .map(n -> Math.random() < FRACTION ? 0 : n) + .toArray(); + + long count = 0; + long start = System.currentTimeMillis(); + for (int i = 0; i < TOP; i++) { + if (first[i] * second[i] != 0) { + ++count; + } + } + long end = System.currentTimeMillis(); + + LOG.info("Counted {}/{} numbers using combined mode in {}ms", count, TOP, end - start); + + } + + @Test + public void separate() { + long[] first = LongStream.range(0, TOP) + .map(n -> Math.random() < FRACTION ? 0 : n) + .toArray(); + long[] second = LongStream.range(0, TOP) + .map(n -> Math.random() < FRACTION ? 0 : n) + .toArray(); + + long count = 0; + long start = System.currentTimeMillis(); + for (int i = 0; i < TOP; i++) { + if (first[i] != 0 && second[i] != 0) { + ++count; + } + } + long end = System.currentTimeMillis(); + + LOG.info("Counted {}/{} numbers using separate mode in {}ms", count, TOP, end - start); + } +} diff --git a/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/IfUnitTest.java b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/IfUnitTest.java new file mode 100644 index 0000000000..6f80624502 --- /dev/null +++ b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/IfUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.branchprediction; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.LongStream; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class IfUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(IfUnitTest.class); + + public static final int TOP = 10000000; + + @Test + public void majorBranchSorted() { + test(TOP, 0.9, false); + } + + @Test + public void minorBranchSorted() { + test(TOP, 0.1, false); + } + + @Test + public void equalBranchSorted() { + test(TOP, 0.5, false); + } + + @Test + public void allBranchSorted() { + test(TOP, 1, false); + } + + @Test + public void noneBranchSorted() { + test(TOP, 0, false); + } + + @Test + public void majorBranchShuffled() { + test(TOP, 0.9, true); + } + + @Test + public void minorBranchShuffled() { + test(TOP, 0.1, true); + } + + @Test + public void equalBranchShuffled() { + test(TOP, 0.5, true); + } + + @Test + public void allBranchShuffled() { + test(TOP, 1, true); + } + + @Test + public void noneBranchShuffled() { + test(TOP, 0, true); + } + + private void test(long top, double cutoffPercentage, boolean shuffle) { + List numbers = LongStream.range(0, top) + .boxed() + .collect(Collectors.toList()); + if (shuffle) { + Collections.shuffle(numbers); + } + + long cutoff = (long)(top * cutoffPercentage); + long low = 0; + long high = 0; + + long start = System.currentTimeMillis(); + for (Long number : numbers) { + if (number < cutoff) { + ++low; + } else { + ++high; + } + } + long end = System.currentTimeMillis(); + + LOG.info("Counted {}/{} {} numbers in {}ms", low, high, shuffle ? "shuffled" : "sorted", end - start); + + } +} diff --git a/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/SortingUnitTest.java b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/SortingUnitTest.java new file mode 100644 index 0000000000..6af40bd57a --- /dev/null +++ b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/SortingUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.branchprediction; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.LongStream; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SortingUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(SortingUnitTest.class); + public static final int BIG = 10000000; + public static final int SMALL = 100000; + + @Test + public void sortedBig() { + test(BIG, false); + } + + @Test + public void shuffledBig() { + test(BIG, true); + } + + @Test + public void sortedSmall() { + test(SMALL, false); + } + + @Test + public void shuffledSmall() { + test(SMALL, true); + } + + private void test(long top, boolean shuffle) { + List numbers = LongStream.range(0, top) + .boxed() + .collect(Collectors.toList()); + + if (shuffle) { + Collections.shuffle(numbers); + } + + long cutoff = top / 2; + long count = 0; + + long start = System.currentTimeMillis(); + for (Long number : numbers) { + if (number < cutoff) { + ++count; + } + } + long end = System.currentTimeMillis(); + + LOG.info("Counted {}/{} {} numbers in {}ms", + count, top, shuffle ? "shuffled" : "sorted", end - start); + } +} diff --git a/core-java-modules/core-java-security-manager/README.md b/core-java-modules/core-java-security-manager/README.md deleted file mode 100644 index a4abe7f80a..0000000000 --- a/core-java-modules/core-java-security-manager/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Intro to the Java SecurityManager](https://www.baeldung.com/java-security-manager) diff --git a/core-java-modules/core-java-security-manager/pom.xml b/core-java-modules/core-java-security-manager/pom.xml deleted file mode 100644 index 52f1554ace..0000000000 --- a/core-java-modules/core-java-security-manager/pom.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - 4.0.0 - core-java-security-manager - 0.1.0-SNAPSHOT - core-java-security-manager - jar - - - com.baeldung.core-java-modules - core-java-modules - 1.0.0-SNAPSHOT - - - diff --git a/core-java-modules/core-java-security-manager/src/test/java/com/baeldung/security/manager/SecurityManagerUnitTest.java b/core-java-modules/core-java-security-manager/src/test/java/com/baeldung/security/manager/SecurityManagerUnitTest.java deleted file mode 100644 index a845f233b5..0000000000 --- a/core-java-modules/core-java-security-manager/src/test/java/com/baeldung/security/manager/SecurityManagerUnitTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.security.manager; - -import org.junit.Test; - -import java.net.URL; -import java.security.AccessControlException; -import java.util.concurrent.Callable; - -public class SecurityManagerUnitTest { - - @Test(expected = AccessControlException.class) - public void whenSecurityManagerIsActive_thenNetworkIsNotAccessibleByDefault() throws Exception { - doTest(() -> { - new URL("http://www.google.com").openConnection().connect(); - return null; - }); - } - - @Test(expected = AccessControlException.class) - public void whenUnauthorizedClassTriesToAccessProtectedOperation_thenAnExceptionIsThrown() throws Exception { - doTest(() -> { - new Service().operation(); - return null; - }); - } - - private void doTest(Callable action) throws Exception { - System.setSecurityManager(new SecurityManager()); - try { - action.call(); - } finally { - System.setSecurityManager(null); - } - } -} diff --git a/core-java-modules/core-java-security/README.md b/core-java-modules/core-java-security/README.md index 7386d04e8e..ff9b1eef14 100644 --- a/core-java-modules/core-java-security/README.md +++ b/core-java-modules/core-java-security/README.md @@ -15,4 +15,5 @@ This module contains articles about core Java Security - [The Java SecureRandom Class](https://www.baeldung.com/java-secure-random) - [An Introduction to Java SASL](https://www.baeldung.com/java-sasl) - [A Guide to Java GSS API](https://www.baeldung.com/java-gss) +- [Intro to the Java SecurityManager](https://www.baeldung.com/java-security-manager) diff --git a/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/CustomPermission.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/securitymanager/CustomPermission.java similarity index 87% rename from core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/CustomPermission.java rename to core-java-modules/core-java-security/src/main/java/com/baeldung/securitymanager/CustomPermission.java index 5f9c43336f..fa46353893 100644 --- a/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/CustomPermission.java +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/securitymanager/CustomPermission.java @@ -1,4 +1,4 @@ -package com.baeldung.security.manager; +package com.baeldung.securitymanager; import java.security.BasicPermission; diff --git a/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/Service.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/securitymanager/Service.java similarity index 92% rename from core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/Service.java rename to core-java-modules/core-java-security/src/main/java/com/baeldung/securitymanager/Service.java index 1b9f14e3b8..21e0c0a657 100644 --- a/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/Service.java +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/securitymanager/Service.java @@ -1,4 +1,4 @@ -package com.baeldung.security.manager; +package com.baeldung.securitymanager; public class Service { diff --git a/core-java-modules/core-java-security/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java similarity index 98% rename from core-java-modules/core-java-security/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java rename to core-java-modules/core-java-security/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java index 55e71470c8..67d6918c09 100644 --- a/core-java-modules/core-java-security/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java +++ b/core-java-modules/core-java-security/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.md5; +package com.baeldung.java.md5; import static org.assertj.core.api.Assertions.assertThat; diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/securitymanager/SecurityManagerUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/securitymanager/SecurityManagerUnitTest.java new file mode 100644 index 0000000000..a7dcc949d2 --- /dev/null +++ b/core-java-modules/core-java-security/src/test/java/com/baeldung/securitymanager/SecurityManagerUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.securitymanager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.net.URL; +import java.security.AccessControlException; + +public class SecurityManagerUnitTest { + + private static final String TESTING_SECURITY_POLICY = "file:src/test/resources/testing.policy"; + + @Before + public void setUp() { + System.setProperty("java.security.policy", TESTING_SECURITY_POLICY); + System.setSecurityManager(new SecurityManager()); + } + + @After + public void tearDown() { + System.setSecurityManager(null); + } + + @Test(expected = AccessControlException.class) + public void whenSecurityManagerIsActive_thenNetworkIsNotAccessibleByDefault() throws IOException { + new URL("http://www.google.com").openConnection().connect(); + } + + @Test(expected = AccessControlException.class) + public void whenUnauthorizedClassTriesToAccessProtectedOperation_thenAnExceptionIsThrown() { + new Service().operation(); + } +} diff --git a/core-java-modules/core-java-security/src/test/resources/testing.policy b/core-java-modules/core-java-security/src/test/resources/testing.policy new file mode 100644 index 0000000000..16ab8a1869 --- /dev/null +++ b/core-java-modules/core-java-security/src/test/resources/testing.policy @@ -0,0 +1,5 @@ +grant { + // This is for testing purposes only. + // It allows us to properly reset the security manager after the unit test completes. + permission java.lang.RuntimePermission "setSecurityManager"; +}; \ No newline at end of file diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index d54e32ddb2..b3e674c8e2 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -49,7 +49,8 @@ core-java-concurrency-basic-2 core-java-concurrency-collections - core-java-date-operations + core-java-date-operations-1 + core-java-date-operations-2 ]](/core-kotlin-lang-oop-2) diff --git a/core-kotlin-modules/core-kotlin-lang-oop/pom.xml b/core-kotlin-modules/core-kotlin-lang-oop/pom.xml new file mode 100644 index 0000000000..03fc80f07d --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-oop/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + core-kotlin-lang-oop + core-kotlin-lang-oop + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + \ No newline at end of file diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Car.kt similarity index 100% rename from core-kotlin/src/main/java/com/baeldung/constructor/Car.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Car.kt diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Employee.kt similarity index 100% rename from core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Employee.kt diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Person.java b/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Person.java similarity index 100% rename from core-kotlin/src/main/java/com/baeldung/constructor/Person.java rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Person.java diff --git a/core-kotlin/src/main/java/com/baeldung/dataclass/Movie.java b/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/dataclass/Movie.java similarity index 100% rename from core-kotlin/src/main/java/com/baeldung/dataclass/Movie.java rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/dataclass/Movie.java diff --git a/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/constructor/Person.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/constructor/Person.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/dataclass/Movie.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Movie.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/dataclass/Movie.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Movie.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/dataclass/Sandbox.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Sandbox.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/dataclass/Sandbox.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Sandbox.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/CardType.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/CardType.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/ICardLimit.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/ICardLimit.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/ListExtension.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/ListExtension.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/ListExtension.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/ListExtension.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/Sealed.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/Sealed.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/StringUtil.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/StringUtil.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/StringUtil.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/StringUtil.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/nested/Computer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/nested/Computer.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/static/LoggingUtils.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/LoggingUtils.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/static/LoggingUtils.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/LoggingUtils.kt diff --git a/core-kotlin/src/test/java/com/baeldung/kotlin/StringUtilUnitTest.java b/core-kotlin-modules/core-kotlin-lang-oop/src/test/java/com/baeldung/kotlin/StringUtilUnitTest.java similarity index 100% rename from core-kotlin/src/test/java/com/baeldung/kotlin/StringUtilUnitTest.java rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/java/com/baeldung/kotlin/StringUtilUnitTest.java diff --git a/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ListExtensionTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/ListExtensionTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/ListExtensionTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/ListExtensionTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/Counter.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/Counter.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/Counter.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/Counter.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/ObjectsTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ObjectsTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/ObjectsTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ObjectsTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/OuterClass.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/OuterClass.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/OuterClass.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/OuterClass.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/ReverseStringComparator.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ReverseStringComparator.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/ReverseStringComparator.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ReverseStringComparator.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/SimpleSingleton.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/SimpleSingleton.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/SimpleSingleton.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/SimpleSingleton.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/StaticClass.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/StaticClass.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/StaticClass.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/StaticClass.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt rename to core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt diff --git a/core-kotlin-modules/pom.xml b/core-kotlin-modules/pom.xml index 1abea86289..e49b5fb85d 100644 --- a/core-kotlin-modules/pom.xml +++ b/core-kotlin-modules/pom.xml @@ -15,11 +15,16 @@ + core-kotlin-advanced core-kotlin-annotations + core-kotlin-collections + core-kotlin-concurrency core-kotlin-io core-kotlin-lang core-kotlin-lang-2 core-kotlin-strings + core-kotlin-lang-oop + core-kotlin-lang-oop-2 diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 785eb0b689..89e1b7287e 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -7,37 +7,26 @@ This module contains articles about core Kotlin. - [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin) - [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability) - [Generics in Kotlin](https://www.baeldung.com/kotlin-generics) -- [Introduction to Kotlin Coroutines](https://www.baeldung.com/kotlin-coroutines) -- [Overview of Kotlin Collections API](https://www.baeldung.com/kotlin-collections-api) -- [Converting a List to Map in Kotlin](https://www.baeldung.com/kotlin-list-to-map) - [Data Classes in Kotlin](https://www.baeldung.com/kotlin-data-classes) - [Delegated Properties in Kotlin](https://www.baeldung.com/kotlin-delegated-properties) - [Sealed Classes in Kotlin](https://www.baeldung.com/kotlin-sealed-classes) - [JUnit 5 for Kotlin Developers](https://www.baeldung.com/junit-5-kotlin) - [Extension Methods in Kotlin](https://www.baeldung.com/kotlin-extension-methods) -- [Regular Expressions in Kotlin](https://www.baeldung.com/kotlin-regular-expressions) - [Objects in Kotlin](https://www.baeldung.com/kotlin-objects) -- [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection) - [Working with Enums in Kotlin](https://www.baeldung.com/kotlin-enum) - [Create a Java and Kotlin Project with Maven](https://www.baeldung.com/kotlin-maven-java-project) -- [Reflection with Kotlin](https://www.baeldung.com/kotlin-reflection) - [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number) -- [Idiomatic Logging in Kotlin](https://www.baeldung.com/kotlin-logging) - [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors) - [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern) - [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes) - [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel) - [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant) - [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class) -- [Mapping of Data Objects in Kotlin](https://www.baeldung.com/kotlin-data-objects) -- [Threads vs Coroutines in Kotlin](https://www.baeldung.com/kotlin-threads-coroutines) - [Guide to Kotlin Interfaces](https://www.baeldung.com/kotlin-interfaces) - [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort) - [Dependency Injection for Kotlin with Injekt](https://www.baeldung.com/kotlin-dependency-injection-with-injekt) - [Implementing a Binary Tree in Kotlin](https://www.baeldung.com/kotlin-binary-tree) -- [Kotlin Contracts](https://www.baeldung.com/kotlin-contracts) - [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes) -- [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl) - [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods) - [Delegation Pattern in Kotlin](https://www.baeldung.com/kotlin-delegation-pattern) - More articles: [[next -->]](/core-kotlin-2) diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index 63a6d8035e..5fe8a47f62 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -14,11 +14,6 @@ - - org.apache.commons - commons-math3 - ${commons-math3.version} - org.apache.commons commons-lang3 @@ -75,7 +70,6 @@ - 3.6.1 1.1.1 5.2.0 3.10.0 diff --git a/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java index 380ff9df6b..cafd8cfb7b 100644 --- a/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java +++ b/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java @@ -1,20 +1,20 @@ package com.baeldung.basic; +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import org.springframework.stereotype.Component; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.PrintWriter; - @Component public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { @Override - public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException { + public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException { response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\""); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); final PrintWriter writer = response.getWriter(); @@ -22,7 +22,7 @@ public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoi } @Override - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() { setRealmName("Baeldung"); super.afterPropertiesSet(); } diff --git a/java-numbers-2/pom.xml b/java-numbers-2/pom.xml index ba40ef0a38..f5f10d9364 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 + 2.6.0 + diff --git a/java-numbers-2/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java b/java-numbers-2/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java new file mode 100644 index 0000000000..84cd3eecb6 --- /dev/null +++ b/java-numbers-2/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java @@ -0,0 +1,91 @@ +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 Integer generateRandomWithSecureRandom() { + SecureRandom secureRandom = new SecureRandom(); + int randomWithSecureRandom = secureRandom.nextInt(); + return randomWithSecureRandom; + } + + 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-2/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java new file mode 100644 index 0000000000..31d334f8b8 --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java @@ -0,0 +1,137 @@ +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 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, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } + } + + @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, MAX_RANGE); + 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 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/java-numbers-3/pom.xml b/java-numbers-3/pom.xml new file mode 100644 index 0000000000..3dd8e16bc7 --- /dev/null +++ b/java-numbers-3/pom.xml @@ -0,0 +1,26 @@ + + 4.0.0 + java-numbers-3 + java-numbers-3 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + java-numbers-3 + + + src/main/resources + true + + + + + diff --git a/java-numbers-3/src/test/java/com/baeldung/doubletolong/DoubleToLongUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/doubletolong/DoubleToLongUnitTest.java new file mode 100644 index 0000000000..702c59c12b --- /dev/null +++ b/java-numbers-3/src/test/java/com/baeldung/doubletolong/DoubleToLongUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.doubletolong; + +import org.junit.Assert; +import org.junit.Test; + +public class DoubleToLongUnitTest { + + final static double VALUE = 9999.999; + + @Test + public void givenDoubleValue_whenLongValueCalled_thenLongValueReturned() { + Assert.assertEquals(9999L, Double.valueOf(VALUE).longValue()); + } + + @Test + public void givenDoubleValue_whenMathRoundUsed_thenRoundUp() { + Assert.assertEquals(10000L, Math.round(VALUE)); + } + + @Test + public void givenDoubleValue_whenMathRoundUsed_thenRoundDown() { + Assert.assertEquals(9999L, Math.round(9999.444)); + } + + @Test + public void givenDoubleValue_whenMathRoundUsed_thenSameValueReturned() { + Assert.assertEquals(9999L, Math.round(9999.0)); + } + + @Test + public void givenDoubleValue_whenMathCeilUsed_thenLongValueReturned() { + Assert.assertEquals(10000L, Math.ceil(VALUE), 0); + } + + @Test + public void givenDoubleValue_whenMathCeilUsed_thenSameValueReturned() { + Assert.assertEquals(9999L, Math.ceil(9999.0), 0); + } + + @Test + public void givenDoubleValue_whenMathCeilUsed_thenDifferentThanRound() { + Assert.assertEquals(10000L, Math.ceil(9999.444), 0); + } + + @Test + public void givenDoubleValue_whenMathFloorUsed_thenLongValueReturned() { + Assert.assertEquals(9999L, Math.floor(VALUE), 0); + } + + @Test + public void givenDoubleValue_whenMathFloorUsed_thenSameValueReturned() { + Assert.assertEquals(9999L, Math.floor(9999.0), 0); + } + + @Test + public void givenDoubleValue_whenMathFloorUsed_thenDifferentThanCeil() { + Assert.assertEquals(9999L, Math.floor(9999.444), 0); + } + + @Test + public void givenDoubleValue_whenTypeCasted_thenLongValueReturned() { + Assert.assertEquals(9999L, (long) VALUE); + } +} diff --git a/linux-bash/read/src/main/bash/file.csv b/linux-bash/read/src/main/bash/file.csv new file mode 100644 index 0000000000..69a50772ab --- /dev/null +++ b/linux-bash/read/src/main/bash/file.csv @@ -0,0 +1 @@ +car,car model,car year,car vin;Mercury,Grand Marquis,2000,2G61S5S33F9986032;Mitsubishi,Truck,1995,SCFFDABE1CG137362;Ford,Mustang,1968,2G4WS55J351278031;Ford,Crown Victoria,1996,4T1BK1EB8EU586249;GMC,Envoy,2004,WVGEF9BP3FD720618; diff --git a/linux-bash/read/src/main/bash/read_inputs.sh b/linux-bash/read/src/main/bash/read_inputs.sh new file mode 100755 index 0000000000..30eb598ac3 --- /dev/null +++ b/linux-bash/read/src/main/bash/read_inputs.sh @@ -0,0 +1,122 @@ +#!/bin/bash + +# section 2.1 +default_read(){ + read input1 input2 input3 + echo "[$input1] [$input2] [$input3]" +} + +# section 2.2 +custom_ifs_no_array(){ + OLDIFS=$IFS + IFS=";" + read input1 input2 input3 + echo "[$input1] [$input2] [$input3]" + # restore default IFS after we're finished so current shell behaves like before + IFS=$OLDIFS +} + +# Section 2.3 +prompt_read_password(){ + prompt="You shall not pass:" + read -p "$prompt" -s input + echo -e "\ninput password [$input]" +} + +array_read(){ + declare -a input_array + text="baeldung is a cool tech site" + read -e -i "$text" -a input_array + for input in ${input_array[@]} + do + echo " word [$input]" + done +} + +# section 3.1 +file_read(){ + exec {file_descriptor}<"./file.csv" + declare -a input_array + delimiter=";" + while IFS="," read -a input_array -d $delimiter -u $file_descriptor + do + echo "${input_array[0]},${input_array[2]}" + done + exec {file_descriptor}>&- +} + +# section 3.2 +command_pipe(){ + ls -ll / | { declare -a input + read + while read -a input; + do + echo "${input[0]} ${input[8]}" + done } +} + +# section 3.3 +timeout_input_read(){ + prompt="You shall not pass:" + read -p "$prompt" -s -r -t 5 input + if [ -z "$input" ]; then + echo -e "\ntimeout occured!" + else + echo -e "\ninput word [$input]" + fi +} + +exactly_n_read(){ + prompt="Reading exactly 11 chars:" + read -p "$prompt" -N 11 -t 5 input1 input2 + echo -e "\ninput word1 [$input1]" + echo "input word2 [$input2]" +} + +# main menu entry point +echo "****Read command samples menu*****" +PS3="Your choice (1,2,3 etc.):" +options=("default_read" "custom_ifs_no_array" "prompt_read_password" \ + "array_read" "file_read" "command_pipe" "timeout_input_read" \ + "exactly_n_read" "quit") +select option in "${options[@]}" +do + case $option in + "default_read") + echo "Enter something separated by spaces" + default_read + ;; + "custom_ifs_no_array") + echo "Enter something separated by ;" + custom_ifs_no_array + ;; + "prompt_read_password") + echo "Enter an invisible password after the prompt" + prompt_read_password + ;; + "array_read") + echo "Enter something else or just return" + array_read + ;; + "file_read") + echo "Reading from one liner csv file" + file_read + ;; + "command_pipe") + echo "Listing files and access rights from /" + command_pipe + ;; + "timeout_input_read") + echo "Enter something in 5 seconds or less" + timeout_input_read + ;; + "exactly_n_read") + echo "Enter at least 11 characters or wait 5 seconds" + exactly_n_read + ;; + "quit") + break + ;; + *) echo "Invalid option";; + esac +done \ No newline at end of file diff --git a/logging-modules/logback/pom.xml b/logging-modules/logback/pom.xml index 6ffc9e1235..ee430949df 100644 --- a/logging-modules/logback/pom.xml +++ b/logging-modules/logback/pom.xml @@ -50,12 +50,25 @@ + + javax.mail + mail + ${javax.mail.version} + + + javax.activation + activation + ${javax.activation.version} + runtime + 1.2.3 0.1.5 3.3.5 + 1.4.7 + 1.1.1 diff --git a/logging-modules/logback/src/main/resources/logback.xml b/logging-modules/logback/src/main/resources/logback.xml index 37ae2adbb0..76ddc2e3ee 100644 --- a/logging-modules/logback/src/main/resources/logback.xml +++ b/logging-modules/logback/src/main/resources/logback.xml @@ -10,9 +10,47 @@ + + OUR-SMTP-HOST-ADDRESS + + EMAIL-RECIPIENT-1 + EMAIL-RECIPIENT-2 + SENDER-EMAIL-ADDRESS + BAELDUNG: %logger{20} - %msg + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg%n + + + + + OUR-SMTP-HOST-ADDRESS + EMAIL-RECIPIENT + SENDER-EMAIL-ADDRESS + BAELDUNG: %logger{20} - %msg + + + + 5 + + + + + smtp.gmail.com + 587 + true + false + SENDER-EMAIL@gmail.com + GMAIL-ACCT-PASSWORD + EMAIL-RECIPIENT + SENDER-EMAIL@gmail.com + BAELDUNG: %logger{20} - %msg + + + + \ 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/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 9260f88de5..85a4645aa7 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -30,8 +30,8 @@ - 5.1.9.RELEASE - 5.1.6.RELEASE + 5.2.2.RELEASE + 5.2.1.RELEASE \ No newline at end of file diff --git a/pom.xml b/pom.xml index 419191e5d5..aeaef5f676 100644 --- a/pom.xml +++ b/pom.xml @@ -344,7 +344,7 @@ algorithms-miscellaneous-5 algorithms-searching algorithms-sorting - + algorithms-sorting-2 animal-sniffer-mvn-plugin annotations antlr @@ -360,6 +360,7 @@ apache-opennlp apache-poi apache-pulsar + apache-rocketmq apache-shiro apache-solrj apache-spark @@ -461,6 +462,7 @@ java-math-2 java-numbers java-numbers-2 + java-numbers-3 java-rmi java-spi java-vavr-stream @@ -531,7 +533,7 @@ mustache mybatis - netflix + netflix-modules ninja oauth2-framework-impl @@ -891,7 +893,7 @@ algorithms-miscellaneous-5 algorithms-searching algorithms-sorting - + algorithms-sorting-2 animal-sniffer-mvn-plugin annotations antlr @@ -907,6 +909,7 @@ apache-opennlp apache-poi apache-pulsar + apache-rocketmq apache-shiro apache-solrj apache-spark @@ -1008,6 +1011,7 @@ java-math-2 java-numbers java-numbers-2 + java-numbers-3 java-rmi java-spi java-vavr-stream @@ -1078,7 +1082,7 @@ mustache mybatis - netflix + netflix-modules ninja oauth2-framework-impl diff --git a/spring-5-reactive-security/pom.xml b/spring-5-reactive-security/pom.xml index 2f4a31241b..58c993bda5 100644 --- a/spring-5-reactive-security/pom.xml +++ b/spring-5-reactive-security/pom.xml @@ -128,7 +128,7 @@ 1.0 4.1 3.1.6.RELEASE - 2.2.1.RELEASE + 2.2.2.RELEASE diff --git a/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java index 6e73e8072c..d8e2f0b23b 100644 --- a/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java @@ -1,11 +1,7 @@ package com.baeldung.reactive.functional; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; - -import java.util.ArrayList; -import java.util.List; - +import com.baeldung.webflux.Employee; +import com.baeldung.webflux.EmployeeRepository; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; @@ -15,13 +11,15 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; - -import com.baeldung.webflux.Employee; -import com.baeldung.webflux.EmployeeRepository; - import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import java.util.Arrays; +import java.util.List; + +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @@ -58,15 +56,11 @@ public class EmployeeSpringFunctionalIntegrationTest { .bindToRouterFunction(config.getAllEmployeesRoute()) .build(); - List employeeList = new ArrayList<>(); + List employees = Arrays.asList( + new Employee("1", "Employee 1"), + new Employee("2", "Employee 2")); - Employee employee1 = new Employee("1", "Employee 1"); - Employee employee2 = new Employee("2", "Employee 2"); - - employeeList.add(employee1); - employeeList.add(employee2); - - Flux employeeFlux = Flux.fromIterable(employeeList); + Flux employeeFlux = Flux.fromIterable(employees); given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); client.get() @@ -75,7 +69,7 @@ public class EmployeeSpringFunctionalIntegrationTest { .expectStatus() .isOk() .expectBodyList(Employee.class) - .isEqualTo(employeeList); + .isEqualTo(employees); } @Test diff --git a/spring-aop/src/main/java/com/baeldung/Application.java b/spring-aop/src/main/java/com/baeldung/Application.java index 52ef79ac23..c0490d50c6 100644 --- a/spring-aop/src/main/java/com/baeldung/Application.java +++ b/spring-aop/src/main/java/com/baeldung/Application.java @@ -6,7 +6,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { - public static void main(String[] args) { SpringApplication.run(Application.class, args); } diff --git a/spring-aop/src/main/resources/org.baeldung.logger/springAop-applicationContext.xml b/spring-aop/src/main/resources/com.baeldung.logger/springAop-applicationContext.xml similarity index 98% rename from spring-aop/src/main/resources/org.baeldung.logger/springAop-applicationContext.xml rename to spring-aop/src/main/resources/com.baeldung.logger/springAop-applicationContext.xml index 32e50e3502..595e7e46e6 100644 --- a/spring-aop/src/main/resources/org.baeldung.logger/springAop-applicationContext.xml +++ b/spring-aop/src/main/resources/com.baeldung.logger/springAop-applicationContext.xml @@ -1,54 +1,54 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-aop/src/test/java/com/baeldung/TestConfig.java b/spring-aop/src/test/java/com/baeldung/TestConfig.java deleted file mode 100644 index e5db2508e4..0000000000 --- a/spring-aop/src/test/java/com/baeldung/TestConfig.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; - -@Configuration -@ComponentScan(basePackages = { "com.baeldung.pointcutadvice" }) -@EnableAspectJAutoProxy -public class TestConfig { -} diff --git a/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopLoggingIntegrationTest.java b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopLoggingIntegrationTest.java index eff3d2eb19..a687eec388 100644 --- a/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopLoggingIntegrationTest.java +++ b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopLoggingIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.pointcutadvice; -import com.baeldung.TestConfig; +import com.baeldung.Application; import com.baeldung.pointcutadvice.dao.FooDao; import org.junit.Before; import org.junit.Test; @@ -23,7 +23,7 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {Application.class}, loader = AnnotationConfigContextLoader.class) public class AopLoggingIntegrationTest { @Before diff --git a/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPerformanceIntegrationTest.java b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPerformanceIntegrationTest.java index 452609d730..5a7797e5cd 100644 --- a/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPerformanceIntegrationTest.java +++ b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPerformanceIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.pointcutadvice; -import com.baeldung.TestConfig; +import com.baeldung.Application; import com.baeldung.pointcutadvice.dao.FooDao; import org.junit.Before; import org.junit.Test; @@ -23,7 +23,7 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {Application.class}, loader = AnnotationConfigContextLoader.class) public class AopPerformanceIntegrationTest { @Before diff --git a/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPublishingIntegrationTest.java b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPublishingIntegrationTest.java index 559dc52cb5..996b56d61e 100644 --- a/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPublishingIntegrationTest.java +++ b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPublishingIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.pointcutadvice; -import com.baeldung.TestConfig; +import com.baeldung.Application; import com.baeldung.pointcutadvice.dao.FooDao; import com.baeldung.pointcutadvice.events.FooCreationEventListener; import org.junit.Before; @@ -21,7 +21,7 @@ import java.util.regex.Pattern; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {Application.class}, loader = AnnotationConfigContextLoader.class) public class AopPublishingIntegrationTest { @Before 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/foo.properties b/spring-boot-properties/src/test/resources/foo.properties new file mode 100644 index 0000000000..c9f0304f65 --- /dev/null +++ b/spring-boot-properties/src/test/resources/foo.properties @@ -0,0 +1 @@ +foo=bar \ 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-core-2/src/main/java/com/baeldung/autowire/sample/FooService.java b/spring-core-2/src/main/java/com/baeldung/autowire/sample/FooService.java index c55d93da11..8a073279bc 100644 --- a/spring-core-2/src/main/java/com/baeldung/autowire/sample/FooService.java +++ b/spring-core-2/src/main/java/com/baeldung/autowire/sample/FooService.java @@ -3,6 +3,10 @@ package com.baeldung.autowire.sample; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +/** + * This class presents a field, a constructor, and a setter injection type. + * Usually, we'd stick with a single approach for a given property. This is just an educational code. + */ @Component public class FooService { @@ -10,6 +14,16 @@ public class FooService { @FormatterType("Foo") private Formatter formatter; + @Autowired + public FooService(@FormatterType("Foo") Formatter formatter) { + this.formatter = formatter; + } + + @Autowired + public void setFormatter(@FormatterType("Foo") Formatter formatter) { + this.formatter = formatter; + } + public String doStuff() { return formatter.format(); } 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-2/README.md b/spring-mvc-basics-2/README.md index 880d5dfa0f..9d1402a210 100644 --- a/spring-mvc-basics-2/README.md +++ b/spring-mvc-basics-2/README.md @@ -11,6 +11,5 @@ This module contains articles about Spring MVC - [Guide to Spring Email](https://www.baeldung.com/spring-email) - [Request Method Not Supported (405) in Spring](https://www.baeldung.com/spring-request-method-not-supported-405) - [Spring @RequestParam Annotation](https://www.baeldung.com/spring-request-param) -- [Spring Optional Path Variables](https://www.baeldung.com/spring-optional-path-variables) - More articles: [[more -->]](/spring-mvc-basics-3) - More articles: [[<-- prev]](/spring-mvc-basics) 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-java/README.md b/spring-mvc-java/README.md index 4859e28147..ff1f7830b6 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -16,4 +16,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC @PathVariable with a dot (.) gets truncated](https://www.baeldung.com/spring-mvc-pathvariable-dot) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) -- [The HttpMediaTypeNotAcceptableException in Spring MVC](https://www.baeldung.com/spring-httpmediatypenotacceptable) 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-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/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml b/spring-security-modules/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml index 659347f610..6c0f24e2c4 100644 --- a/spring-security-modules/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml +++ b/spring-security-modules/spring-security-mvc-login/src/main/resources/RedirectionWebSecurityConfig.xml @@ -2,9 +2,9 @@ diff --git a/spring-security-modules/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml b/spring-security-modules/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml index 516829f5eb..eff3e1a1a1 100644 --- a/spring-security-modules/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml +++ b/spring-security-modules/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml @@ -2,9 +2,9 @@ diff --git a/spring-security-modules/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml b/spring-security-modules/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml index 189522889f..8a83bf5e93 100644 --- a/spring-security-modules/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml +++ b/spring-security-modules/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml @@ -2,9 +2,9 @@ diff --git a/spring-security-modules/spring-security-mvc-login/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-security-modules/spring-security-mvc-login/src/main/webapp/WEB-INF/mvc-servlet.xml index 4ba9642448..fa2fae4148 100644 --- a/spring-security-modules/spring-security-mvc-login/src/main/webapp/WEB-INF/mvc-servlet.xml +++ b/spring-security-modules/spring-security-mvc-login/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd" > \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml b/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml index aa5488b116..4568d319b8 100644 --- a/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml +++ b/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml @@ -1,7 +1,7 @@ + xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> diff --git a/spring-security-modules/spring-security-rest-basic-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/spring-security-modules/spring-security-rest-basic-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java index 6e580e7a22..f440bbd10c 100644 --- a/spring-security-modules/spring-security-rest-basic-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java +++ b/spring-security-modules/spring-security-rest-basic-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java @@ -14,7 +14,7 @@ import java.io.PrintWriter; public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { @Override - public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException { + public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException { response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\""); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); final PrintWriter writer = response.getWriter(); @@ -22,7 +22,7 @@ public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoi } @Override - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() { setRealmName("Baeldung"); super.afterPropertiesSet(); } 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/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/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumCookiesJUnitLiveTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumCookiesJUnitLiveTest.java new file mode 100644 index 0000000000..0cbbf52454 --- /dev/null +++ b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumCookiesJUnitLiveTest.java @@ -0,0 +1,110 @@ +package test.java.com.baeldung.selenium.junit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openqa.selenium.Capabilities; +import org.openqa.selenium.Cookie; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.remote.DesiredCapabilities; + +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; + +public class SeleniumCookiesJUnitLiveTest { + + private WebDriver driver; + private String navUrl; + + @Before + public void setUp() { + Capabilities capabilities = DesiredCapabilities.firefox(); + driver = new FirefoxDriver(capabilities); + navUrl = "https://baeldung.com"; + driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); + System.setProperty("webdriver.gecko.driver", "geckodriver.exe"); + } + + @After + public void teardown() { + driver.quit(); + } + + @Test + public void whenNavigate_thenCookiesExist() { + driver.navigate().to(navUrl); + Set cookies = driver.manage().getCookies(); + + assertThat(cookies, is(not(empty()))); + } + + @Test + public void whenNavigate_thenLpCookieExists() { + driver.navigate().to(navUrl); + Cookie lpCookie = driver.manage().getCookieNamed("lp_120073"); + + assertThat(lpCookie, is(not(nullValue()))); + } + + @Test + public void whenNavigate_thenLpCookieIsHasCorrectValue() { + driver.navigate().to(navUrl); + Cookie lpCookie = driver.manage().getCookieNamed("lp_120073"); + + assertThat(lpCookie.getValue(), containsString("www.baeldung.com")); + } + + @Test + public void whenNavigate_thenLpCookieHasCorrectProps() { + driver.navigate().to(navUrl); + Cookie lpCookie = driver.manage().getCookieNamed("lp_120073"); + + assertThat(lpCookie.getDomain(), equalTo(".baeldung.com")); + assertThat(lpCookie.getPath(), equalTo("/")); + assertThat(lpCookie.getExpiry(), is(not(nullValue()))); + assertThat(lpCookie.isSecure(), equalTo(false)); + assertThat(lpCookie.isHttpOnly(), equalTo(false)); + } + + @Test + public void whenAddingCookie_thenItIsPresent() { + driver.navigate().to(navUrl); + Cookie cookie = new Cookie("foo", "bar"); + driver.manage().addCookie(cookie); + Cookie driverCookie = driver.manage().getCookieNamed("foo"); + + assertThat(driverCookie.getValue(), equalTo("bar")); + } + + @Test + public void whenDeletingCookie_thenItIsAbsent() { + driver.navigate().to(navUrl); + Cookie lpCookie = driver.manage().getCookieNamed("lp_120073"); + + assertThat(lpCookie, is(not(nullValue()))); + + driver.manage().deleteCookie(lpCookie); + Cookie deletedCookie = driver.manage().getCookieNamed("lp_120073"); + + assertThat(deletedCookie, is(nullValue())); + } + + @Test + public void whenOverridingCookie_thenItIsUpdated() { + driver.navigate().to(navUrl); + Cookie lpCookie = driver.manage().getCookieNamed("lp_120073"); + driver.manage().deleteCookie(lpCookie); + + Cookie newLpCookie = new Cookie("lp_120073", "foo"); + driver.manage().addCookie(newLpCookie); + + Cookie overriddenCookie = driver.manage().getCookieNamed("lp_120073"); + + assertThat(overriddenCookie.getValue(), equalTo("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 + +