From ebbe8d5dedc0f64b4ec73791ec7f5992c8f48436 Mon Sep 17 00:00:00 2001 From: TINO Date: Sat, 14 Dec 2019 17:40:21 +0300 Subject: [PATCH 01/44] BAEL- 3482 Initial commit --- .../algorithms/minheapmerge/HeapNode.java | 13 ++++ .../algorithms/minheapmerge/MinHeap.java | 63 +++++++++++++++++++ .../algorithms/minheapmerge/MinHeapMerge.java | 56 +++++++++++++++++ 3 files changed, 132 insertions(+) create mode 100644 algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/HeapNode.java create mode 100644 algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeap.java create mode 100644 algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeapMerge.java 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..d19ffa6e46 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeap.java @@ -0,0 +1,63 @@ +package com.baeldung.algorithms.minheapmerge; + +public class MinHeap { + + HeapNode[] heapNodes; + int heapSize; + + public MinHeap(HeapNode heapNodes[]) { + this.heapSize = heapNodes.length; + this.heapNodes = heapNodes; + heapifyFromLastLeafsParent(); + } + + void heapifyFromLastLeafsParent() { + int lastLeafsParentIndex = getParentNodeIndex(heapSize); + while (lastLeafsParentIndex >= 0) { + heapify(lastLeafsParentIndex); + lastLeafsParentIndex--; + } + } + + void heapify(int index) { + int leftNodeIndex = getLeftNodeIndex(index); + int rightNodeIndex = getRightNodeIndex(index); + int smallestElementIndex = index; + if (leftNodeIndex < heapSize && heapNodes[leftNodeIndex].element < heapNodes[index].element) + smallestElementIndex = leftNodeIndex; + + if (rightNodeIndex < heapSize && 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 hepifyFromRoot(HeapNode root) { + heapify(0); + } + + void swap(int i, int j) { + HeapNode temp = heapNodes[i]; + heapNodes[i] = heapNodes[j]; + heapNodes[j] = temp; + } +} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeapMerge.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeapMerge.java new file mode 100644 index 0000000000..62cb46321c --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeapMerge.java @@ -0,0 +1,56 @@ +package com.baeldung.algorithms.minheapmerge; + +public class MinHeapMerge { + + static void printArray(int[] array) { + for (int i = 0; i < array.length; i++) { + System.out.print(array[i] + " "); + } + } + + static int populateHeapNodesAndDetermineResultingArrayLength(int[][] array, HeapNode[] heapNodes) { + int resultSize = 0; + + for (int i = 0; i < array.length; i++) { + HeapNode node = new HeapNode(array[i][0], i); + heapNodes[i] = node; + resultSize += array[i].length; + } + return resultSize; + } + + static int[] createMinHeapAndMergeArrays(int[][] array, HeapNode[] heapNodes, int resultingArraySize) { + + 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.hepifyFromRoot(root); + } + return resultingArray; + } + + static void merge(int[][] array) { + HeapNode[] heapNodes = new HeapNode[array.length]; + int resultingArraySize = populateHeapNodesAndDetermineResultingArrayLength(array, heapNodes); + + int[] resultingArray = createMinHeapAndMergeArrays(array, heapNodes, resultingArraySize); + + printArray(resultingArray); + + } + + public static void main(String args[]) { + int[][] array = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 650, 200 }, { 3, 4 }, { 1001, 6456, 23000 } }; + + merge(array); + } +} From 0104b269fac0399e44d401f2895a5dff0b14a06d Mon Sep 17 00:00:00 2001 From: Anshul BANSAL Date: Thu, 19 Dec 2019 11:29:19 +0200 Subject: [PATCH 02/44] Initial Commit --- java-async/pom.xml | 37 +++++++++++++++ .../main/java/com/baeldung/async/Async.java | 46 +++++++++++++++++++ .../com/baeldung/async/AsyncUnitTest.java | 9 ++++ 3 files changed, 92 insertions(+) create mode 100644 java-async/pom.xml create mode 100644 java-async/src/main/java/com/baeldung/async/Async.java create mode 100644 java-async/src/main/resources/com/baeldung/async/AsyncUnitTest.java diff --git a/java-async/pom.xml b/java-async/pom.xml new file mode 100644 index 0000000000..56ff53321f --- /dev/null +++ b/java-async/pom.xml @@ -0,0 +1,37 @@ + + + 4.0.0 + java-async + 0.1.0-SNAPSHOT + java-async + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + + + + java-async + + + src/main/resources + true + + + + + + 1.0.3 + 3.6.1 + + + diff --git a/java-async/src/main/java/com/baeldung/async/Async.java b/java-async/src/main/java/com/baeldung/async/Async.java new file mode 100644 index 0000000000..b505077d10 --- /dev/null +++ b/java-async/src/main/java/com/baeldung/async/Async.java @@ -0,0 +1,46 @@ +package com.baeldung.async; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class Async { + + public static void main(String[] args) { + System.out.println("hello world!!"); + + try { + Future completableFuture = calculateAsync(); + + String result = completableFuture.get(); + + System.out.println(result); + + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ExecutionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + CompletableFuture.runAsync(() -> { + System.out.println("This is Async"); + }); + } + + public static Future calculateAsync() throws InterruptedException { + CompletableFuture completableFuture = new CompletableFuture<>(); + + Executors.newCachedThreadPool().submit(() -> { + Thread.sleep(500); + completableFuture.complete("Hello"); + return null; + }); + + return completableFuture; + } + +} \ No newline at end of file diff --git a/java-async/src/main/resources/com/baeldung/async/AsyncUnitTest.java b/java-async/src/main/resources/com/baeldung/async/AsyncUnitTest.java new file mode 100644 index 0000000000..57a61dbfe2 --- /dev/null +++ b/java-async/src/main/resources/com/baeldung/async/AsyncUnitTest.java @@ -0,0 +1,9 @@ +package com.baeldung.async; + +public class AsyncUnitTest { + + public static void main(String[] args) { + System.out.println("hello"); + } + +} \ No newline at end of file From 64e55aea15b7d4cb9503e7282b1782e82e2c5c8f Mon Sep 17 00:00:00 2001 From: TINO Date: Sat, 21 Dec 2019 16:55:42 +0300 Subject: [PATCH 03/44] BAEL - 3482 Added unit test --- .../algorithms/minheapmerge/MinHeap.java | 14 ++++---- .../algorithms/minheapmerge/MinHeapMerge.java | 22 ++---------- .../minheapmerge/MinHeapmergeUnitTest.java | 35 +++++++++++++++++++ 3 files changed, 44 insertions(+), 27 deletions(-) create mode 100644 algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapmergeUnitTest.java 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 index d19ffa6e46..94b3abfbd6 100644 --- 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 @@ -3,16 +3,14 @@ package com.baeldung.algorithms.minheapmerge; public class MinHeap { HeapNode[] heapNodes; - int heapSize; public MinHeap(HeapNode heapNodes[]) { - this.heapSize = heapNodes.length; this.heapNodes = heapNodes; heapifyFromLastLeafsParent(); } void heapifyFromLastLeafsParent() { - int lastLeafsParentIndex = getParentNodeIndex(heapSize); + int lastLeafsParentIndex = getParentNodeIndex(heapNodes.length); while (lastLeafsParentIndex >= 0) { heapify(lastLeafsParentIndex); lastLeafsParentIndex--; @@ -23,12 +21,12 @@ public class MinHeap { int leftNodeIndex = getLeftNodeIndex(index); int rightNodeIndex = getRightNodeIndex(index); int smallestElementIndex = index; - if (leftNodeIndex < heapSize && heapNodes[leftNodeIndex].element < heapNodes[index].element) + if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) smallestElementIndex = leftNodeIndex; - - if (rightNodeIndex < heapSize && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) + + if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) smallestElementIndex = rightNodeIndex; - + if (smallestElementIndex != index) { swap(index, smallestElementIndex); heapify(smallestElementIndex); @@ -51,7 +49,7 @@ public class MinHeap { return heapNodes[0]; } - void hepifyFromRoot(HeapNode root) { + void heapifyFromRoot() { heapify(0); } diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeapMerge.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeapMerge.java index 62cb46321c..8cb375c3c6 100644 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeapMerge.java +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeapMerge.java @@ -2,12 +2,6 @@ package com.baeldung.algorithms.minheapmerge; public class MinHeapMerge { - static void printArray(int[] array) { - for (int i = 0; i < array.length; i++) { - System.out.print(array[i] + " "); - } - } - static int populateHeapNodesAndDetermineResultingArrayLength(int[][] array, HeapNode[] heapNodes) { int resultSize = 0; @@ -33,24 +27,14 @@ public class MinHeapMerge { } else { root.element = Integer.MAX_VALUE; } - minHeap.hepifyFromRoot(root); + minHeap.heapifyFromRoot(); } return resultingArray; } - static void merge(int[][] array) { + static int[] merge(int[][] array) { HeapNode[] heapNodes = new HeapNode[array.length]; int resultingArraySize = populateHeapNodesAndDetermineResultingArrayLength(array, heapNodes); - - int[] resultingArray = createMinHeapAndMergeArrays(array, heapNodes, resultingArraySize); - - printArray(resultingArray); - - } - - public static void main(String args[]) { - int[][] array = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 650, 200 }, { 3, 4 }, { 1001, 6456, 23000 } }; - - merge(array); + return createMinHeapAndMergeArrays(array, heapNodes, resultingArraySize); } } diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapmergeUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapmergeUnitTest.java new file mode 100644 index 0000000000..1d80651f92 --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapmergeUnitTest.java @@ -0,0 +1,35 @@ +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 MinHeapmergeUnitTest { + + 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 givenSortedArraysWhenMergedShouldReturnASingleSortedarray() { + int[] resultArray = MinHeapMerge.merge(inputArray); + assertThat(resultArray.length, is(equalTo(10))); + assertThat(resultArray, is(equalTo(expectedArray))); + } + + @Test + public void givenEmptyHeapNodesAndInputArrayWhenPopulatedShouldPopulateAndReturnResultArrayLength() { + int size = MinHeapMerge.populateHeapNodesAndDetermineResultingArrayLength(inputArray, new HeapNode[inputArray.length]); + assertThat(size, is(equalTo(10))); + } + + @Test + public void givenArrayAndHeapNodesAndResultArraySizeWhenMergedShouldReturnASingleSortedarray() { + HeapNode[] heapNodes = new HeapNode[inputArray.length]; + int size = MinHeapMerge.populateHeapNodesAndDetermineResultingArrayLength(inputArray, heapNodes); + int[] resultArray = MinHeapMerge.createMinHeapAndMergeArrays(inputArray, heapNodes, size); + assertThat(resultArray.length, is(equalTo(10))); + assertThat(resultArray, is(equalTo(expectedArray))); + } +} From 8b1de9300b5e48245502894f9aea1217b822abc5 Mon Sep 17 00:00:00 2001 From: TINO Date: Mon, 23 Dec 2019 18:11:22 +0300 Subject: [PATCH 04/44] BAEL - 3482 --- .../com/baeldung/algorithms/minheapmerge/MinHeap.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) 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 index 94b3abfbd6..cd6847e2bb 100644 --- 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 @@ -21,12 +21,12 @@ public class MinHeap { int leftNodeIndex = getLeftNodeIndex(index); int rightNodeIndex = getRightNodeIndex(index); int smallestElementIndex = index; - if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) + if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) { smallestElementIndex = leftNodeIndex; - - if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) + } + if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) { smallestElementIndex = rightNodeIndex; - + } if (smallestElementIndex != index) { swap(index, smallestElementIndex); heapify(smallestElementIndex); From 82f7a6c75aed94e7e72830a066ea10253fb6384c Mon Sep 17 00:00:00 2001 From: TINO Date: Mon, 23 Dec 2019 18:22:40 +0300 Subject: [PATCH 05/44] BAEL - 3482 --- ...pmergeUnitTest.java => MinHeapMergeUnitTest.java} | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) rename algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/{MinHeapmergeUnitTest.java => MinHeapMergeUnitTest.java} (74%) diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapmergeUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapMergeUnitTest.java similarity index 74% rename from algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapmergeUnitTest.java rename to algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapMergeUnitTest.java index 1d80651f92..6e4b8421c6 100644 --- a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapmergeUnitTest.java +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapMergeUnitTest.java @@ -6,29 +6,33 @@ import static org.junit.Assert.assertThat; import org.junit.Test; -public class MinHeapmergeUnitTest { +public class MinHeapMergeUnitTest { 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 givenSortedArraysWhenMergedShouldReturnASingleSortedarray() { + public void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() { int[] resultArray = MinHeapMerge.merge(inputArray); + assertThat(resultArray.length, is(equalTo(10))); assertThat(resultArray, is(equalTo(expectedArray))); } @Test - public void givenEmptyHeapNodesAndInputArrayWhenPopulatedShouldPopulateAndReturnResultArrayLength() { + public void givenEmptyHeapNodesAndInputArray_whenPopulated_thenShouldPopulateAndReturnResultArrayLength() { int size = MinHeapMerge.populateHeapNodesAndDetermineResultingArrayLength(inputArray, new HeapNode[inputArray.length]); + assertThat(size, is(equalTo(10))); } @Test - public void givenArrayAndHeapNodesAndResultArraySizeWhenMergedShouldReturnASingleSortedarray() { + public void givenArrayAndHeapNodesAndResultArraySize_whenMerged_thenShouldReturnASingleSortedarray() { HeapNode[] heapNodes = new HeapNode[inputArray.length]; int size = MinHeapMerge.populateHeapNodesAndDetermineResultingArrayLength(inputArray, heapNodes); + int[] resultArray = MinHeapMerge.createMinHeapAndMergeArrays(inputArray, heapNodes, size); + assertThat(resultArray.length, is(equalTo(10))); assertThat(resultArray, is(equalTo(expectedArray))); } From 9cd73de5cc9b770887f09b6cde4672762d666c57 Mon Sep 17 00:00:00 2001 From: Anshul BANSAL Date: Wed, 1 Jan 2020 16:00:57 +0200 Subject: [PATCH 06/44] BAEL-3596 - Asynchronous Method Calls in Java --- java-async/pom.xml | 109 +++++++--- .../main/java/com/baeldung/async/Async.java | 46 ----- .../com/baeldung/async/EAAsyncExample.java | 57 ++++++ .../java/com/baeldung/async/JavaAsync.java | 186 ++++++++++++++++++ .../com/baeldung/async/AsyncUnitTest.java | 9 - 5 files changed, 323 insertions(+), 84 deletions(-) delete mode 100644 java-async/src/main/java/com/baeldung/async/Async.java create mode 100644 java-async/src/main/java/com/baeldung/async/EAAsyncExample.java create mode 100644 java-async/src/main/java/com/baeldung/async/JavaAsync.java delete mode 100644 java-async/src/main/resources/com/baeldung/async/AsyncUnitTest.java diff --git a/java-async/pom.xml b/java-async/pom.xml index 56ff53321f..17cdabbb06 100644 --- a/java-async/pom.xml +++ b/java-async/pom.xml @@ -1,37 +1,88 @@ - 4.0.0 - java-async - 0.1.0-SNAPSHOT - java-async - jar + 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 + java-async + java-async + jar + 1.0 - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + - - - + + + com.jcabi + jcabi-aspects + 0.22.6 + - - java-async - - - src/main/resources - true - - - + + org.aspectj + aspectjrt + 1.9.5 + runtime + - - 1.0.3 - 3.6.1 - + + com.google.guava + guava + 28.1-jre + + + + org.cactoos + cactoos + 0.43 + + + + com.ea.async + ea-async + 1.2.3 + + + + + java-async + + + src/main/resources + true + + + + + + com.jcabi + jcabi-maven-plugin + 0.14.1 + + + + ajc + + + + + + org.aspectj + aspectjtools + 1.9.1 + + + org.aspectj + aspectjweaver + 1.9.1 + + + + + diff --git a/java-async/src/main/java/com/baeldung/async/Async.java b/java-async/src/main/java/com/baeldung/async/Async.java deleted file mode 100644 index b505077d10..0000000000 --- a/java-async/src/main/java/com/baeldung/async/Async.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.async; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -public class Async { - - public static void main(String[] args) { - System.out.println("hello world!!"); - - try { - Future completableFuture = calculateAsync(); - - String result = completableFuture.get(); - - System.out.println(result); - - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ExecutionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - CompletableFuture.runAsync(() -> { - System.out.println("This is Async"); - }); - } - - public static Future calculateAsync() throws InterruptedException { - CompletableFuture completableFuture = new CompletableFuture<>(); - - Executors.newCachedThreadPool().submit(() -> { - Thread.sleep(500); - completableFuture.complete("Hello"); - return null; - }); - - return completableFuture; - } - -} \ No newline at end of file diff --git a/java-async/src/main/java/com/baeldung/async/EAAsyncExample.java b/java-async/src/main/java/com/baeldung/async/EAAsyncExample.java new file mode 100644 index 0000000000..c7c893e731 --- /dev/null +++ b/java-async/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/java-async/src/main/java/com/baeldung/async/JavaAsync.java b/java-async/src/main/java/com/baeldung/async/JavaAsync.java new file mode 100644 index 0000000000..c1c2c98550 --- /dev/null +++ b/java-async/src/main/java/com/baeldung/async/JavaAsync.java @@ -0,0 +1,186 @@ +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.FutureCallback; +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/java-async/src/main/resources/com/baeldung/async/AsyncUnitTest.java b/java-async/src/main/resources/com/baeldung/async/AsyncUnitTest.java deleted file mode 100644 index 57a61dbfe2..0000000000 --- a/java-async/src/main/resources/com/baeldung/async/AsyncUnitTest.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.async; - -public class AsyncUnitTest { - - public static void main(String[] args) { - System.out.println("hello"); - } - -} \ No newline at end of file From 7b5f3dcd8c6d161265631955912a1ee30e2a1fc1 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Wed, 1 Jan 2020 16:04:42 +0200 Subject: [PATCH 07/44] space instead of tab --- java-async/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/java-async/pom.xml b/java-async/pom.xml index 17cdabbb06..ead558aeeb 100644 --- a/java-async/pom.xml +++ b/java-async/pom.xml @@ -46,6 +46,7 @@ ea-async 1.2.3 + From fde817c5e28f11fb041575cbfed34bb72dd3eb23 Mon Sep 17 00:00:00 2001 From: Anshul BANSAL Date: Wed, 1 Jan 2020 16:14:06 +0200 Subject: [PATCH 08/44] added java-async to the pom.xml --- pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pom.xml b/pom.xml index 63d4e04291..ded191b574 100644 --- a/pom.xml +++ b/pom.xml @@ -506,6 +506,7 @@ jackson-conversions jackson-conversions-2 jackson-custom-conversions +java-async java-collections-conversions java-collections-conversions-2 java-collections-maps @@ -1145,6 +1146,7 @@ jackson-conversions jackson-conversions-2 jackson-custom-conversions +java-async java-collections-conversions java-collections-conversions-2 java-collections-maps From 476504220ddac453e0de7bcf7af68836f647fb21 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Wed, 1 Jan 2020 16:17:46 +0200 Subject: [PATCH 09/44] code indentation --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index ded191b574..d48ade6a7c 100644 --- a/pom.xml +++ b/pom.xml @@ -506,7 +506,7 @@ jackson-conversions jackson-conversions-2 jackson-custom-conversions -java-async + java-async java-collections-conversions java-collections-conversions-2 java-collections-maps @@ -1146,7 +1146,7 @@ jackson-conversions jackson-conversions-2 jackson-custom-conversions -java-async + java-async java-collections-conversions java-collections-conversions-2 java-collections-maps From 82698d28d0cf8512807f6982022288327fb9f870 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Wed, 1 Jan 2020 16:19:37 +0200 Subject: [PATCH 10/44] Update pom.xml --- java-async/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/java-async/pom.xml b/java-async/pom.xml index ead558aeeb..17cdabbb06 100644 --- a/java-async/pom.xml +++ b/java-async/pom.xml @@ -46,7 +46,6 @@ ea-async 1.2.3 - From 7de715c611528c7afa5d57395cc0e631d58bc153 Mon Sep 17 00:00:00 2001 From: Gang Date: Wed, 1 Jan 2020 21:34:48 -0700 Subject: [PATCH 11/44] BAEL-3656 Read Numeric Strings in Excel Cells as a String with Apache POI --- apache-poi/pom.xml | 2 +- .../poi/excel/ExcelCellFormatter.java | 20 +++ .../ExcelCellFormatterIntegrationTest.java | 128 ++++++++++++++++++ 3 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 apache-poi/src/main/java/com/baeldung/poi/excel/ExcelCellFormatter.java create mode 100644 apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterIntegrationTest.java 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/test/java/com/baeldung/poi/excel/ExcelCellFormatterIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterIntegrationTest.java new file mode 100644 index 0000000000..889ee1b527 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterIntegrationTest.java @@ -0,0 +1,128 @@ +package com.baeldung.poi.excel; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.DataFormat; +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.After; +import org.junit.Before; +import org.junit.Test; + +public class ExcelCellFormatterIntegrationTest { + private static int STRING_CELL_INDEX = 0; + private static int BOOLEAN_CELL_INDEX = 1; + private static int RAW_NUMERIC_CELL_INDEX = 2; + private static int FORMATTED_NUMERIC_CELL_INDEX = 3; + private static int FORMULA_CELL_INDEX = 4; + + private String fileLocation; + + @Before + public void generateExcelFile() throws IOException { + + Workbook workbook = new XSSFWorkbook(); + + Sheet sheet = workbook.createSheet("Test"); + Row row = sheet.createRow(0); + Cell cell = row.createCell(STRING_CELL_INDEX); + cell.setCellValue("String Test"); // STRING cell + + cell = row.createCell(BOOLEAN_CELL_INDEX); + cell.setCellValue(true); // BOOLEAN cell + + cell = row.createCell(RAW_NUMERIC_CELL_INDEX); + cell.setCellValue(1234.5678); // NUMERIC cell + + cell = row.createCell(FORMATTED_NUMERIC_CELL_INDEX); + cell.setCellValue(1234.5678); + CellStyle curStyle = workbook.createCellStyle(); + DataFormat df = workbook.createDataFormat(); + curStyle.setDataFormat(df.getFormat("$#,##0.00")); + cell.setCellStyle(curStyle); // NUMERIC cell with format rule + + cell = row.createCell(FORMULA_CELL_INDEX); + cell.setCellFormula("SUM(C1:D1)"); // FORMULA cell + + File tempFile = File.createTempFile("ExcelCellFormatterIntegrationTest", ".xlsx"); + + fileLocation = tempFile.getAbsolutePath(); + + FileOutputStream outputStream = new FileOutputStream(fileLocation); + workbook.write(outputStream); + workbook.close(); + outputStream.close(); + } + + @Test + public void gvieStringCell_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 gvieBooleanCell_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 gvieNumericCell_whenGetCellStringValue_thenReturnNumericStringValue() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + + ExcelCellFormatter formatter = new ExcelCellFormatter(); + assertEquals("1234.5678", formatter.getCellStringValue(row.getCell(RAW_NUMERIC_CELL_INDEX))); + assertEquals("$1,234.57", formatter.getCellStringValue(row.getCell(FORMATTED_NUMERIC_CELL_INDEX))); + workbook.close(); + } + + @Test + public void gvieFormualCell_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(C1:D1)", formatter.getCellStringValue(row.getCell(FORMULA_CELL_INDEX))); + workbook.close(); + } + + @Test + public void gvieFormualCell_whenGetCellStringValueForFormula_thenReturnOriginalFormulatring() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + + ExcelCellFormatter formatter = new ExcelCellFormatter(); + assertEquals("2469.1356", formatter.getCellStringValueWithFormula(row.getCell(FORMULA_CELL_INDEX), workbook)); + workbook.close(); + } + + @After + public void cleanup() { + File testFile = new File(fileLocation); + if (testFile.exists()) { + testFile.deleteOnExit(); + } + } +} \ No newline at end of file From 0e79e57e0b67bcbf8b4fbe65f0b8a478ad35fd6f Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Fri, 3 Jan 2020 14:07:40 +0200 Subject: [PATCH 12/44] pom.xml merged --- pom.xml | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/pom.xml b/pom.xml index 2513380066..7df3ce208d 100644 --- a/pom.xml +++ b/pom.xml @@ -500,13 +500,6 @@ image-processing immutables - jackson - jackson-simple - jackson-annotations - jackson-exceptions - jackson-conversions - jackson-conversions-2 - jackson-custom-conversions jackson-modules java-async java-collections-conversions @@ -1143,13 +1136,6 @@ image-processing immutables - jackson - jackson-simple - jackson-annotations - jackson-exceptions - jackson-conversions - jackson-conversions-2 - jackson-custom-conversions jackson-modules java-async java-collections-conversions From 7ea496ba09ea03cea44a8244879827e07be79b67 Mon Sep 17 00:00:00 2001 From: TINO Date: Sat, 4 Jan 2020 12:38:37 +0300 Subject: [PATCH 13/44] BAEL-3482 Code re-factor --- .../algorithms/minheapmerge/MinHeap.java | 27 +++++++++++++ .../algorithms/minheapmerge/MinHeapMerge.java | 40 ------------------- .../minheapmerge/MinHeapMergeUnitTest.java | 39 ------------------ .../minheapmerge/MinHeapUnitTest.java | 22 ++++++++++ 4 files changed, 49 insertions(+), 79 deletions(-) delete mode 100644 algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeapMerge.java delete mode 100644 algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapMergeUnitTest.java create mode 100644 algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapUnitTest.java 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 index cd6847e2bb..b77ce43160 100644 --- 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 @@ -58,4 +58,31 @@ public class MinHeap { 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/main/java/com/baeldung/algorithms/minheapmerge/MinHeapMerge.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeapMerge.java deleted file mode 100644 index 8cb375c3c6..0000000000 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeapMerge.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.algorithms.minheapmerge; - -public class MinHeapMerge { - - static int populateHeapNodesAndDetermineResultingArrayLength(int[][] array, HeapNode[] heapNodes) { - int resultSize = 0; - - for (int i = 0; i < array.length; i++) { - HeapNode node = new HeapNode(array[i][0], i); - heapNodes[i] = node; - resultSize += array[i].length; - } - return resultSize; - } - - static int[] createMinHeapAndMergeArrays(int[][] array, HeapNode[] heapNodes, int resultingArraySize) { - - 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; - } - - static int[] merge(int[][] array) { - HeapNode[] heapNodes = new HeapNode[array.length]; - int resultingArraySize = populateHeapNodesAndDetermineResultingArrayLength(array, heapNodes); - return createMinHeapAndMergeArrays(array, heapNodes, resultingArraySize); - } -} diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapMergeUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapMergeUnitTest.java deleted file mode 100644 index 6e4b8421c6..0000000000 --- a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapMergeUnitTest.java +++ /dev/null @@ -1,39 +0,0 @@ -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 MinHeapMergeUnitTest { - - 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 = MinHeapMerge.merge(inputArray); - - assertThat(resultArray.length, is(equalTo(10))); - assertThat(resultArray, is(equalTo(expectedArray))); - } - - @Test - public void givenEmptyHeapNodesAndInputArray_whenPopulated_thenShouldPopulateAndReturnResultArrayLength() { - int size = MinHeapMerge.populateHeapNodesAndDetermineResultingArrayLength(inputArray, new HeapNode[inputArray.length]); - - assertThat(size, is(equalTo(10))); - } - - @Test - public void givenArrayAndHeapNodesAndResultArraySize_whenMerged_thenShouldReturnASingleSortedarray() { - HeapNode[] heapNodes = new HeapNode[inputArray.length]; - int size = MinHeapMerge.populateHeapNodesAndDetermineResultingArrayLength(inputArray, heapNodes); - - int[] resultArray = MinHeapMerge.createMinHeapAndMergeArrays(inputArray, heapNodes, size); - - assertThat(resultArray.length, is(equalTo(10))); - assertThat(resultArray, is(equalTo(expectedArray))); - } -} 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))); + } + +} From 9a2b5b9ca3f440878604a7664f99e7fc65a8b361 Mon Sep 17 00:00:00 2001 From: Anshul BANSAL Date: Sat, 4 Jan 2020 14:37:34 +0200 Subject: [PATCH 14/44] BAEL-3596 - code moved to core-java-concurrency-advanced-3 --- .../core-java-concurrency-advanced-3/pom.xml | 56 ++++++++++++ .../com/baeldung/async/EAAsyncExample.java | 0 .../java/com/baeldung/async/JavaAsync.java | 0 java-async/pom.xml | 88 ------------------- pom.xml | 2 - 5 files changed, 56 insertions(+), 90 deletions(-) rename {java-async => core-java-modules/core-java-concurrency-advanced-3}/src/main/java/com/baeldung/async/EAAsyncExample.java (100%) rename {java-async => core-java-modules/core-java-concurrency-advanced-3}/src/main/java/com/baeldung/async/JavaAsync.java (100%) delete mode 100644 java-async/pom.xml 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..6b9c8b2d05 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,38 @@ ${assertj.version} test + + + com.jcabi + jcabi-aspects + 0.22.6 + + + + org.aspectj + aspectjrt + 1.9.5 + runtime + + + + com.google.guava + guava + 28.1-jre + + + + org.cactoos + cactoos + 0.43 + + + + com.ea.async + ea-async + 1.2.3 + + @@ -36,6 +68,30 @@ ${maven.compiler.target} + + com.jcabi + jcabi-maven-plugin + 0.14.1 + + + + ajc + + + + + + org.aspectj + aspectjtools + 1.9.1 + + + org.aspectj + aspectjweaver + 1.9.1 + + + diff --git a/java-async/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 similarity index 100% rename from java-async/src/main/java/com/baeldung/async/EAAsyncExample.java rename to core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/EAAsyncExample.java diff --git a/java-async/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 similarity index 100% rename from java-async/src/main/java/com/baeldung/async/JavaAsync.java rename to core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/JavaAsync.java diff --git a/java-async/pom.xml b/java-async/pom.xml deleted file mode 100644 index 17cdabbb06..0000000000 --- a/java-async/pom.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - 4.0.0 - java-async - java-async - jar - 1.0 - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - com.jcabi - jcabi-aspects - 0.22.6 - - - - org.aspectj - aspectjrt - 1.9.5 - runtime - - - - com.google.guava - guava - 28.1-jre - - - - org.cactoos - cactoos - 0.43 - - - - com.ea.async - ea-async - 1.2.3 - - - - - java-async - - - src/main/resources - true - - - - - - com.jcabi - jcabi-maven-plugin - 0.14.1 - - - - ajc - - - - - - org.aspectj - aspectjtools - 1.9.1 - - - org.aspectj - aspectjweaver - 1.9.1 - - - - - - - diff --git a/pom.xml b/pom.xml index 7df3ce208d..cb2fe5a929 100644 --- a/pom.xml +++ b/pom.xml @@ -501,7 +501,6 @@ immutables jackson-modules - java-async java-collections-conversions java-collections-conversions-2 java-collections-maps @@ -1137,7 +1136,6 @@ immutables jackson-modules - java-async java-collections-conversions java-collections-conversions-2 java-collections-maps From 683cb35880514cc9b069efdf600845f737edc632 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Sat, 4 Jan 2020 14:38:39 +0200 Subject: [PATCH 15/44] code indentation --- core-java-modules/core-java-concurrency-advanced-3/pom.xml | 1 - 1 file changed, 1 deletion(-) 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 6b9c8b2d05..e4a10e223c 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-3/pom.xml @@ -54,7 +54,6 @@ ea-async 1.2.3 - From d790355eda3f4cf99524720ce2f0eb58ad336d0b Mon Sep 17 00:00:00 2001 From: Anshul BANSAL Date: Sat, 4 Jan 2020 14:41:27 +0200 Subject: [PATCH 16/44] Code indentation --- .../core-java-concurrency-advanced-3/pom.xml | 96 +++++++++---------- 1 file changed, 48 insertions(+), 48 deletions(-) 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 e4a10e223c..4eb26ed4db 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-3/pom.xml @@ -1,30 +1,30 @@ + 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-concurrency-advanced-3 - 0.1.0-SNAPSHOT - core-java-concurrency-advanced-3 - jar + 4.0.0 + core-java-concurrency-advanced-3 + 0.1.0-SNAPSHOT + core-java-concurrency-advanced-3 + jar - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + - - - org.assertj - assertj-core - ${assertj.version} - test - - - + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.jcabi jcabi-aspects 0.22.6 @@ -54,20 +54,20 @@ ea-async 1.2.3 - + - - core-java-concurrency-advanced-3 - - - org.apache.maven.plugins - maven-compiler-plugin - - ${maven.compiler.source} - ${maven.compiler.target} - - - + + core-java-concurrency-advanced-3 + + + org.apache.maven.plugins + maven-compiler-plugin + + ${maven.compiler.source} + ${maven.compiler.target} + + + com.jcabi jcabi-maven-plugin 0.14.1 @@ -91,19 +91,19 @@ - - - - src/main/resources - true - - - + + + + src/main/resources + true + + + - - 3.14.0 - 1.8 - 1.8 - + + 3.14.0 + 1.8 + 1.8 + From 63dbe2dce0f46b9230b343a10fee2ca4f947150f Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Sat, 4 Jan 2020 14:42:04 +0200 Subject: [PATCH 17/44] pom.xml code indentation --- core-java-modules/core-java-concurrency-advanced-3/pom.xml | 1 + 1 file changed, 1 insertion(+) 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 4eb26ed4db..26c01dea50 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-3/pom.xml @@ -67,6 +67,7 @@ ${maven.compiler.target} + com.jcabi jcabi-maven-plugin From d85d65a58188367684534f906853b1177ab3fd44 Mon Sep 17 00:00:00 2001 From: Anshul BANSAL Date: Sat, 4 Jan 2020 14:49:57 +0200 Subject: [PATCH 18/44] pom.xml code indentation --- core-java-modules/core-java-concurrency-advanced-3/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 26c01dea50..bbb75be033 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-3/pom.xml @@ -67,7 +67,7 @@ ${maven.compiler.target} - + com.jcabi jcabi-maven-plugin From df1f565779cf2af06ac6df2b9ac03f4f6705b214 Mon Sep 17 00:00:00 2001 From: Anshul BANSAL Date: Sat, 4 Jan 2020 14:57:29 +0200 Subject: [PATCH 19/44] 4 spaces code indentation --- .../core-java-concurrency-advanced-3/pom.xml | 199 +++++++++--------- 1 file changed, 99 insertions(+), 100 deletions(-) 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 bbb75be033..e5f3970de7 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-3/pom.xml @@ -1,110 +1,109 @@ + 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-concurrency-advanced-3 - 0.1.0-SNAPSHOT - core-java-concurrency-advanced-3 - jar + 4.0.0 + core-java-concurrency-advanced-3 + 0.1.0-SNAPSHOT + core-java-concurrency-advanced-3 + jar - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + - - - org.assertj - assertj-core - ${assertj.version} - test - + + + org.assertj + assertj-core + ${assertj.version} + test + + + + com.jcabi + jcabi-aspects + 0.22.6 + + + + org.aspectj + aspectjrt + 1.9.5 + runtime + + + + com.google.guava + guava + 28.1-jre + + + + org.cactoos + cactoos + 0.43 + - - com.jcabi - jcabi-aspects - 0.22.6 - + + com.ea.async + ea-async + 1.2.3 + + - - org.aspectj - aspectjrt - 1.9.5 - runtime - + + core-java-concurrency-advanced-3 + + + org.apache.maven.plugins + maven-compiler-plugin + + ${maven.compiler.source} + ${maven.compiler.target} + + + + com.jcabi + jcabi-maven-plugin + 0.14.1 + + + + ajc + + + + + + org.aspectj + aspectjtools + 1.9.1 + + + org.aspectj + aspectjweaver + 1.9.1 + + + + + + + src/main/resources + true + + + - - com.google.guava - guava - 28.1-jre - - - - org.cactoos - cactoos - 0.43 - - - - com.ea.async - ea-async - 1.2.3 - - - - - core-java-concurrency-advanced-3 - - - org.apache.maven.plugins - maven-compiler-plugin - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - com.jcabi - jcabi-maven-plugin - 0.14.1 - - - - ajc - - - - - - org.aspectj - aspectjtools - 1.9.1 - - - org.aspectj - aspectjweaver - 1.9.1 - - - - - - - src/main/resources - true - - - - - - 3.14.0 - 1.8 - 1.8 - + + 3.14.0 + 1.8 + 1.8 + From 0021e7849adc3c0d7bbeec8a45d3a75e906a555d Mon Sep 17 00:00:00 2001 From: Anshul BANSAL Date: Sat, 4 Jan 2020 14:59:27 +0200 Subject: [PATCH 20/44] organized imports --- .../src/main/java/com/baeldung/async/JavaAsync.java | 1 - 1 file changed, 1 deletion(-) 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 index c1c2c98550..4f308250e2 100644 --- 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 @@ -11,7 +11,6 @@ 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.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; From f484bcb498e131b232a4650a4d0bf70b6a7740df Mon Sep 17 00:00:00 2001 From: Gang Date: Sun, 5 Jan 2020 00:19:49 -0700 Subject: [PATCH 21/44] BAEL-3656 Change the integration test into unit test. --- .../resources/ExcelCellFormatterTest.xlsx | Bin 0 -> 3375 bytes .../ExcelCellFormatterIntegrationTest.java | 128 ------------------ .../poi/excel/ExcelCellFormatterUnitTest.java | 87 ++++++++++++ 3 files changed, 87 insertions(+), 128 deletions(-) create mode 100644 apache-poi/src/main/resources/ExcelCellFormatterTest.xlsx delete mode 100644 apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterIntegrationTest.java create mode 100644 apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterUnitTest.java diff --git a/apache-poi/src/main/resources/ExcelCellFormatterTest.xlsx b/apache-poi/src/main/resources/ExcelCellFormatterTest.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..54e8734d58f7e14ba90c1bd65417142c460db369 GIT binary patch literal 3375 zcmaJ@2{@E%8y-f+P?4l59h3=8#W*8tc4`>QjHHm=ScWmiR*WUokbO_tvUEsMvNo~| z*&-o(nIj^Sts_gwKcoLY=J-!N-}TKmb6wx_&ig#?{oMDBMgiIQ02~|~fJ(q|G=M4g z)4!W(5L`X6uAY`gK5keKbBSwsm$D0OuJv%9^`w@5n9L&j;(;Iyp=SOEi@+Nc$Ja9FKfyu`i1R)Z=a;jzn{{ z-T6dwlxTHaxm4O&elBP)Zan{n2B!DkbV^vt(;)wjXS%Bw6?pkHGxmoE=dK>7g%;<> zj+|;xf8Mf?Zx#v8Z4wk#Y%9JEUL@%+rUZlzTwVxqYdqrPY@nOP28ngnzivF6yO8&; zR^2p!{N#B?AQ7?@ILIv=Zhc6|J?uTnpq2%V0&(~zz9cHL002kW008t)d(TDhy`?+W z#Y0kp@mUy8#WlcplPw!3X>v1Gk(i3xzfa;LXIZ4pv~_LT28NQWH`*o4P@Dpv#i9P2 zpl)xKQ0;1rL`F`K*PGyM$HCPBfosZ2k7iX5P$%6+k?hAB0xJBo!S`Jgsd?G3WBkAn zB&DA+5X72H-rqPhB?n40ov;uq6=ka!^h8B zFg3g|Dn_#wJYMuy@?IB9pq5EXO$wm;^V3ytqKgosUr%?c7VF3#9{mp1%l2~g!4(9> z1pYK_ilEaUlMMtb@U3TCa7>j54fwM%dXpFFTRldvT$}Y*z2Tw1VMnkUC_@a2h|EzF52g z*XtOSAGm$qW_PmilrRUoOP;(yqBct)ftHQUu zzmwi5oXo$fP5XE@?fLjpKKa9M>2py<$P7&UJ^ph`l)@I<5|k`-A;`HElv8|cC>C$d z*>;0id9^8(uRmc)|FXHay;WV%zZN|vXFrCU7(FL{c6eC1 zy)CagqeddOXI%T$4GlrGD5kDHG%CtZEVQ@Rt3}6Z3?A|GbHO^d??&k@Rr1cE{RX@N{=_ zb?{*HQ7KAoZ!nxkYgv?*b*Fka1>ThS6u!VZ%5oTz1x{CYfD8UfA+CPkTzy@hDVHjX z1>X{oGd=?uRo)ZS%$_m4;TF_4bJbW=FH@%Pch(Z(Wm(F`v$QAD@COo?G^fPEEec9` zZcik+FPg$*#8ILuEtnBHsCL6%^iMQx`+u zZow~6vFE=9dHT3uw<<}GS0XeB^N^QyHn_v8sS9YWq?z4GSG=a;jXvqL51t!GT^FgU zt+7gbkzU|EIy+7a4apgZF}#Pk+*}4*@J_I1E9i=RSoC79`I~j&sXM@ec}ZN@DE^^iMUcoko#zpEvw01B5eL@oR@-ypBTlsX@J;C7 zR%lHs$3UkNeTdW-H!Ef0#^}jew2+Hl$WC4%G2n4yQ?>ebuUaDnPQ~(6x^c7*7?fFx zwdR~&6MFz-D^-S^n)_Dii$}g&v}ogj>nj%KhqXl5f?3O1j_xIT3e9jY4P;A)T;k6Z zYMi#L@9g9i)zvu`sE7J|KxXqGf7DFUW<&aBYgE3JjjzB5u!~Y4m6xPgS2pv^)_tw9 zSC%obEQ(|4R&<PO9v#4mQeglJmkn163S8*VoU~zrP1BQen ztjmSfPLG*4 zyl1cfo#pnc=>sfEPLpAXFeAl>M`vb$VU5EFO-`?#f%ePJY<1;e?Z)Xrdd*jUIe~|N zbmfO^G56+&gvIGO(16c?e9 z^Ca$4T0lpFPxCR6gpeX9s_?F8kv)4YmJMW=tu&RiRHU+iHUqAGujPCSRiIHOx>~Vv z$bwa>DH!Y^xyK=wGWD$8V!C9v%$nOgaOmP&+Ms*K_2X|oXNNqE_${Sc5?BD#uCem# zGHlCzFhWtVUyn&%3)sEV@*aP#o6EcEdPwz=5`~Dau^au5SN`~ZzjmWH&`lnx-gCj{ zx8X8W09ziUs&Z+9i-8z2P%*BDUOD2Ih=FV)#={Yd_4J?<75yQ##q{xJ1|h0EH~-XI z=T7zShL|`O-eq?zz}pJlg*f|LT2gUs-tXP*-e;?+Y zv-r_-!cq31nbH+R&1Cm;fn-(K)#Cw^6MMo>ogebld?0c}su~KK@%kR}*W%pR=f|3V&LnumF(cPX@5m+_x@p0~Z-xA8gEPF)_vI^cI zAAN72d3a3;cZaHT_Ypc->oDe$C*q^i3zLE~!A`xgC24{mp*qOo>CyH@&?j8aSL^cX zxhWxzz%9XDBzV>!=_r-mIt><9KESrOWp-W+Z~M>q7pIFx{c{0kd%`ei+u=w5OD4Ov zGm+T_Fx<;_q|o=d)64A4X4XH3RoD(EAXE1LjKj`!X0>66y!oQz-p0XhyWcmMzZ literal 0 HcmV?d00001 diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterIntegrationTest.java deleted file mode 100644 index 889ee1b527..0000000000 --- a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterIntegrationTest.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.baeldung.poi.excel; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.DataFormat; -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.After; -import org.junit.Before; -import org.junit.Test; - -public class ExcelCellFormatterIntegrationTest { - private static int STRING_CELL_INDEX = 0; - private static int BOOLEAN_CELL_INDEX = 1; - private static int RAW_NUMERIC_CELL_INDEX = 2; - private static int FORMATTED_NUMERIC_CELL_INDEX = 3; - private static int FORMULA_CELL_INDEX = 4; - - private String fileLocation; - - @Before - public void generateExcelFile() throws IOException { - - Workbook workbook = new XSSFWorkbook(); - - Sheet sheet = workbook.createSheet("Test"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(STRING_CELL_INDEX); - cell.setCellValue("String Test"); // STRING cell - - cell = row.createCell(BOOLEAN_CELL_INDEX); - cell.setCellValue(true); // BOOLEAN cell - - cell = row.createCell(RAW_NUMERIC_CELL_INDEX); - cell.setCellValue(1234.5678); // NUMERIC cell - - cell = row.createCell(FORMATTED_NUMERIC_CELL_INDEX); - cell.setCellValue(1234.5678); - CellStyle curStyle = workbook.createCellStyle(); - DataFormat df = workbook.createDataFormat(); - curStyle.setDataFormat(df.getFormat("$#,##0.00")); - cell.setCellStyle(curStyle); // NUMERIC cell with format rule - - cell = row.createCell(FORMULA_CELL_INDEX); - cell.setCellFormula("SUM(C1:D1)"); // FORMULA cell - - File tempFile = File.createTempFile("ExcelCellFormatterIntegrationTest", ".xlsx"); - - fileLocation = tempFile.getAbsolutePath(); - - FileOutputStream outputStream = new FileOutputStream(fileLocation); - workbook.write(outputStream); - workbook.close(); - outputStream.close(); - } - - @Test - public void gvieStringCell_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 gvieBooleanCell_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 gvieNumericCell_whenGetCellStringValue_thenReturnNumericStringValue() throws IOException { - Workbook workbook = new XSSFWorkbook(fileLocation); - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(0); - - ExcelCellFormatter formatter = new ExcelCellFormatter(); - assertEquals("1234.5678", formatter.getCellStringValue(row.getCell(RAW_NUMERIC_CELL_INDEX))); - assertEquals("$1,234.57", formatter.getCellStringValue(row.getCell(FORMATTED_NUMERIC_CELL_INDEX))); - workbook.close(); - } - - @Test - public void gvieFormualCell_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(C1:D1)", formatter.getCellStringValue(row.getCell(FORMULA_CELL_INDEX))); - workbook.close(); - } - - @Test - public void gvieFormualCell_whenGetCellStringValueForFormula_thenReturnOriginalFormulatring() throws IOException { - Workbook workbook = new XSSFWorkbook(fileLocation); - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(0); - - ExcelCellFormatter formatter = new ExcelCellFormatter(); - assertEquals("2469.1356", formatter.getCellStringValueWithFormula(row.getCell(FORMULA_CELL_INDEX), workbook)); - workbook.close(); - } - - @After - public void cleanup() { - File testFile = new File(fileLocation); - if (testFile.exists()) { - testFile.deleteOnExit(); - } - } -} \ No newline at end of file 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..adedf951d6 --- /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 gvieStringCell_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 gvieBooleanCell_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 gvieNumericCell_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 gvieFormualCell_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 gvieFormualCell_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 From 3c986727c047139503f6ee39ea300fcbc4c88973 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Sun, 5 Jan 2020 11:51:57 +0100 Subject: [PATCH 22/44] BAEL-19956: Use jar packaging type --- spring-scheduling/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 64365791dd81f94c840e61f8e9c3bfac8790ee9f Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Mon, 6 Jan 2020 10:49:41 +0200 Subject: [PATCH 23/44] review changes --- .../src/main/java/com/baeldung/async/JavaAsync.java | 2 -- 1 file changed, 2 deletions(-) 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 index 4f308250e2..6f36f46154 100644 --- 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 @@ -127,7 +127,6 @@ public class JavaAsync { } /** - * * Finds factorial of a number using Async of Cactoos * @param number * @return @@ -170,7 +169,6 @@ public class JavaAsync { } /** - * * Finds factorial of a number using @Async of jcabi-aspects * @param number * @return From 73e7543a9d228b8ecc348285e924725a4271c83d Mon Sep 17 00:00:00 2001 From: kwoyke Date: Mon, 6 Jan 2020 21:36:38 +0100 Subject: [PATCH 24/44] BAEL-3693: Rename test methods (#8482) --- .../baeldung/ternaryoperator/TernaryOperatorUnitTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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; From 721c60966fbd96499d673cd9ef1f0ce428603e81 Mon Sep 17 00:00:00 2001 From: sandip singh Date: Tue, 7 Jan 2020 09:25:52 +0530 Subject: [PATCH 25/44] BAEL-3283 - Moved the code to a single package meant for the themes tutorial. --- .../com/baeldung/{ => themes}/config/DataSourceConfig.java | 4 ++-- .../java/com/baeldung/{ => themes}/config/InitSecurity.java | 2 +- .../com/baeldung/{ => themes}/config/SecurityConfig.java | 2 +- .../com/baeldung/{ => themes}/config/ThemeMVCConfig.java | 4 ++-- .../com/baeldung/{ => themes}/config/WebInitializer.java | 2 +- .../baeldung/{ => themes}/controllers/AppController.java | 2 +- .../com/baeldung/{ => themes}/domain/UserPreference.java | 2 +- .../{ => themes}/repository/UserPreferenceRepository.java | 4 ++-- .../resolver/UserPreferenceThemeResolver.java | 6 +++--- 9 files changed, 14 insertions(+), 14 deletions(-) rename spring-mvc-views/src/main/java/com/baeldung/{ => themes}/config/DataSourceConfig.java (94%) rename spring-mvc-views/src/main/java/com/baeldung/{ => themes}/config/InitSecurity.java (82%) rename spring-mvc-views/src/main/java/com/baeldung/{ => themes}/config/SecurityConfig.java (98%) rename spring-mvc-views/src/main/java/com/baeldung/{ => themes}/config/ThemeMVCConfig.java (94%) rename spring-mvc-views/src/main/java/com/baeldung/{ => themes}/config/WebInitializer.java (96%) rename spring-mvc-views/src/main/java/com/baeldung/{ => themes}/controllers/AppController.java (85%) rename spring-mvc-views/src/main/java/com/baeldung/{ => themes}/domain/UserPreference.java (93%) rename spring-mvc-views/src/main/java/com/baeldung/{ => themes}/repository/UserPreferenceRepository.java (66%) rename spring-mvc-views/src/main/java/com/baeldung/{theme => themes}/resolver/UserPreferenceThemeResolver.java (95%) 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; From 9873c70dc4e598380382490a1d0198b0c154198d Mon Sep 17 00:00:00 2001 From: "m.raheem" Date: Tue, 7 Jan 2020 21:28:46 +0200 Subject: [PATCH 26/44] modifying partialMocking() --- .../LoginControllerIntegrationTest.java | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) 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..cb490926f8 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,36 @@ 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 loginDao#login() call + loginDao.login(userForm); result = 1; + + //no expectation for partialLoginService#login() so that real implementation is used + + //mocking partialLoginService#setCurrentUser() partialLoginService.setCurrentUser("foo"); }}; String login = loginController.login(userForm); Assert.assertEquals("OK", login); - // verify mocked call - new FullVerifications(partialLoginService) { - }; - new FullVerifications(loginDao) { + // verify that mocked partialLoginService#setCurrentUser("foo") is called + new Verifications() { + { + partialLoginService.setCurrentUser("foo"); + } }; + } } From 9bfe9a406a202ec8ea4de69a87a8a0f41d1efa44 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 8 Jan 2020 21:01:45 +0200 Subject: [PATCH 27/44] Update WebserviceUnitTest.groovy --- .../groovy/com/baeldung/webservice/WebserviceUnitTest.groovy | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy index 302959d0d9..50433ea890 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 WebserviceUnitTest extends GroovyTestCase { assert stories.size() == 5 } + /* see BAEL-3753 void test_whenConsumingSoap_thenReceiveResponse() { def url = "http://www.dataaccess.com/webservicesserver/numberconversion.wso" def soapClient = new SOAPClient(url) @@ -89,6 +90,7 @@ class WebserviceUnitTest extends GroovyTestCase { def words = response.NumberToWordsResponse assert words == "one thousand two hundred and thirty four " } + */ void test_whenConsumingRestGet_thenReceiveResponse() { def path = "/get" @@ -149,4 +151,4 @@ class WebserviceUnitTest extends GroovyTestCase { assert e?.response?.statusCode != 200 } } -} \ No newline at end of file +} From 1beacb0ce8b4e57b45d82a9bb22f700631d6fa11 Mon Sep 17 00:00:00 2001 From: "m.raheem" Date: Wed, 8 Jan 2020 21:07:33 +0200 Subject: [PATCH 28/44] first review round changes --- .../jmockit/LoginControllerIntegrationTest.java | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) 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 cb490926f8..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 @@ -133,7 +133,6 @@ public class LoginControllerIntegrationTest { @Test public void partialMocking() { - LoginService partialLoginService = new LoginService(); partialLoginService.setLoginDao(loginDao); loginController.loginService = partialLoginService; @@ -142,24 +141,22 @@ public class LoginControllerIntegrationTest { userForm.username = "foo"; new Expectations(partialLoginService) {{ - //let's mock loginDao#login() call + // let's mock DAO call loginDao.login(userForm); result = 1; - //no expectation for partialLoginService#login() so that real implementation is used + // no expectation for login method so that real implementation is used - //mocking partialLoginService#setCurrentUser() + // mock setCurrentUser call partialLoginService.setCurrentUser("foo"); }}; String login = loginController.login(userForm); Assert.assertEquals("OK", login); - // verify that mocked partialLoginService#setCurrentUser("foo") is called - new Verifications() { - { - partialLoginService.setCurrentUser("foo"); - } - }; + // verify mocked call + new Verifications() {{ + partialLoginService.setCurrentUser("foo"); + }}; } } From be324f6d097fa3b84473c16c4d45449a65cd6efa Mon Sep 17 00:00:00 2001 From: Gang Date: Wed, 8 Jan 2020 20:07:32 -0700 Subject: [PATCH 29/44] BAEL-3656 Fix typos in the unit test names. --- .../baeldung/poi/excel/ExcelCellFormatterUnitTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 index adedf951d6..d9f96ee93c 100644 --- a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterUnitTest.java +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelCellFormatterUnitTest.java @@ -29,7 +29,7 @@ public class ExcelCellFormatterUnitTest { } @Test - public void gvieStringCell_whenGetCellStringValue_thenReturnStringValue() throws IOException { + public void givenStringCell_whenGetCellStringValue_thenReturnStringValue() throws IOException { Workbook workbook = new XSSFWorkbook(fileLocation); Sheet sheet = workbook.getSheetAt(0); Row row = sheet.getRow(0); @@ -40,7 +40,7 @@ public class ExcelCellFormatterUnitTest { } @Test - public void gvieBooleanCell_whenGetCellStringValue_thenReturnBooleanStringValue() throws IOException { + public void givenBooleanCell_whenGetCellStringValue_thenReturnBooleanStringValue() throws IOException { Workbook workbook = new XSSFWorkbook(fileLocation); Sheet sheet = workbook.getSheetAt(0); Row row = sheet.getRow(0); @@ -51,7 +51,7 @@ public class ExcelCellFormatterUnitTest { } @Test - public void gvieNumericCell_whenGetCellStringValue_thenReturnNumericStringValue() throws IOException { + public void givenNumericCell_whenGetCellStringValue_thenReturnNumericStringValue() throws IOException { Workbook workbook = new XSSFWorkbook(fileLocation); Sheet sheet = workbook.getSheetAt(0); Row row = sheet.getRow(0); @@ -63,7 +63,7 @@ public class ExcelCellFormatterUnitTest { } @Test - public void gvieFormualCell_whenGetCellStringValue_thenReturnOriginalFormulaString() throws IOException { + public void givenFormualCell_whenGetCellStringValue_thenReturnOriginalFormulaString() throws IOException { Workbook workbook = new XSSFWorkbook(fileLocation); Sheet sheet = workbook.getSheetAt(0); Row row = sheet.getRow(0); @@ -74,7 +74,7 @@ public class ExcelCellFormatterUnitTest { } @Test - public void gvieFormualCell_whenGetCellStringValueForFormula_thenReturnOriginalFormulatring() throws IOException { + public void givenFormualCell_whenGetCellStringValueForFormula_thenReturnOriginalFormulatring() throws IOException { Workbook workbook = new XSSFWorkbook(fileLocation); Sheet sheet = workbook.getSheetAt(0); Row row = sheet.getRow(0); From eb36131a55d70fcfc1bf0cf996a99b5ce530cac9 Mon Sep 17 00:00:00 2001 From: Anshul BANSAL Date: Thu, 9 Jan 2020 11:34:28 +0200 Subject: [PATCH 30/44] BAEL-3596 - extracted the version numbers into properties --- .../core-java-concurrency-advanced-3/pom.xml | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) 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 e5f3970de7..8f275f4043 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-3/pom.xml @@ -27,32 +27,32 @@ com.jcabi jcabi-aspects - 0.22.6 + ${jcabi-aspects.version} org.aspectj aspectjrt - 1.9.5 + ${aspectjrt.version} runtime com.google.guava guava - 28.1-jre + ${guava.version} org.cactoos cactoos - 0.43 + ${cactoos.version} com.ea.async ea-async - 1.2.3 + ${ea-async.version} @@ -70,7 +70,7 @@ com.jcabi jcabi-maven-plugin - 0.14.1 + ${jcabi-maven-plugin.version} @@ -82,12 +82,12 @@ org.aspectj aspectjtools - 1.9.1 + ${aspectjtools.version} org.aspectj aspectjweaver - 1.9.1 + ${aspectjweaver.version} @@ -104,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 From 08a1af18fb0e4708152990ca443fcdb1b29f7901 Mon Sep 17 00:00:00 2001 From: Vijay Palaniappan S Date: Thu, 9 Jan 2020 23:28:12 +0530 Subject: [PATCH 31/44] Added Create Date class & Unit Tests for all the cases (#8499) --- .../com/baeldung/datebasics/CreateDate.java | 45 +++++++++++++++ .../datebasics/CreateDateUnitTest.java | 56 +++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datebasics/CreateDate.java create mode 100644 core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datebasics/CreateDateUnitTest.java 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")); + } +} From 0e6fd4f3935e49296eea3b998801ec01c70a9c96 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Thu, 9 Jan 2020 19:04:26 +0100 Subject: [PATCH 32/44] BAEL-3723: Add missing code - SecurityWebApplicationInitializer (#8492) --- .../security/SecurityWebApplicationInitializer.java | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/SecurityWebApplicationInitializer.java 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); + } +} From 7a186e9bc840bb42d8a3d670f63e498c88019e95 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Thu, 9 Jan 2020 19:07:20 +0100 Subject: [PATCH 33/44] BAEL-3741: Add usage examples of @TestPropertySource (#8493) --- .../FilePropertyInjectionUnitTest.java | 24 +++++++++++++++++++ .../PropertyInjectionUnitTest.java | 23 ++++++++++++++++++ ...gBootPropertyInjectionIntegrationTest.java | 23 ++++++++++++++++++ .../src/test/resources/foo.properties | 1 + 4 files changed, 71 insertions(+) create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/FilePropertyInjectionUnitTest.java create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/PropertyInjectionUnitTest.java create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/testproperty/SpringBootPropertyInjectionIntegrationTest.java create mode 100644 spring-boot-properties/src/test/resources/foo.properties 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 From 56f11da5047d2e67443017d094308bc6b742e807 Mon Sep 17 00:00:00 2001 From: Priyesh Mashelkar Date: Thu, 9 Jan 2020 18:14:56 +0000 Subject: [PATCH 34/44] BAEL-3499 Added files for article (#8498) --- spring-boot/pom.xml | 16 +++++++++++-- .../baeldung/buildproperties/Application.java | 18 ++++++++++++++ .../buildproperties/BuildInfoService.java | 21 ++++++++++++++++ .../src/main/resources/build.properties | 2 ++ spring-boot/src/main/resources/build.yml | 2 ++ .../BuildInfoServiceIntegrationTest.java | 24 +++++++++++++++++++ 6 files changed, 81 insertions(+), 2 deletions(-) create mode 100644 spring-boot/src/main/java/com/baeldung/buildproperties/Application.java create mode 100644 spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java create mode 100644 spring-boot/src/main/resources/build.properties create mode 100644 spring-boot/src/main/resources/build.yml create mode 100644 spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java 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")); + } +} From ccadf794a00123d8f98985b097be0210cdb92258 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 9 Jan 2020 22:58:18 +0200 Subject: [PATCH 35/44] Update pom.xml --- spring-boot-admin/pom.xml | 1 + 1 file changed, 1 insertion(+) 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 From 31889765c31a816531356403bc36d54c45ad0fcb Mon Sep 17 00:00:00 2001 From: kwoyke Date: Thu, 9 Jan 2020 22:21:14 +0100 Subject: [PATCH 36/44] BAEL-3733: Fix integration tests (#8500) --- .../FooRepositoryIntegrationTest.java | 14 +++++++------- .../HibernateSessionIntegrationTest.java | 17 ++++++++--------- 2 files changed, 15 insertions(+), 16 deletions(-) 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")); } } From 9136e9a6fb4d22e37fb014f1abd832af9e627607 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Dupire?= Date: Fri, 10 Jan 2020 01:06:52 +0100 Subject: [PATCH 37/44] dupirefr/dupire.francois+pro@gmail.com [BAEL-3488] Timer Class (#8468) * [BAEL-3488] Added examples and tests * [BAEL-3488] Moved code to core-java-date-operations-2 module * [BAEL-3488] Added assertj library to maven dependencies --- .../core-java-date-operations-2/pom.xml | 7 +++ .../baeldung/timer/DatabaseMigrationTask.java | 19 ++++++++ .../com/baeldung/timer/NewsletterTask.java | 14 ++++++ .../timer/DatabaseMigrationTaskUnitTest.java | 44 +++++++++++++++++++ .../timer/NewsletterTaskUnitTest.java | 33 ++++++++++++++ 5 files changed, 117 insertions(+) create mode 100644 core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/timer/DatabaseMigrationTask.java create mode 100644 core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/timer/NewsletterTask.java create mode 100644 core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/timer/DatabaseMigrationTaskUnitTest.java create mode 100644 core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java diff --git a/core-java-modules/core-java-date-operations-2/pom.xml b/core-java-modules/core-java-date-operations-2/pom.xml index 6b126a978b..155b8ad0b7 100644 --- a/core-java-modules/core-java-date-operations-2/pom.xml +++ b/core-java-modules/core-java-date-operations-2/pom.xml @@ -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-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-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 From ac4d7757b70b0d97ae001259afa86ed7bd2841aa Mon Sep 17 00:00:00 2001 From: Eugen Date: Fri, 10 Jan 2020 08:49:50 +0200 Subject: [PATCH 38/44] Update README.md --- spring-exceptions/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From e5b40484199a02bd6f19fcb8a00408df15b1197c Mon Sep 17 00:00:00 2001 From: Tapan Avasthi Date: Fri, 10 Jan 2020 21:34:18 +0530 Subject: [PATCH 39/44] BAEL-3484: Partitioning and Sorting an Array With Many Repeated Entries (#8369) --- algorithms-sorting-2/.gitignore | 4 ++ algorithms-sorting-2/pom.xml | 64 ++++++++++++++++++ .../quicksort/BentleyMcIlroyPartioning.java | 66 +++++++++++++++++++ .../DutchNationalFlagPartioning.java | 38 +++++++++++ .../algorithms/quicksort/Partition.java | 29 ++++++++ .../algorithms/quicksort/SortingUtils.java | 32 +++++++++ .../src/main/resources/logback.xml | 13 ++++ .../BentleyMcilroyPartitioningUnitTest.java | 16 +++++ .../DNFThreeWayQuickSortUnitTest.java | 15 +++++ pom.xml | 2 + 10 files changed, 279 insertions(+) create mode 100644 algorithms-sorting-2/.gitignore create mode 100644 algorithms-sorting-2/pom.xml create mode 100644 algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/BentleyMcIlroyPartioning.java create mode 100644 algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/DutchNationalFlagPartioning.java create mode 100644 algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/Partition.java create mode 100644 algorithms-sorting-2/src/main/java/com/baeldung/algorithms/quicksort/SortingUtils.java create mode 100644 algorithms-sorting-2/src/main/resources/logback.xml create mode 100644 algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java create mode 100644 algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java 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/pom.xml b/pom.xml index c28fcdb273..71e5d21b02 100644 --- a/pom.xml +++ b/pom.xml @@ -341,6 +341,7 @@ algorithms-miscellaneous-4 algorithms-miscellaneous-5 algorithms-sorting + algorithms-sorting-2 algorithms-searching animal-sniffer-mvn-plugin annotations @@ -985,6 +986,7 @@ algorithms-miscellaneous-4 algorithms-miscellaneous-5 algorithms-sorting + algorithms-sorting-2 algorithms-searching animal-sniffer-mvn-plugin annotations From d8b0fd59a8dafd8fbd34a4f174f4a9f36a3655bc Mon Sep 17 00:00:00 2001 From: aitorcuesta <56877414+aitorcuesta@users.noreply.github.com> Date: Fri, 10 Jan 2020 22:48:48 +0100 Subject: [PATCH 40/44] BAEL-3678 - Generating Random Numbers - Initial commit (#8491) * BAEL-3678 - Initial commit * BAEL-3678 - Test added * BAEL-3678 - Generated multiple methods and tests * BAEL-3678 - Test improvement --- java-numbers-2/pom.xml | 5 + .../randomnumbers/RandomNumbersGenerator.java | 91 ++++++++++++ .../RandomNumbersGeneratorUnitTest.java | 137 ++++++++++++++++++ 3 files changed, 233 insertions(+) create mode 100644 java-numbers-2/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java create mode 100644 java-numbers-2/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java 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; + } + +} From e10dc3cb9a46742b1f769fcd4ac3816751bb0dfc Mon Sep 17 00:00:00 2001 From: kwoyke Date: Mon, 13 Jan 2020 06:24:24 +0100 Subject: [PATCH 41/44] BAEL-3729: Use entityManagerFactory method name to match the code in the article (#8519) --- .../main/java/com/baeldung/config/PersistenceJPAConfig.java | 5 +++-- .../transactional/PersistenceTransactionalTestConfig.java | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java index e202e45b32..7d3a881827 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java @@ -15,6 +15,7 @@ import org.springframework.dao.annotation.PersistenceExceptionTranslationPostPro import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; @@ -39,12 +40,12 @@ public class PersistenceJPAConfig { // beans @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java index fde1857ca2..72031a2232 100644 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java @@ -14,6 +14,7 @@ import org.springframework.dao.annotation.PersistenceExceptionTranslationPostPro import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; @@ -91,12 +92,12 @@ public class PersistenceTransactionalTestConfig { // beans @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); From 4697561c517f4ad95e95806e7fbe1b485826bbff Mon Sep 17 00:00:00 2001 From: aitorcuesta <56877414+aitorcuesta@users.noreply.github.com> Date: Mon, 13 Jan 2020 18:26:57 +0100 Subject: [PATCH 42/44] BAEL-3678 - Moving from java-numbers-2 to java-numbers-3 (#8521) --- java-numbers-2/pom.xml | 5 ---- java-numbers-3/pom.xml | 8 +++++++ .../randomnumbers/RandomNumbersGenerator.java | 12 ++++++++++ .../RandomNumbersGeneratorUnitTest.java | 23 ++++++++++++++++--- 4 files changed, 40 insertions(+), 8 deletions(-) rename {java-numbers-2 => java-numbers-3}/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java (83%) rename {java-numbers-2 => java-numbers-3}/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java (84%) diff --git a/java-numbers-2/pom.xml b/java-numbers-2/pom.xml index f5f10d9364..ba40ef0a38 100644 --- a/java-numbers-2/pom.xml +++ b/java-numbers-2/pom.xml @@ -21,11 +21,6 @@ jmh-generator-annprocess ${jmh-generator.version} - - it.unimi.dsi - dsiutils - 2.6.0 - diff --git a/java-numbers-3/pom.xml b/java-numbers-3/pom.xml index 3dd8e16bc7..e3c64064c7 100644 --- a/java-numbers-3/pom.xml +++ b/java-numbers-3/pom.xml @@ -12,6 +12,14 @@ 0.0.1-SNAPSHOT ../parent-java + + + + it.unimi.dsi + dsiutils + 2.6.0 + + java-numbers-3 diff --git a/java-numbers-2/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java b/java-numbers-3/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java similarity index 83% rename from java-numbers-2/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java rename to java-numbers-3/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java index 84cd3eecb6..50a072371e 100644 --- a/java-numbers-2/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java +++ b/java-numbers-3/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java @@ -70,12 +70,24 @@ public class RandomNumbersGenerator { return randomWithSplittableRandom; } + public IntStream generateRandomWithSplittableRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) { + SplittableRandom splittableRandom = new SplittableRandom(); + IntStream limitedIntStreamWithinARangeWithSplittableRandom = splittableRandom.ints(streamSize, min, max); + return limitedIntStreamWithinARangeWithSplittableRandom; + } + public Integer generateRandomWithSecureRandom() { SecureRandom secureRandom = new SecureRandom(); int randomWithSecureRandom = secureRandom.nextInt(); return randomWithSecureRandom; } + public Integer generateRandomWithSecureRandomWithinARange(int min, int max) { + SecureRandom secureRandom = new SecureRandom(); + int randomWithSecureRandomWithinARange = secureRandom.nextInt(max - min) + min; + return randomWithSecureRandomWithinARange; + } + public Integer generateRandomWithRandomDataGenerator(int min, int max) { RandomDataGenerator randomDataGenerator = new RandomDataGenerator(); int randomWithRandomDataGenerator = randomDataGenerator.nextInt(min, max); diff --git a/java-numbers-2/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java similarity index 84% rename from java-numbers-2/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java rename to java-numbers-3/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java index 31d334f8b8..bdd955a4ee 100644 --- a/java-numbers-2/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java +++ b/java-numbers-3/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java @@ -11,6 +11,7 @@ public class RandomNumbersGeneratorUnitTest { private static final int MIN_RANGE = 1; private static final int MAX_RANGE = 10; + private static final int MIN_RANGE_NEGATIVE = -10; private static final int ITERATIONS = 50; private static final long STREAM_SIZE = 50; @@ -19,7 +20,7 @@ public class RandomNumbersGeneratorUnitTest { 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)); + assertTrue(isInRange(randomNumer, MIN_RANGE, MAX_RANGE)); } } @@ -97,10 +98,17 @@ public class RandomNumbersGeneratorUnitTest { 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)); + int randomNumber = generator.generateRandomWithSplittableRandom(MIN_RANGE_NEGATIVE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE_NEGATIVE, MAX_RANGE)); } } + + @Test + public void whenGenerateRandomWithSplittableRandomLimitedIntStreamWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + generator.generateRandomWithSplittableRandomLimitedIntStreamWithinARange(MIN_RANGE, MAX_RANGE, STREAM_SIZE) + .forEach(randomNumber -> assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE))); + } @Test public void whenGenerateRandomWithSecureRandom_returnsSuccessfully() { @@ -110,6 +118,15 @@ public class RandomNumbersGeneratorUnitTest { assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)); } } + + @Test + public void whenGenerateRandomWithSecureRandomWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithSecureRandomWithinARange(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)); + } + } @Test public void whenGenerateRandomWithRandomDataGenerator_returnsSuccessfully() { From 74246a69ecbbeeafb51f9d8c3ae2503c928355cc Mon Sep 17 00:00:00 2001 From: chris9408 <58786016+chris9408@users.noreply.github.com> Date: Mon, 13 Jan 2020 22:17:54 +0200 Subject: [PATCH 43/44] [BAEL-3463] - Big Queue (#8517) --- data-structures/pom.xml | 15 ++++ .../baeldung/bigqueue/BigQueueLiveTest.java | 82 +++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 data-structures/src/test/java/com/baeldung/bigqueue/BigQueueLiveTest.java diff --git a/data-structures/pom.xml b/data-structures/pom.xml index e8f4628062..f4a8ea3a14 100644 --- a/data-structures/pom.xml +++ b/data-structures/pom.xml @@ -12,6 +12,21 @@ 1.0.0-SNAPSHOT + + + github.release.repo + https://raw.github.com/bulldog2011/bulldog-repo/master/repo/releases/ + + + + + + com.leansoft + bigqueue + 0.7.0 + + + diff --git a/data-structures/src/test/java/com/baeldung/bigqueue/BigQueueLiveTest.java b/data-structures/src/test/java/com/baeldung/bigqueue/BigQueueLiveTest.java new file mode 100644 index 0000000000..c0305a7ca3 --- /dev/null +++ b/data-structures/src/test/java/com/baeldung/bigqueue/BigQueueLiveTest.java @@ -0,0 +1,82 @@ +package com.baeldung.bigqueue; + +import com.leansoft.bigqueue.BigQueueImpl; +import com.leansoft.bigqueue.IBigQueue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@RunWith(JUnit4.class) +public class BigQueueLiveTest { + + private IBigQueue bigQueue; + + @Before + public void setup() throws IOException { + String queueDir = System.getProperty("user.home"); + String queueName = "baeldung-queue"; + bigQueue = new BigQueueImpl(queueDir, queueName); + } + + @After + public void emptyQueue() throws IOException { + bigQueue.removeAll(); + bigQueue.gc(); + bigQueue.close(); + } + + @Test + public void whenAddingRecords_ThenTheSizeIsCorrect() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + + assertEquals(100, bigQueue.size()); + } + + @Test + public void whenAddingRecords_ThenTheyCanBeRetrieved() throws IOException { + bigQueue.enqueue(String.valueOf("new_record").getBytes()); + + String record = new String(bigQueue.dequeue()); + assertEquals("new_record", record); + } + + @Test + public void whenDequeueingRecords_ThenTheyAreConsumed() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + bigQueue.dequeue(); + + assertEquals(99, bigQueue.size()); + } + + @Test + public void whenPeekingRecords_ThenSizeDoesntChange() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + String firstRecord = new String(bigQueue.peek()); + + assertEquals("1", firstRecord); + assertEquals(100, bigQueue.size()); + } + + @Test + public void whenEmptyingTheQueue_ThenItSizeIs0() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + bigQueue.removeAll(); + + assertEquals(0, bigQueue.size()); + } + +} From 7a23abe4ff8062b690eafbb09bacbd28853b0b41 Mon Sep 17 00:00:00 2001 From: Paturi Radhe Sravan Date: Tue, 14 Jan 2020 22:34:07 +0530 Subject: [PATCH 44/44] BAEL-3597 Cactoos (#8512) * BAEL-3597 Cactoos * BAEL-3597 Cactoos * BAEL-3597 Cactoos * BAEL-3597 Cactoos --- libraries-3/pom.xml | 8 ++- .../cactoos/CactoosCollectionUtils.java | 28 ++++++++++ .../baeldung/cactoos/CactoosStringUtils.java | 37 +++++++++++++ .../CactoosCollectionUtilsUnitTest.java | 35 ++++++++++++ .../cactoos/CactoosStringUtilsUnitTest.java | 54 +++++++++++++++++++ 5 files changed, 161 insertions(+), 1 deletion(-) create mode 100644 libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java create mode 100644 libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java create mode 100644 libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java create mode 100644 libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index c8980fd309..6942aa736d 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -23,10 +23,16 @@ lombok ${lombok.version} + + org.cactoos + cactoos + ${cactoos.version} + 1.78 1.18.6 + 0.43 - + \ No newline at end of file diff --git a/libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java new file mode 100644 index 0000000000..717c63ae63 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java @@ -0,0 +1,28 @@ +package com.baeldung.cactoos; + +import java.util.Collection; +import java.util.List; + +import org.cactoos.collection.Filtered; +import org.cactoos.iterable.IterableOf; +import org.cactoos.list.ListOf; +import org.cactoos.scalar.And; +import org.cactoos.text.FormattedText; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CactoosCollectionUtils { + + final Logger LOGGER = LoggerFactory.getLogger(CactoosCollectionUtils.class); + + public void iterateCollection(List strings) throws Exception { + new And((String input) -> LOGGER.info(new FormattedText("%s\n", input).asString()), strings).value(); + } + + public Collection getFilteredList(List strings) { + Collection filteredStrings = new ListOf<>( + new Filtered<>(string -> string.length() == 5, new IterableOf<>(strings))); + return filteredStrings; + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java new file mode 100644 index 0000000000..3e2903ebf4 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java @@ -0,0 +1,37 @@ +package com.baeldung.cactoos; + +import java.io.IOException; + +import org.cactoos.text.FormattedText; +import org.cactoos.text.IsBlank; +import org.cactoos.text.Lowered; +import org.cactoos.text.TextOf; +import org.cactoos.text.Upper; + +public class CactoosStringUtils { + + public String createString() throws IOException { + String testString = new TextOf("Test String").asString(); + return testString; + } + + public String createdFormattedString(String stringToFormat) throws IOException { + String formattedString = new FormattedText("Hello %s", stringToFormat).asString(); + return formattedString; + } + + public String toLowerCase(String testString) throws IOException { + String lowerCaseString = new Lowered(new TextOf(testString)).asString(); + return lowerCaseString; + } + + public String toUpperCase(String testString) throws Exception { + String upperCaseString = new Upper(new TextOf(testString)).asString(); + return upperCaseString; + } + + public boolean isBlank(String testString) throws Exception { + return new IsBlank(new TextOf(testString)) != null; + } + +} diff --git a/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java new file mode 100644 index 0000000000..c6bcbd7df7 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.cactoos; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; + +import org.junit.Test; + +public class CactoosCollectionUtilsUnitTest { + + @Test + public void whenFilteredClassIsCalledWithSpecificArgs_thenCorrespondingFilteredCollectionShouldBeReturned() throws IOException { + + CactoosCollectionUtils obj = new CactoosCollectionUtils(); + + // when + List strings = new ArrayList() { + { + add("Hello"); + add("John"); + add("Smith"); + add("Eric"); + add("Dizzy"); + } + }; + int size = obj.getFilteredList(strings).size(); + + // then + assertEquals(3, size); + + } + +} diff --git a/libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java new file mode 100644 index 0000000000..67dd6d91e4 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.cactoos; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; + +import org.junit.Test; + +public class CactoosStringUtilsUnitTest { + + @Test + public void whenFormattedTextIsPassedWithArgs_thenFormattedStringIsReturned() throws IOException { + + CactoosStringUtils obj = new CactoosStringUtils(); + + // when + String formattedString = obj.createdFormattedString("John"); + + // then + assertEquals("Hello John", formattedString); + + } + + @Test + public void whenStringIsPassesdToLoweredOrUpperClass_thenCorrespondingStringIsReturned() throws Exception { + + CactoosStringUtils obj = new CactoosStringUtils(); + + // when + String lowerCaseString = obj.toLowerCase("TeSt StrIng"); + String upperCaseString = obj.toUpperCase("TeSt StrIng"); + + // then + assertEquals("test string", lowerCaseString); + assertEquals("TEST STRING", upperCaseString); + + } + + @Test + public void whenEmptyStringIsPassesd_thenIsBlankReturnsTrue() throws Exception { + + CactoosStringUtils obj = new CactoosStringUtils(); + + // when + boolean isBlankEmptyString = obj.isBlank(""); + boolean isBlankNull = obj.isBlank(null); + + // then + assertEquals(true, isBlankEmptyString); + assertEquals(true, isBlankNull); + + } + +}