diff --git a/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java b/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java index 1170a2d761..33462d6171 100644 --- a/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java +++ b/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java @@ -7,6 +7,8 @@ import akka.http.javadsl.model.HttpEntities; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.testkit.JUnitRouteTest; import akka.http.javadsl.testkit.TestRoute; + +import org.junit.Ignore; import org.junit.Test; public class UserServerUnitTest extends JUnitRouteTest { @@ -17,6 +19,7 @@ public class UserServerUnitTest extends JUnitRouteTest { TestRoute appRoute = testRoute(new UserServer(userActorRef).routes()); + @Ignore @Test public void whenRequest_thenActorResponds() { diff --git a/algorithms-miscellaneous-1/pom.xml b/algorithms-miscellaneous-1/pom.xml index a2183f7474..b7c32bda43 100644 --- a/algorithms-miscellaneous-1/pom.xml +++ b/algorithms-miscellaneous-1/pom.xml @@ -64,7 +64,7 @@ org.codehaus.mojo cobertura-maven-plugin - 2.7 + ${cobertura.plugin.version} @@ -85,6 +85,7 @@ 1.11 27.0.1-jre 3.3.0 + 2.7 \ No newline at end of file diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java index d5eea279de..bfcafdaef2 100644 --- a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java @@ -98,7 +98,7 @@ public class SlopeOne { for (Item j : InputData.items) { if (e.getValue().containsKey(j)) { clean.put(j, e.getValue().get(j)); - } else { + } else if (!clean.containsKey(j)) { clean.put(j, -1.0); } } diff --git a/algorithms-miscellaneous-3/pom.xml b/algorithms-miscellaneous-3/pom.xml index a893f0a045..673ac0121d 100644 --- a/algorithms-miscellaneous-3/pom.xml +++ b/algorithms-miscellaneous-3/pom.xml @@ -46,13 +46,13 @@ org.apache.commons commons-lang3 - 3.8.1 + ${commons.lang3.version} pl.pragmatists JUnitParams - 1.1.0 + ${JUnitParams.version} test @@ -91,6 +91,8 @@ 2.6.0 1.19 1.19 + 3.8.1 + 1.1.0 \ No newline at end of file diff --git a/algorithms-miscellaneous-5/pom.xml b/algorithms-miscellaneous-5/pom.xml index 95036da775..4f9cc8b711 100644 --- a/algorithms-miscellaneous-5/pom.xml +++ b/algorithms-miscellaneous-5/pom.xml @@ -37,7 +37,7 @@ com.google.guava guava - 28.1-jre + ${guava.version} @@ -65,6 +65,7 @@ 3.9.0 1.11 3.6.1 + 28.1-jre \ No newline at end of file diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDeque.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDeque.java new file mode 100644 index 0000000000..4c220b4047 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDeque.java @@ -0,0 +1,36 @@ +package com.baeldung.algorithms.balancedbrackets; + +import java.util.Deque; +import java.util.LinkedList; + +public class BalancedBracketsUsingDeque { + + public boolean isBalanced(String str) { + if (null == str || ((str.length() % 2) != 0)) { + return false; + } else { + char[] ch = str.toCharArray(); + for (char c : ch) { + if (!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) { + return false; + } + + } + } + + Deque deque = new LinkedList<>(); + for (char ch : str.toCharArray()) { + if (ch == '{' || ch == '[' || ch == '(') { + deque.addFirst(ch); + } else { + if (!deque.isEmpty() && ((deque.peekFirst() == '{' && ch == '}') || (deque.peekFirst() == '[' && ch == ']') || (deque.peekFirst() == '(' && ch == ')'))) { + deque.removeFirst(); + } else { + return false; + } + } + } + + return true; + } +} \ No newline at end of file diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingString.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingString.java new file mode 100644 index 0000000000..0418efbe79 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingString.java @@ -0,0 +1,27 @@ +package com.baeldung.algorithms.balancedbrackets; + +public class BalancedBracketsUsingString { + + public boolean isBalanced(String str) { + if (null == str || ((str.length() % 2) != 0)) { + return false; + } else { + char[] ch = str.toCharArray(); + for (char c : ch) { + if (!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) { + return false; + } + + } + } + + while (str.contains("()") || str.contains("[]") || str.contains("{}")) { + str = str.replaceAll("\\(\\)", "") + .replaceAll("\\[\\]", "") + .replaceAll("\\{\\}", ""); + } + return (str.length() == 0); + + } + +} \ No newline at end of file diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java new file mode 100644 index 0000000000..964c1ce11a --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.algorithms.balancedbrackets; + +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BalancedBracketsUsingDequeUnitTest { + private BalancedBracketsUsingDeque balancedBracketsUsingDeque; + + @Before + public void setup() { + balancedBracketsUsingDeque = new BalancedBracketsUsingDeque(); + } + + @Test + public void givenNullInput_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingDeque.isBalanced(null); + assertThat(result).isFalse(); + } + + @Test + public void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingDeque.isBalanced(""); + assertThat(result).isTrue(); + } + + @Test + public void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingDeque.isBalanced("abc[](){}"); + assertThat(result).isFalse(); + } + + @Test + public void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}"); + assertThat(result).isFalse(); + } + + @Test + public void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}}"); + assertThat(result).isFalse(); + } + + @Test + public void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingDeque.isBalanced("{[(])}"); + assertThat(result).isFalse(); + } + + @Test + public void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingDeque.isBalanced("{[()]}"); + assertThat(result).isTrue(); + } + + @Test + public void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingDeque.isBalanced("{{[[(())]]}}"); + assertThat(result).isTrue(); + } + + @Test + public void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingDeque.isBalanced("{{([])}}"); + assertThat(result).isTrue(); + } + + @Test + public void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingDeque.isBalanced("{{)[](}}"); + assertThat(result).isFalse(); + } + +} \ No newline at end of file diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java new file mode 100644 index 0000000000..69ce42b0f1 --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.algorithms.balancedbrackets; + +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BalancedBracketsUsingStringUnitTest { + private BalancedBracketsUsingString balancedBracketsUsingString; + + @Before + public void setup() { + balancedBracketsUsingString = new BalancedBracketsUsingString(); + } + + @Test + public void givenNullInput_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingString.isBalanced(null); + assertThat(result).isFalse(); + } + + @Test + public void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingString.isBalanced(""); + assertThat(result).isTrue(); + } + + @Test + public void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingString.isBalanced("abc[](){}"); + assertThat(result).isFalse(); + } + + @Test + public void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}"); + assertThat(result).isFalse(); + } + + @Test + public void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}}"); + assertThat(result).isFalse(); + } + + @Test + public void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingString.isBalanced("{[(])}"); + assertThat(result).isFalse(); + } + + @Test + public void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingString.isBalanced("{[()]}"); + assertThat(result).isTrue(); + } + + @Test + public void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingString.isBalanced("{{[[(())]]}}"); + assertThat(result).isTrue(); + } + + @Test + public void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() { + boolean result = balancedBracketsUsingString.isBalanced("{{([])}}"); + assertThat(result).isTrue(); + } + + @Test + public void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() { + boolean result = balancedBracketsUsingString.isBalanced("{{)[](}}"); + assertThat(result).isFalse(); + } + +} \ No newline at end of file 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/core-kotlin/src/main/resources/logback.xml b/algorithms-sorting-2/src/main/resources/logback.xml similarity index 89% rename from core-kotlin/src/main/resources/logback.xml rename to algorithms-sorting-2/src/main/resources/logback.xml index 7d900d8ea8..26beb6d5b4 100644 --- a/core-kotlin/src/main/resources/logback.xml +++ b/algorithms-sorting-2/src/main/resources/logback.xml @@ -8,6 +8,6 @@ - + \ No newline at end of file diff --git a/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java new file mode 100644 index 0000000000..847f7f8acb --- /dev/null +++ b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.algorithms.quicksort; + +import org.junit.Assert; +import org.junit.Test; + +public class BentleyMcilroyPartitioningUnitTest { + + @Test + public void given_IntegerArray_whenSortedWithBentleyMcilroyPartitioning_thenGetSortedArray() { + int[] actual = {3, 2, 2, 2, 3, 7, 7, 3, 2, 2, 7, 3, 3}; + int[] expected = {2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 7, 7, 7}; + BentleyMcIlroyPartioning.quicksort(actual, 0, actual.length - 1); + Assert.assertArrayEquals(expected, actual); + } + +} diff --git a/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java new file mode 100644 index 0000000000..a8e27253cc --- /dev/null +++ b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.algorithms.quicksort; + +import org.junit.Assert; +import org.junit.Test; + +public class DNFThreeWayQuickSortUnitTest { + + @Test + public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() { + int[] actual = {3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3}; + int[] expected = {3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7}; + DutchNationalFlagPartioning.quicksort(actual, 0, actual.length - 1); + Assert.assertArrayEquals(expected, actual); + } +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml index 43bbcf1ef4..1d7ecdb58f 100644 --- a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml @@ -18,19 +18,19 @@ javax.ws.rs javax.ws.rs-api - 2.1 + ${rs-api.version} provided javax.enterprise cdi-api - 2.0 + ${cdi-api.version} provided javax.json.bind javax.json.bind-api - 1.0 + ${bind-api.version} provided @@ -80,6 +80,9 @@ 2.4.2 false 18.0.0.2 + 2.1 + 2.0 + 1.0 diff --git a/apache-rocketmq/pom.xml b/apache-rocketmq/pom.xml index 59c204dddf..f15dd0e61c 100644 --- a/apache-rocketmq/pom.xml +++ b/apache-rocketmq/pom.xml @@ -17,11 +17,12 @@ org.apache.rocketmq rocketmq-spring-boot-starter - 2.0.4 + ${rocketmq.version} 1.6.0 + 2.0.4 diff --git a/apache-tapestry/pom.xml b/apache-tapestry/pom.xml index e306b56b4a..a4124b07df 100644 --- a/apache-tapestry/pom.xml +++ b/apache-tapestry/pom.xml @@ -81,10 +81,10 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + ${compiler.plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} true @@ -92,7 +92,7 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's org.apache.maven.plugins maven-surefire-plugin - 2.7.2 + ${compiler.surefire.version} Qa @@ -104,7 +104,7 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's org.mortbay.jetty maven-jetty-plugin - 6.1.16 + ${compiler.jetty.version} @@ -140,6 +140,11 @@ of testing facilities designed for use with TestNG (http://testng.org/), so it's + 6.1.16 + 2.7.2 + 2.3.2 + 1.8 + 1.8 5.4.5 2.5 6.8.21 diff --git a/aws-reactive/pom.xml b/aws-reactive/pom.xml index b3fcb24902..046825130a 100644 --- a/aws-reactive/pom.xml +++ b/aws-reactive/pom.xml @@ -17,6 +17,8 @@ 1.8 + 2.2.1.RELEASE + 2.10.27 @@ -26,7 +28,7 @@ org.springframework.boot spring-boot-dependencies - 2.2.1.RELEASE + ${spring.version} pom import @@ -34,7 +36,7 @@ software.amazon.awssdk bom - 2.10.27 + ${awssdk.version} pom import diff --git a/blade/pom.xml b/blade/pom.xml index e302f33c51..6d73913e25 100644 --- a/blade/pom.xml +++ b/blade/pom.xml @@ -124,7 +124,7 @@ maven-assembly-plugin - 3.1.0 + ${assembly.plugin.version} ${project.build.finalName} false @@ -161,6 +161,7 @@ 3.11.1 3.0.0-M3 0.7 + 3.1.0 diff --git a/cloud-foundry-uaa/pom.xml b/cloud-foundry-uaa/pom.xml new file mode 100644 index 0000000000..0001e521ed --- /dev/null +++ b/cloud-foundry-uaa/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + cloud-foundry-uaa + 0.0.1-SNAPSHOT + cloud-foundry-uaa + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + cf-uaa-oauth2-client + cf-uaa-oauth2-resource-server + + + diff --git a/core-groovy-2/pom.xml b/core-groovy-2/pom.xml index e0987de4b3..752b6945b3 100644 --- a/core-groovy-2/pom.xml +++ b/core-groovy-2/pom.xml @@ -62,12 +62,12 @@ org.codehaus.groovy groovy-eclipse-compiler - 3.3.0-01 + ${groovy.compiler.version} true maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} groovy-eclipse-compiler ${java.version} @@ -113,7 +113,7 @@ maven-surefire-plugin - 2.20.1 + ${surefire.plugin.version} false @@ -126,7 +126,7 @@ org.apache.maven.plugins maven-assembly-plugin - 3.1.0 + ${assembly.plugin.version} @@ -183,6 +183,10 @@ 1.1.3 1.2.3 2.5.7 + 3.1.0 + 2.20.1 + 3.8.0 + 3.3.0-01 diff --git a/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy index a1f67b1e2e..5ba7a2347c 100644 --- a/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy +++ b/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy @@ -28,16 +28,17 @@ class CategoryUnitTest extends GroovyTestCase { } } - void test_whenUsingTimeCategory_thenOperationOnNumber() { - SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy") - use (TimeCategory) { - assert sdf.format(5.days.from.now) == sdf.format(new Date() + 5.days) - - sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss") - assert sdf.format(10.minutes.from.now) == sdf.format(new Date() + 10.minutes) - assert sdf.format(2.hours.ago) == sdf.format(new Date() - 2.hours) - } - } +// http://team.baeldung.com/browse/BAEL-20687 +// void test_whenUsingTimeCategory_thenOperationOnNumber() { +// SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy") +// use (TimeCategory) { +// assert sdf.format(5.days.from.now) == sdf.format(new Date() + 5.days) +// +// sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss") +// assert sdf.format(10.minutes.from.now) == sdf.format(new Date() + 10.minutes) +// assert sdf.format(2.hours.ago) == sdf.format(new Date() - 2.hours) +// } +// } void test_whenUsingDOMCategory_thenOperationOnXML() { diff --git a/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy index 50433ea890..144d5720c8 100644 --- a/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy +++ b/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy @@ -9,7 +9,7 @@ import wslite.soap.SOAPMessageBuilder import wslite.http.auth.HTTPBasicAuthorization import org.junit.Test -class WebserviceUnitTest extends GroovyTestCase { +class WebserviceManualTest extends GroovyTestCase { JsonSlurper jsonSlurper = new JsonSlurper() diff --git a/core-groovy-collections/pom.xml b/core-groovy-collections/pom.xml index 423be5e977..4e591970b0 100644 --- a/core-groovy-collections/pom.xml +++ b/core-groovy-collections/pom.xml @@ -99,7 +99,7 @@ maven-surefire-plugin - 2.20.1 + ${surefire.plugin.version} false @@ -126,6 +126,7 @@ 2.4.0 1.1-groovy-2.4 1.6 + 2.20.1 diff --git a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy index a479c265c4..b969f0d1ab 100644 --- a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy @@ -1,6 +1,7 @@ package com.baeldung.file import spock.lang.Specification +import spock.lang.Ignore class ReadFileUnitTest extends Specification { @@ -32,6 +33,7 @@ class ReadFileUnitTest extends Specification { assert lines.size(), 3 } + @Ignore def 'Should return file content in string using ReadFile.readFileString given filePath' () { given: def filePath = "src/main/resources/fileContent.txt" diff --git a/core-java-modules/core-java-11/pom.xml b/core-java-modules/core-java-11/pom.xml index 5bebaae00d..32bc68fa66 100644 --- a/core-java-modules/core-java-11/pom.xml +++ b/core-java-modules/core-java-11/pom.xml @@ -42,12 +42,12 @@ org.eclipse.collections eclipse-collections - 10.0.0 + ${eclipse.collections.version} org.eclipse.collections eclipse-collections-api - 10.0.0 + ${eclipse.collections.version} @@ -108,6 +108,7 @@ 3.11.1 benchmarks 1.22 + 10.0.0 diff --git a/core-java-modules/core-java-13/pom.xml b/core-java-modules/core-java-13/pom.xml index 1f215ae6b0..9469f49411 100644 --- a/core-java-modules/core-java-13/pom.xml +++ b/core-java-modules/core-java-13/pom.xml @@ -41,7 +41,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.0.0-M3 + ${surefire.plugin.version} --enable-preview @@ -53,6 +53,7 @@ 13 13 3.6.1 + 3.0.0-M3 \ No newline at end of file diff --git a/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/SwitchExpressionsWithYieldUnitTest.java b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/SwitchExpressionsWithYieldUnitTest.java new file mode 100644 index 0000000000..be1fcfd167 --- /dev/null +++ b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/SwitchExpressionsWithYieldUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.newfeatures; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class SwitchExpressionsWithYieldUnitTest { + + @Test + @SuppressWarnings("preview") + public void whenSwitchingOnOperationSquareMe_thenWillReturnSquare() { + var me = 4; + var operation = "squareMe"; + var result = switch (operation) { + case "doubleMe" -> { + yield me * 2; + } + case "squareMe" -> { + yield me * me; + } + default -> me; + }; + + assertEquals(16, result); + } + +} diff --git a/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/TextBlocksUnitTest.java b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/TextBlocksUnitTest.java new file mode 100644 index 0000000000..1f8ddcbfb4 --- /dev/null +++ b/core-java-modules/core-java-13/src/test/java/com/baeldung/newfeatures/TextBlocksUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.newfeatures; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class TextBlocksUnitTest { + + private static final String JSON_STRING = "{\r\n" + "\"name\" : \"Baeldung\",\r\n" + "\"website\" : \"https://www.%s.com/\"\r\n" + "}"; + + @SuppressWarnings("preview") + private static final String TEXT_BLOCK_JSON = """ + { + "name" : "Baeldung", + "website" : "https://www.%s.com/" + } + """; + + @Test + public void whenTextBlocks_thenStringOperationsWork() { + + assertThat(TEXT_BLOCK_JSON.contains("Baeldung")).isTrue(); + assertThat(TEXT_BLOCK_JSON.indexOf("www")).isGreaterThan(0); + assertThat(TEXT_BLOCK_JSON.length()).isGreaterThan(0); + + } + + @SuppressWarnings("removal") + @Test + public void whenTextBlocks_thenFormattedWorksAsFormat() { + assertThat(TEXT_BLOCK_JSON.formatted("baeldung") + .contains("www.baeldung.com")).isTrue(); + + assertThat(String.format(JSON_STRING, "baeldung") + .contains("www.baeldung.com")).isTrue(); + + } + +} diff --git a/core-java-modules/core-java-14/pom.xml b/core-java-modules/core-java-14/pom.xml index 48ec627416..b985ada5e6 100644 --- a/core-java-modules/core-java-14/pom.xml +++ b/core-java-modules/core-java-14/pom.xml @@ -36,7 +36,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.0.0-M3 + ${surefire.plugin.version} --enable-preview @@ -47,6 +47,7 @@ 14 14 + 3.0.0-M3 \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-2/pom.xml b/core-java-modules/core-java-arrays-2/pom.xml index 532f0a6144..b300de511a 100644 --- a/core-java-modules/core-java-arrays-2/pom.xml +++ b/core-java-modules/core-java-arrays-2/pom.xml @@ -51,7 +51,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.0 + ${shade.plugin.version} package @@ -79,6 +79,7 @@ 3.9 3.10.0 + 3.2.0 diff --git a/core-java-modules/core-java-arrays/pom.xml b/core-java-modules/core-java-arrays/pom.xml index 20a835594f..02d82e4af6 100644 --- a/core-java-modules/core-java-arrays/pom.xml +++ b/core-java-modules/core-java-arrays/pom.xml @@ -183,8 +183,8 @@ maven-javadoc-plugin ${maven-javadoc-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} @@ -373,6 +373,8 @@ 3.1.1 2.0.3.RELEASE 1.6.0 + 1.8 + 1.8 diff --git a/core-java-modules/core-java-concurrency-advanced-3/pom.xml b/core-java-modules/core-java-concurrency-advanced-3/pom.xml index df9834181f..8f275f4043 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-3/pom.xml @@ -23,6 +23,37 @@ ${assertj.version} test + + + com.jcabi + jcabi-aspects + ${jcabi-aspects.version} + + + + org.aspectj + aspectjrt + ${aspectjrt.version} + runtime + + + + com.google.guava + guava + ${guava.version} + + + + org.cactoos + cactoos + ${cactoos.version} + + + + com.ea.async + ea-async + ${ea-async.version} + @@ -36,6 +67,30 @@ ${maven.compiler.target} + + com.jcabi + jcabi-maven-plugin + ${jcabi-maven-plugin.version} + + + + ajc + + + + + + org.aspectj + aspectjtools + ${aspectjtools.version} + + + org.aspectj + aspectjweaver + ${aspectjweaver.version} + + + @@ -49,6 +104,14 @@ 3.14.0 1.8 1.8 + 0.22.6 + 1.9.5 + 28.2-jre + 0.43 + 1.2.3 + 0.14.1 + 1.9.1 + 1.9.1 diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/EAAsyncExample.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/EAAsyncExample.java new file mode 100644 index 0000000000..c7c893e731 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/EAAsyncExample.java @@ -0,0 +1,57 @@ +package com.baeldung.async; + +import static com.ea.async.Async.await; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import com.ea.async.Async; + +public class EAAsyncExample { + + static { + Async.init(); + } + + public static void main(String[] args) throws Exception { + usingCompletableFuture(); + usingAsyncAwait(); + } + + public static void usingCompletableFuture() throws InterruptedException, ExecutionException, Exception { + CompletableFuture completableFuture = hello() + .thenComposeAsync(hello -> mergeWorld(hello)) + .thenAcceptAsync(helloWorld -> print(helloWorld)) + .exceptionally( throwable -> { + System.out.println(throwable.getCause()); + return null; + }); + completableFuture.get(); + } + + public static CompletableFuture hello() { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); + return completableFuture; + } + + public static CompletableFuture mergeWorld(String s) { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> { + return s + " World!"; + }); + return completableFuture; + } + + public static void print(String str) { + CompletableFuture.runAsync(() -> System.out.println(str)); + } + + private static void usingAsyncAwait() { + try { + String hello = await(hello()); + String helloWorld = await(mergeWorld(hello)); + await(CompletableFuture.runAsync(() -> print(helloWorld))); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/JavaAsync.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/JavaAsync.java new file mode 100644 index 0000000000..6f36f46154 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/async/JavaAsync.java @@ -0,0 +1,183 @@ +package com.baeldung.async; + +import static com.ea.async.Async.await; + +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import com.google.common.util.concurrent.AsyncCallable; +import com.google.common.util.concurrent.Callables; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import com.jcabi.aspects.Async; +import com.jcabi.aspects.Loggable; + +public class JavaAsync { + + static { + com.ea.async.Async.init(); + } + + private static final ExecutorService threadpool = Executors.newCachedThreadPool(); + + public static void main (String[] args) throws InterruptedException, ExecutionException { + int number = 20; + + //Thread Example + factorialUsingThread(number).start(); + + //FutureTask Example + Future futureTask = factorialUsingFutureTask(number); + System.out.println("Factorial of " + number + " is: " + futureTask.get()); + + // CompletableFuture Example + Future completableFuture = factorialUsingCompletableFuture(number); + System.out.println("Factorial of " + number + " is: " + completableFuture.get()); + + // EA Async example + System.out.println("Factorial of " + number + " is: " + factorialUsingEAAsync(number)); + + // cactoos async example + Future asyncFuture = factorialUsingCactoos(number); + System.out.println("Factorial of " + number + " is: " + asyncFuture.get()); + + // Guava example + ListenableFuture guavaFuture = factorialUsingGuavaServiceSubmit(number); + System.out.println("Factorial of " + number + " is: " + guavaFuture.get()); + + ListenableFuture guavaFutures = factorialUsingGuavaFutures(number); + System.out.println("Factorial of " + number + " is: " + guavaFutures.get()); + + // @async jcabi-aspect example + Future aspectFuture = factorialUsingJcabiAspect(number); + System.out.println("Factorial of " + number + " is: " + aspectFuture.get()); + + } + + /** + * Finds factorial of a number + * @param number + * @return + */ + public static long factorial(int number) { + long result = 1; + for(int i=number;i>0;i--) { + result *= i; + } + return result; + } + + /** + * Finds factorial of a number using Thread + * @param number + * @return + */ + @Loggable + public static Thread factorialUsingThread(int number) { + Thread newThread = new Thread(() -> { + System.out.println("Factorial of " + number + " is: " + factorial(number)); + }); + + return newThread; + } + + /** + * Finds factorial of a number using FutureTask + * @param number + * @return + */ + @Loggable + public static Future factorialUsingFutureTask(int number) { + Future futureTask = threadpool.submit(() -> factorial(number)); + + while (!futureTask.isDone()) { + System.out.println("FutureTask is not finished yet..."); + } + + return futureTask; + } + + /** + * Finds factorial of a number using CompletableFuture + * @param number + * @return + */ + @Loggable + public static Future factorialUsingCompletableFuture(int number) { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> factorial(number)); + return completableFuture; + } + + /** + * Finds factorial of a number using EA Async + * @param number + * @return + */ + @Loggable + public static long factorialUsingEAAsync(int number) { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> factorial(number)); + long result = await(completableFuture); + return result; + } + + /** + * Finds factorial of a number using Async of Cactoos + * @param number + * @return + * @throws InterruptedException + * @throws ExecutionException + */ + @Loggable + public static Future factorialUsingCactoos(int number) throws InterruptedException, ExecutionException { + org.cactoos.func.Async asyncFunction = new org.cactoos.func.Async(input -> factorial(input)); + Future asyncFuture = asyncFunction.apply(number); + return asyncFuture; + } + + /** + * Finds factorial of a number using Guava's ListeningExecutorService.submit() + * @param number + * @return + */ + @Loggable + public static ListenableFuture factorialUsingGuavaServiceSubmit(int number) { + ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool); + ListenableFuture factorialFuture = (ListenableFuture) service.submit(()-> factorial(number)); + return factorialFuture; + } + + /** + * Finds factorial of a number using Guava's Futures.submitAsync() + * @param number + * @return + */ + @Loggable + public static ListenableFuture factorialUsingGuavaFutures(int number) { + ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool); + AsyncCallable asyncCallable = Callables.asAsyncCallable(new Callable() { + public Long call() { + return factorial(number); + } + }, service); + return Futures.submitAsync(asyncCallable, service); + } + + /** + * Finds factorial of a number using @Async of jcabi-aspects + * @param number + * @return + */ + @Async + @Loggable + public static Future factorialUsingJcabiAspect(int number) { + Future factorialFuture = CompletableFuture.supplyAsync(() -> factorial(number)); + return factorialFuture; + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/workstealing/PrimeNumbers.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/workstealing/PrimeNumbers.java new file mode 100644 index 0000000000..b31ec85cd4 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/workstealing/PrimeNumbers.java @@ -0,0 +1,85 @@ +package com.baeldung.workstealing; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.RecursiveAction; +import java.util.concurrent.atomic.AtomicInteger; + +public class PrimeNumbers extends RecursiveAction { + + private int lowerBound; + private int upperBound; + private int granularity; + static final List GRANULARITIES + = Arrays.asList(1, 10, 100, 1000, 10000); + private AtomicInteger noOfPrimeNumbers; + + PrimeNumbers(int lowerBound, int upperBound, int granularity, AtomicInteger noOfPrimeNumbers) { + this.lowerBound = lowerBound; + this.upperBound = upperBound; + this.granularity = granularity; + this.noOfPrimeNumbers = noOfPrimeNumbers; + } + + PrimeNumbers(int upperBound) { + this(1, upperBound, 100, new AtomicInteger(0)); + } + + private PrimeNumbers(int lowerBound, int upperBound, AtomicInteger noOfPrimeNumbers) { + this(lowerBound, upperBound, 100, noOfPrimeNumbers); + } + + private List subTasks() { + List subTasks = new ArrayList<>(); + + for (int i = 1; i <= this.upperBound / granularity; i++) { + int upper = i * granularity; + int lower = (upper - granularity) + 1; + subTasks.add(new PrimeNumbers(lower, upper, noOfPrimeNumbers)); + } + return subTasks; + } + + @Override + protected void compute() { + if (((upperBound + 1) - lowerBound) > granularity) { + ForkJoinTask.invokeAll(subTasks()); + } else { + findPrimeNumbers(); + } + } + + void findPrimeNumbers() { + for (int num = lowerBound; num <= upperBound; num++) { + if (isPrime(num)) { + noOfPrimeNumbers.getAndIncrement(); + } + } + } + + private boolean isPrime(int number) { + if (number == 2) { + return true; + } + + if (number == 1 || number % 2 == 0) { + return false; + } + + int noOfNaturalNumbers = 0; + + for (int i = 1; i <= number; i++) { + if (number % i == 0) { + noOfNaturalNumbers++; + } + } + + return noOfNaturalNumbers == 2; + } + + public int noOfPrimeNumbers() { + return noOfPrimeNumbers.intValue(); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/rejection/SaturationPolicyUnitTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/rejection/SaturationPolicyUnitTest.java index 5016cc1d06..1301fe2778 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/rejection/SaturationPolicyUnitTest.java +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/rejection/SaturationPolicyUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.rejection; import org.junit.After; +import org.junit.Ignore; import org.junit.Test; import java.util.ArrayList; @@ -28,24 +29,26 @@ public class SaturationPolicyUnitTest { } } + @Ignore @Test public void givenAbortPolicy_WhenSaturated_ThenShouldThrowRejectedExecutionException() { executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new SynchronousQueue<>(), new AbortPolicy()); - executor.execute(() -> waitFor(100)); + executor.execute(() -> waitFor(250)); assertThatThrownBy(() -> executor.execute(() -> System.out.println("Will be rejected"))).isInstanceOf(RejectedExecutionException.class); } + @Ignore @Test public void givenCallerRunsPolicy_WhenSaturated_ThenTheCallerThreadRunsTheTask() { executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new SynchronousQueue<>(), new CallerRunsPolicy()); - executor.execute(() -> waitFor(100)); + executor.execute(() -> waitFor(250)); - long startTime = System.nanoTime(); - executor.execute(() -> waitFor(100)); - double blockedDuration = (System.nanoTime() - startTime) / 1_000_000.0; + long startTime = System.currentTimeMillis(); + executor.execute(() -> waitFor(500)); + long blockedDuration = System.currentTimeMillis() - startTime; - assertThat(blockedDuration).isGreaterThanOrEqualTo(100); + assertThat(blockedDuration).isGreaterThanOrEqualTo(500); } @Test diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/workstealing/PrimeNumbersUnitTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/workstealing/PrimeNumbersUnitTest.java new file mode 100644 index 0000000000..66bc677345 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/workstealing/PrimeNumbersUnitTest.java @@ -0,0 +1,101 @@ +package com.baeldung.workstealing; + +import org.junit.Test; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.logging.Logger; + +import static org.junit.Assert.fail; + +public class PrimeNumbersUnitTest { + + private static Logger logger = Logger.getAnonymousLogger(); + + @Test + public void givenPrimesCalculated_whenUsingPoolsAndOneThread_thenOneThreadSlowest() { + Options opt = new OptionsBuilder() + .include(Benchmarker.class.getSimpleName()) + .forks(1) + .build(); + + try { + new Runner(opt).run(); + } catch (RunnerException e) { + fail(); + } + } + + @Test + public void givenNewWorkStealingPool_whenGettingPrimes_thenStealCountChanges() { + StringBuilder info = new StringBuilder(); + + for (int granularity : PrimeNumbers.GRANULARITIES) { + int parallelism = ForkJoinPool.getCommonPoolParallelism(); + ForkJoinPool pool = + (ForkJoinPool) Executors.newWorkStealingPool(parallelism); + + stealCountInfo(info, granularity, pool); + } + logger.info("\nExecutors.newWorkStealingPool ->" + info.toString()); + } + + @Test + public void givenCommonPool_whenGettingPrimes_thenStealCountChangesSlowly() { + StringBuilder info = new StringBuilder(); + + for (int granularity : PrimeNumbers.GRANULARITIES) { + ForkJoinPool pool = ForkJoinPool.commonPool(); + stealCountInfo(info, granularity, pool); + } + logger.info("\nForkJoinPool.commonPool ->" + info.toString()); + } + + private void stealCountInfo(StringBuilder info, int granularity, ForkJoinPool forkJoinPool) { + PrimeNumbers primes = new PrimeNumbers(1, 10000, granularity, new AtomicInteger(0)); + forkJoinPool.invoke(primes); + forkJoinPool.shutdown(); + + long steals = forkJoinPool.getStealCount(); + String output = "\nGranularity: [" + granularity + "], Steals: [" + steals + "]"; + info.append(output); + } + + + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + @State(Scope.Benchmark) + @Fork(value = 2, warmups = 1, jvmArgs = {"-Xms2G", "-Xmx2G"}) + public static class Benchmarker { + + @Benchmark + public void singleThread() { + PrimeNumbers primes = new PrimeNumbers(10000); + primes.findPrimeNumbers(); // get prime numbers using a single thread + } + + @Benchmark + public void commonPoolBenchmark() { + PrimeNumbers primes = new PrimeNumbers(10000); + ForkJoinPool pool = ForkJoinPool.commonPool(); + pool.invoke(primes); + pool.shutdown(); + } + + @Benchmark + public void newWorkStealingPoolBenchmark() { + PrimeNumbers primes = new PrimeNumbers(10000); + int parallelism = ForkJoinPool.getCommonPoolParallelism(); + ForkJoinPool stealer = (ForkJoinPool) Executors.newWorkStealingPool(parallelism); + stealer.invoke(primes); + stealer.shutdown(); + } + } +} 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 diff --git a/core-java-modules/core-java-datetime-java8-2/pom.xml b/core-java-modules/core-java-datetime-java8-2/pom.xml new file mode 100644 index 0000000000..34323fe76c --- /dev/null +++ b/core-java-modules/core-java-datetime-java8-2/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + core-java-datetime-java8 + ${project.parent.version} + core-java-datetime-java8 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + joda-time + joda-time + ${joda-time.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + log4j + log4j + ${log4j.version} + test + + + + + core-java-datetime-java8 + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 1.9 + 1.9 + 2.10 + + 3.6.1 + + + diff --git a/core-java-modules/core-java-datetime-java8-2/src/main/java/com/baeldung/localdate/LocalDateExample.java b/core-java-modules/core-java-datetime-java8-2/src/main/java/com/baeldung/localdate/LocalDateExample.java new file mode 100644 index 0000000000..f4c9e5431f --- /dev/null +++ b/core-java-modules/core-java-datetime-java8-2/src/main/java/com/baeldung/localdate/LocalDateExample.java @@ -0,0 +1,31 @@ +package com.baeldung.localdate; + +import java.time.LocalDate; +import java.time.Month; +import java.time.format.DateTimeFormatter; + +public class LocalDateExample { + public LocalDate getCustomDateOne(int year, int month, int dayOfMonth) { + return LocalDate.of(year, month, dayOfMonth); + } + + public LocalDate getCustomDateTwo(int year, Month month, int dayOfMonth) { + return LocalDate.of(year, month, dayOfMonth); + } + + public LocalDate getDateFromEpochDay(long epochDay) { + return LocalDate.ofEpochDay(epochDay); + } + + public LocalDate getDateFromYearAndDayOfYear(int year, int dayOfYear) { + return LocalDate.ofYearDay(year, dayOfYear); + } + + public LocalDate getDateFromString(String date) { + return LocalDate.parse(date); + } + + public LocalDate getDateFromStringAndFormatter(String date, String pattern) { + return LocalDate.parse(date, DateTimeFormatter.ofPattern(pattern)); + } +} diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datebasics/CreateDateUnitTest.java b/core-java-modules/core-java-datetime-java8-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java similarity index 65% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datebasics/CreateDateUnitTest.java rename to core-java-modules/core-java-datetime-java8-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java index 54f3285ea0..dff15486a4 100644 --- a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datebasics/CreateDateUnitTest.java +++ b/core-java-modules/core-java-datetime-java8-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.datebasics; +package com.baeldung.localdate; import static org.junit.Assert.assertEquals; @@ -6,49 +6,34 @@ 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")); - } - +public class LocalDateExampleUnitTest { + private LocalDateExample date = new LocalDateExample(); + @Test public void givenValues_whenUsingOfMethod_thenLocalDate() { assertEquals("2020-01-08", date.getCustomDateOne(2020, 1, 8)); } - + @Test public void givenValuesWithMonthEnum_whenUsingOfMethod_thenLocalDate() { assertEquals("2020-01-08", date.getCustomDateTwo(2020, Month.JANUARY, 8)); } - + @Test public void givenValues_whenUsingEpochDay_thenLocalDate() { assertEquals("2020-01-08", date.getDateFromEpochDay(18269)); } - + @Test public void givenValues_whenUsingYearDay_thenLocalDate() { assertEquals("2020-01-08", date.getDateFromYearAndDayOfYear(2020, 8)); } - + @Test public void givenValues_whenUsingParse_thenLocalDate() { assertEquals("2020-01-08", date.getDateFromString("2020-01-08")); } - + @Test public void givenValuesWithFormatter_whenUsingParse_thenLocalDate() { assertEquals("2020-01-08", date.getDateFromStringAndFormatter("8-Jan-2020", "d-MMM-yyyy")); diff --git a/core-java-modules/core-java-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 deleted file mode 100644 index 327827e03a..0000000000 --- a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datebasics/CreateDate.java +++ /dev/null @@ -1,45 +0,0 @@ -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-exceptions-2/pom.xml b/core-java-modules/core-java-exceptions-2/pom.xml index 2f7f613faf..955d7153fa 100644 --- a/core-java-modules/core-java-exceptions-2/pom.xml +++ b/core-java-modules/core-java-exceptions-2/pom.xml @@ -13,12 +13,24 @@ 0.0.1-SNAPSHOT ../../parent-java + + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + http://maven.apache.org UTF-8 + + 3.10.0 diff --git a/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/exceptions/UnknownHostExceptionHandling.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/exceptions/UnknownHostExceptionHandling.java new file mode 100644 index 0000000000..0e1c36f64c --- /dev/null +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/exceptions/UnknownHostExceptionHandling.java @@ -0,0 +1,28 @@ +package com.baeldung.exceptions; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.UnknownHostException; + +public class UnknownHostExceptionHandling { + + public static int getResponseCode(String hostname) throws IOException { + URL url = new URL(hostname.trim()); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + int resCode = -1; + try { + resCode = con.getResponseCode(); + } catch (UnknownHostException e){ + con.disconnect(); + } + return resCode; + } + + public static int getResponseCodeUnhandled(String hostname) throws IOException { + URL url = new URL(hostname.trim()); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + int resCode = con.getResponseCode(); + return resCode; + } +} diff --git a/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/exceptions/UnknownHostExceptionHandlingUnitTest.java b/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/exceptions/UnknownHostExceptionHandlingUnitTest.java new file mode 100644 index 0000000000..d4b53e2dce --- /dev/null +++ b/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/exceptions/UnknownHostExceptionHandlingUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.exceptions; + +import java.io.IOException; +import java.net.UnknownHostException; + +import org.junit.Test; + +public class UnknownHostExceptionHandlingUnitTest { + + @Test(expected = UnknownHostException.class) + public void givenUnknownHost_whenResolve_thenUnknownHostException() throws IOException { + UnknownHostExceptionHandling.getResponseCodeUnhandled("http://locaihost"); + } + +} diff --git a/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/file/FileClassUnitTest.java b/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/file/FileClassUnitTest.java index a4317af372..1883f40681 100644 --- a/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/file/FileClassUnitTest.java +++ b/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/file/FileClassUnitTest.java @@ -1,5 +1,6 @@ package com.baeldung.file; +import org.junit.Ignore; import org.junit.Test; import java.io.*; @@ -73,6 +74,7 @@ public class FileClassUnitTest { assertFalse(writable); } + @Ignore @Test public void givenWriteOnlyFile_whenCreateNewFile_thenCantReadFile() { File parentDir = makeDir("writeDir"); diff --git a/core-java-modules/core-java-jar/pom.xml b/core-java-modules/core-java-jar/pom.xml index a3e8941622..fe94a6d8a8 100644 --- a/core-java-modules/core-java-jar/pom.xml +++ b/core-java-modules/core-java-jar/pom.xml @@ -207,8 +207,8 @@ maven-javadoc-plugin ${maven-javadoc-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} @@ -397,6 +397,8 @@ 3.1.1 2.0.3.RELEASE 1.6.0 + 1.8 + 1.8 diff --git a/core-java-modules/core-java-jndi/pom.xml b/core-java-modules/core-java-jndi/pom.xml index 13504886d6..bb4299ae75 100644 --- a/core-java-modules/core-java-jndi/pom.xml +++ b/core-java-modules/core-java-jndi/pom.xml @@ -9,44 +9,49 @@ core-java-jndi - com.baeldung - parent-modules + com.baeldung.core-java-modules + core-java-modules 1.0.0-SNAPSHOT - ../../ org.junit.jupiter junit-jupiter + ${jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-api 5.5.1 test org.springframework spring-core - 5.0.9.RELEASE + ${spring.version} org.springframework spring-context - 5.0.9.RELEASE + ${spring.version} org.springframework spring-jdbc - 5.0.9.RELEASE + ${spring.version} org.springframework spring-test - 5.0.9.RELEASE + ${spring.version} test com.h2database h2 - 1.4.199 + ${h2.version} @@ -56,11 +61,19 @@ org.apache.maven.plugins maven-compiler-plugin - 1.8 - 1.8 + ${source.version} + ${target.version} + + + 5.0.9.RELEASE + 1.4.199 + 5.5.1 + 1.8 + 1.8 + diff --git a/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java b/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java index 49d4facffb..434fa41252 100644 --- a/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java +++ b/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java @@ -1,5 +1,12 @@ package com.baeldung.jndi.exceptions; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import javax.naming.InitialContext; +import javax.naming.NameNotFoundException; +import javax.naming.NoInitialContextException; + +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; @@ -7,15 +14,10 @@ import org.junit.jupiter.api.TestMethodOrder; import org.springframework.jndi.JndiTemplate; import org.springframework.mock.jndi.SimpleNamingContextBuilder; -import javax.naming.InitialContext; -import javax.naming.NameNotFoundException; -import javax.naming.NoInitialContextException; - -import static org.junit.jupiter.api.Assertions.assertThrows; - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class JndiExceptionsUnitTest { + @Disabled @Test @Order(1) void givenNoContext_whenLookupObject_thenThrowNoInitialContext() { diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml index ddf52d8fef..e708502dee 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml @@ -16,7 +16,7 @@ com.baeldung.servicemodule servicemodule - 1.0 + ${servicemodule.version} @@ -29,4 +29,8 @@ + + 1.0 + + diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml index 78a9d1eaad..3c03643a2c 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml @@ -19,10 +19,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 11 - 11 + ${source.version} + ${target.version} @@ -31,6 +31,9 @@ UTF-8 + 3.8.0 + 11 + 11 \ No newline at end of file diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule/pom.xml index ece85fd5dc..3fe6f735eb 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule/pom.xml @@ -2,7 +2,6 @@ 4.0.0 - com.baeldung.servicemodule servicemodule jar diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml index 734774af0e..a042ee4562 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml @@ -8,8 +8,8 @@ 1.0 - decoupling-pattern2 - com.baeldung.decoupling-pattern2 + com.baeldung.decoupling-pattern2 + decoupling-pattern2 1.0-SNAPSHOT @@ -17,12 +17,12 @@ com.baeldung.servicemodule servicemodule - 1.0 + ${servicemodule.version} com.baeldung.providermodule providermodule - 1.0 + ${providermodule.version} @@ -34,5 +34,10 @@ + + + 1.0 + 1.0 + \ No newline at end of file diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml index 2f84c69fd6..f6b4e5b0df 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml @@ -20,14 +20,20 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 11 - 11 + ${source.version} + ${target.version} + + + 3.8.0 + 11 + 11 + \ No newline at end of file diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml index 5ec36c581e..20e97fca0f 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml @@ -8,8 +8,8 @@ 1.0 - decoupling-pattern2 - com.baeldung.decoupling-pattern2 + com.baeldung.decoupling-pattern2 + decoupling-pattern2 1.0-SNAPSHOT @@ -17,7 +17,7 @@ com.baeldung.servicemodule servicemodule - 1.0 + ${servicemodule.version} @@ -30,4 +30,9 @@ + + 1.0 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml index 9249ea5d89..f65ebb0b55 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml @@ -3,13 +3,12 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung.servicemodule servicemodule 1.0 - decoupling-pattern2 - >com.baeldung.decoupling-pattern2 + com.baeldung.decoupling-pattern2 + decoupling-pattern2 1.0-SNAPSHOT diff --git a/core-java-modules/core-java-jpms/pom.xml b/core-java-modules/core-java-jpms/pom.xml new file mode 100644 index 0000000000..dfb3c71229 --- /dev/null +++ b/core-java-modules/core-java-jpms/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + core-java-jpms + 0.0.1-SNAPSHOT + core-java-jpms + pom + + + com.baeldung.core-java-modules + core-java-modules + 1.0.0-SNAPSHOT + + + + decoupling-pattern1 + decoupling-pattern2 + + + diff --git a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoUnitTest.java b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoManualTest.java similarity index 88% rename from core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoUnitTest.java rename to core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoManualTest.java index 0c50651af0..d56dea62f4 100644 --- a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoUnitTest.java +++ b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmExitDemoManualTest.java @@ -2,7 +2,7 @@ package com.baeldung.exitvshalt; import org.junit.Test; -public class JvmExitDemoUnitTest { +public class JvmExitDemoManualTest { JvmExitAndHaltDemo jvmExitAndHaltDemo = new JvmExitAndHaltDemo(); diff --git a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoUnitTest.java b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoManualTest.java similarity index 88% rename from core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoUnitTest.java rename to core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoManualTest.java index 9f08e95c6a..4fe0999a9c 100644 --- a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoUnitTest.java +++ b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/exitvshalt/JvmHaltDemoManualTest.java @@ -2,7 +2,7 @@ package com.baeldung.exitvshalt; import org.junit.Test; -public class JvmHaltDemoUnitTest { +public class JvmHaltDemoManualTest { JvmExitAndHaltDemo jvmExitAndHaltDemo = new JvmExitAndHaltDemo(); diff --git a/core-java-modules/core-java-lang-2/pom.xml b/core-java-modules/core-java-lang-2/pom.xml index 5657e64b17..4702b7350b 100644 --- a/core-java-modules/core-java-lang-2/pom.xml +++ b/core-java-modules/core-java-lang-2/pom.xml @@ -18,7 +18,7 @@ commons-beanutils commons-beanutils - 1.9.4 + ${commons.beanutils.version} org.openjdk.jmh @@ -57,6 +57,7 @@ 1.19 1.19 3.12.2 + 1.9.4 diff --git a/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java index 47473c29ea..f9fbc5dc3a 100644 --- a/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java +++ b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java @@ -1,6 +1,8 @@ package com.baeldung.optional; +import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; public class Person { private String name; @@ -21,7 +23,7 @@ public class Person { } public Optional getAge() { - return Optional.ofNullable(age); + return Optional.of(age); } public void setAge(int age) { @@ -36,4 +38,37 @@ public class Person { return Optional.ofNullable(password); } + public static List search(List people, String name, Optional age) { + // Null checks for people and name + return people.stream() + .filter(p -> p.getName().equals(name)) + .filter(p -> p.getAge().get() >= age.orElse(0)) + .collect(Collectors.toList()); + } + + public static List search(List people, String name, Integer age) { + // Null checks for people and name + final Integer ageFilter = age != null ? age : 0; + + return people.stream() + .filter(p -> p.getName().equals(name)) + .filter(p -> p.getAge().get() >= ageFilter) + .collect(Collectors.toList()); + } + + public static List search(List people, String name) { + return doSearch(people, name, 0); + } + + public static List search(List people, String name, int age) { + return doSearch(people, name, age); + } + + private static List doSearch(List people, String name, int age) { + // Null checks for people and name + return people.stream() + .filter(p -> p.getName().equals(name)) + .filter(p -> p.getAge().get().intValue() >= age) + .collect(Collectors.toList()); + } } diff --git a/core-java-modules/core-java-reflection/pom.xml b/core-java-modules/core-java-reflection/pom.xml index b3c3390df8..64086ef5b8 100644 --- a/core-java-modules/core-java-reflection/pom.xml +++ b/core-java-modules/core-java-reflection/pom.xml @@ -37,8 +37,8 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} -parameters @@ -48,5 +48,7 @@ 3.8.0 3.10.0 + 1.8 + 1.8 \ No newline at end of file diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetExample.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetExample.java new file mode 100644 index 0000000000..a20ee527f8 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetExample.java @@ -0,0 +1,7 @@ +package com.baeldung.reflection.exception.invocationtarget; + +public class InvocationTargetExample { + public int divideByZeroExample() { + return 1 / 0; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetUnitTest.java new file mode 100644 index 0000000000..b4cabebcef --- /dev/null +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/exception/invocationtarget/InvocationTargetUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.reflection.exception.invocationtarget; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.jupiter.api.Test; + +public class InvocationTargetUnitTest { + + @Test + public void whenCallingMethodThrowsException_thenAssertCauseOfInvocationTargetException() throws Exception { + + InvocationTargetExample targetExample = new InvocationTargetExample(); + Method method = InvocationTargetExample.class.getMethod("divideByZeroExample"); + + Exception exception = assertThrows(InvocationTargetException.class, () -> method.invoke(targetExample)); + + assertEquals(ArithmeticException.class, exception.getCause().getClass()); + } +} diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index a5dd31c762..43dc040591 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -25,7 +25,7 @@ com.google.guava guava - 28.1-jre + ${guava.version} @@ -62,7 +62,7 @@ 3.8.1 3.6.1 - 27.0.1-jre + 28.1-jre 5.3.1 diff --git a/core-java-modules/core-java-text/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java b/core-java-modules/core-java-text/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java new file mode 100644 index 0000000000..304b9f2f1d --- /dev/null +++ b/core-java-modules/core-java-text/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.regex.matcher; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.Test; + +public class MatcherUnitTest { + + @Test + public void whenFindFourDigitWorks_thenCorrect() { + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); + Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); + + assertTrue(m.find()); + assertEquals(8, m.start()); + assertEquals("2019", m.group()); + assertEquals(12, m.end()); + + assertTrue(m.find()); + assertEquals(25, m.start()); + assertEquals("2020", m.group()); + assertEquals(29, m.end()); + + assertFalse(m.find()); + } + + @Test + public void givenStartIndex_whenFindFourDigitWorks_thenCorrect() { + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); + Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); + + assertTrue(m.find(20)); + assertEquals(25, m.start()); + assertEquals("2020", m.group()); + assertEquals(29, m.end()); + } + + @Test + public void whenMatchFourDigitWorks_thenFail() { + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); + Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); + assertFalse(m.matches()); + } + + @Test + public void whenMatchFourDigitWorks_thenCorrect() { + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); + Matcher m = stringPattern.matcher("2019"); + + assertTrue(m.matches()); + assertEquals(0, m.start()); + assertEquals("2019", m.group()); + assertEquals(4, m.end()); + + assertTrue(m.matches());// matches will always return the same return + } + +} diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml index 341363f8ed..2442d81559 100644 --- a/core-java-modules/core-java/pom.xml +++ b/core-java-modules/core-java/pom.xml @@ -207,8 +207,8 @@ maven-javadoc-plugin ${maven-javadoc-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} @@ -397,6 +397,8 @@ 3.1.1 2.0.3.RELEASE 1.6.0 + 1.8 + 1.8 diff --git a/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml b/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml index fa2d92d67f..e8a8203f33 100644 --- a/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml @@ -17,17 +17,17 @@ com.baeldung.entitymodule entitymodule - 1.0 + ${entitymodule.version} com.baeldung.daomodule daomodule - 1.0 + ${daomodule.version} com.baeldung.userdaomodule userdaomodule - 1.0 + ${userdaomodule.version} @@ -43,6 +43,9 @@ 9 9 + 1.0 + 1.0 + 1.0 \ No newline at end of file diff --git a/core-java-modules/multimodulemavenproject/pom.xml b/core-java-modules/multimodulemavenproject/pom.xml index 1d4aebf32e..dcf9f7311e 100644 --- a/core-java-modules/multimodulemavenproject/pom.xml +++ b/core-java-modules/multimodulemavenproject/pom.xml @@ -45,10 +45,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 1.9 - 1.9 + ${source.version} + ${target.version} @@ -56,6 +56,9 @@ + 3.8.0 + 1.9 + 1.9 UTF-8 3.12.2 diff --git a/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml b/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml index 19012708cf..8f4cc3d945 100644 --- a/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml @@ -17,12 +17,12 @@ com.baeldung.entitymodule entitymodule - 1.0 + ${entitymodule.version} com.baeldung.daomodule daomodule - 1.0 + ${daomodule.version} @@ -38,6 +38,8 @@ 9 9 + 1.0 + 1.0 \ No newline at end of file diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index b3b9be9ee4..904cec2815 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -14,11 +14,110 @@ - pre-jpms - core-java-optional - core-java-lang-operators - core-java-networking-2 + core-java + + + + + core-java-8 + core-java-8-2 + + + + + + + + core-java-annotations + core-java-arrays + core-java-arrays-2 + + core-java-collections + core-java-collections-2 + core-java-collections-3 + core-java-collections-array-list + core-java-collections-list + core-java-collections-list-2 + core-java-collections-list-3 + core-java-collections-set + + core-java-concurrency-2 + core-java-concurrency-advanced + core-java-concurrency-advanced-2 + core-java-concurrency-advanced-3 + core-java-concurrency-basic + core-java-concurrency-basic-2 + core-java-concurrency-collections + + core-java-date-operations-2 + + + + core-java-exceptions + core-java-exceptions-2 + + core-java-function + + core-java-io + core-java-io-2 + core-java-io-apis + core-java-io-conversions + + core-java-jar + core-java-jndi + + core-java-jvm + + core-java-lambdas + core-java-lang + core-java-lang-2 + core-java-lang-math + core-java-lang-oop + core-java-lang-oop-2 + core-java-lang-oop-3 + core-java-lang-oop-4 + core-java-lang-operators + core-java-lang-syntax + core-java-lang-syntax-2 + + core-java-networking + core-java-networking-2 + core-java-nio + core-java-nio-2 + + core-java-optional + + + core-java-perf + + core-java-reflection + + core-java-security + core-java-streams + core-java-streams-2 + core-java-streams-3 + core-java-string-algorithms + core-java-string-algorithms-2 + core-java-string-algorithms-3 + core-java-string-apis + core-java-string-conversions + core-java-string-conversions-2 + core-java-string-operations + core-java-string-operations-2 + core-java-strings + core-java-sun + + core-java-text + + + + pre-jpms diff --git a/core-java-modules/pre-jpms/pom.xml b/core-java-modules/pre-jpms/pom.xml index cb23427138..9833dc2ff7 100644 --- a/core-java-modules/pre-jpms/pom.xml +++ b/core-java-modules/pre-jpms/pom.xml @@ -29,16 +29,16 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} org.apache.maven.plugins maven-dependency-plugin - 3.1.1 + ${dependency.plugin.version} copy-dependencies @@ -69,5 +69,12 @@ + + + 3.1.1 + 3.8.0 + 1.8 + 1.8 + diff --git a/core-kotlin-2/.gitignore b/core-kotlin-2/.gitignore deleted file mode 100644 index 0c017e8f8c..0000000000 --- a/core-kotlin-2/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -/bin/ - -#ignore gradle -.gradle/ - - -#ignore build and generated files -build/ -node/ -out/ - -#ignore installed node modules and package lock file -node_modules/ -package-lock.json diff --git a/core-kotlin-2/README.md b/core-kotlin-2/README.md deleted file mode 100644 index 5249262fa3..0000000000 --- a/core-kotlin-2/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Core Kotlin - -This module contains articles about core Kotlin. - -### Relevant articles: - -- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions) -- [Kotlin Annotations](https://www.baeldung.com/kotlin-annotations) -- [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts) -- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison) -- [Guide to JVM Platform Annotations in Kotlin](https://www.baeldung.com/kotlin-jvm-annotations) -- [Finding an Element in a List Using Kotlin](https://www.baeldung.com/kotlin-finding-element-in-list) -- [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-conditional-operator) -- More articles: [[<-- prev]](/core-kotlin) diff --git a/core-kotlin-2/build.gradle b/core-kotlin-2/build.gradle deleted file mode 100644 index 1c52172404..0000000000 --- a/core-kotlin-2/build.gradle +++ /dev/null @@ -1,58 +0,0 @@ - - -group 'com.baeldung.ktor' -version '1.0-SNAPSHOT' - - -buildscript { - ext.kotlin_version = '1.3.30' - - repositories { - mavenCentral() - } - dependencies { - - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -apply plugin: 'java' -apply plugin: 'kotlin' -apply plugin: 'application' - -mainClassName = 'APIServer.kt' - -sourceCompatibility = 1.8 -compileKotlin { kotlinOptions.jvmTarget = "1.8" } -compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } - -repositories { - mavenCentral() - jcenter() - maven { url "https://dl.bintray.com/kotlin/ktor" } -} -sourceSets { - main{ - kotlin{ - srcDirs 'com/baeldung/ktor' - } - } -} - -test { - useJUnitPlatform() - testLogging { - events "passed", "skipped", "failed" - } -} - -dependencies { - implementation "ch.qos.logback:logback-classic:1.2.1" - implementation "org.jetbrains.kotlin:kotlin-stdlib:${kotlin_version}" - testImplementation 'org.junit.jupiter:junit-jupiter:5.4.2' - testImplementation 'junit:junit:4.12' - testImplementation 'org.assertj:assertj-core:3.12.2' - testImplementation 'org.mockito:mockito-core:2.27.0' - testImplementation "org.jetbrains.kotlin:kotlin-test:${kotlin_version}" - testImplementation "org.jetbrains.kotlin:kotlin-test-junit5:${kotlin_version}" -} diff --git a/core-kotlin-2/gradle/wrapper/gradle-wrapper.jar b/core-kotlin-2/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 5c2d1cf016..0000000000 Binary files a/core-kotlin-2/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/core-kotlin-2/gradle/wrapper/gradle-wrapper.properties b/core-kotlin-2/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 5f1b1201a7..0000000000 --- a/core-kotlin-2/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.4-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/core-kotlin-2/gradlew b/core-kotlin-2/gradlew deleted file mode 100644 index b0d6d0ab5d..0000000000 --- a/core-kotlin-2/gradlew +++ /dev/null @@ -1,188 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 2015 the original author or authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/core-kotlin-2/gradlew.bat b/core-kotlin-2/gradlew.bat deleted file mode 100644 index 9991c50326..0000000000 --- a/core-kotlin-2/gradlew.bat +++ /dev/null @@ -1,100 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem http://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/core-kotlin-2/pom.xml b/core-kotlin-2/pom.xml deleted file mode 100644 index be2f5fa68f..0000000000 --- a/core-kotlin-2/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - 4.0.0 - core-kotlin-2 - core-kotlin-2 - jar - - - com.baeldung - parent-kotlin - 1.0.0-SNAPSHOT - ../parent-kotlin - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.junit.jupiter - junit-jupiter - ${junit.jupiter.version} - test - - - org.mockito - mockito-core - ${mockito.version} - test - - - net.bytebuddy - byte-buddy - ${byte-buddy.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - - - org.jetbrains.kotlin - kotlin-test-junit5 - ${kotlin.version} - test - - - - - - - org.jetbrains.kotlin - kotlin-maven-plugin - ${kotlin.version} - - - compile - compile - - compile - - - - test-compile - test-compile - - test-compile - - - - - 1.8 - - - - - - - 1.3.30 - 5.4.2 - 2.27.0 - 1.9.12 - 3.10.0 - - - diff --git a/core-kotlin-2/resources/logback.xml b/core-kotlin-2/resources/logback.xml deleted file mode 100644 index 9452207268..0000000000 --- a/core-kotlin-2/resources/logback.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - \ No newline at end of file diff --git a/core-kotlin-2/settings.gradle b/core-kotlin-2/settings.gradle deleted file mode 100644 index c91c993971..0000000000 --- a/core-kotlin-2/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ -rootProject.name = 'KtorWithKotlin' - diff --git a/core-kotlin-2/src/test/resources/Kotlin.in b/core-kotlin-2/src/test/resources/Kotlin.in deleted file mode 100644 index d140d4429e..0000000000 --- a/core-kotlin-2/src/test/resources/Kotlin.in +++ /dev/null @@ -1,5 +0,0 @@ -Hello to Kotlin. Its: -1. Concise -2. Safe -3. Interoperable -4. Tool-friendly \ No newline at end of file diff --git a/core-kotlin-2/src/test/resources/Kotlin.out b/core-kotlin-2/src/test/resources/Kotlin.out deleted file mode 100644 index 63d15d2528..0000000000 --- a/core-kotlin-2/src/test/resources/Kotlin.out +++ /dev/null @@ -1,2 +0,0 @@ -Kotlin -Concise, Safe, Interoperable, Tool-friendly \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-2/README.md b/core-kotlin-modules/core-kotlin-2/README.md new file mode 100644 index 0000000000..11593062c5 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-2/README.md @@ -0,0 +1,8 @@ +## Core Kotlin 2 + +This module contains articles about Kotlin core features. + +### Relevant articles: +- [Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates) +- [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-conditional-operator) +- [[<-- Prev]](/core-kotlin-modules/core-kotlin) diff --git a/core-kotlin-modules/core-kotlin-2/pom.xml b/core-kotlin-modules/core-kotlin-2/pom.xml new file mode 100644 index 0000000000..ae6e2d175a --- /dev/null +++ b/core-kotlin-modules/core-kotlin-2/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + core-kotlin-2 + core-kotlin-2 + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseDuration.kt b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseDuration.kt similarity index 90% rename from core-kotlin/src/main/kotlin/com/baeldung/datetime/UseDuration.kt rename to core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseDuration.kt index 40fb161c08..922c3a1988 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseDuration.kt +++ b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseDuration.kt @@ -1,4 +1,4 @@ -package com.baeldung.datetime +package com.baeldung.dates.datetime import java.time.Duration import java.time.LocalTime diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDate.kt b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDate.kt similarity index 96% rename from core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDate.kt rename to core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDate.kt index 250c071bbe..81d50a70b2 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDate.kt +++ b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDate.kt @@ -1,4 +1,4 @@ -package com.baeldung.datetime +package com.baeldung.dates.datetime import java.time.DayOfWeek import java.time.LocalDate diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDateTime.kt b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDateTime.kt similarity index 84% rename from core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDateTime.kt rename to core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDateTime.kt index ab7bbfcee1..5d0eb6a911 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDateTime.kt +++ b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDateTime.kt @@ -1,4 +1,4 @@ -package com.baeldung.datetime +package com.baeldung.dates.datetime import java.time.LocalDateTime diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalTime.kt b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalTime.kt similarity index 92% rename from core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalTime.kt rename to core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalTime.kt index 152515621f..24402467e8 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalTime.kt +++ b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseLocalTime.kt @@ -1,6 +1,5 @@ -package com.baeldung.datetime +package com.baeldung.dates.datetime -import java.time.LocalDateTime import java.time.LocalTime import java.time.temporal.ChronoUnit diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UsePeriod.kt b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UsePeriod.kt similarity index 90% rename from core-kotlin/src/main/kotlin/com/baeldung/datetime/UsePeriod.kt rename to core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UsePeriod.kt index df66a3d546..d15e02eb37 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UsePeriod.kt +++ b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UsePeriod.kt @@ -1,4 +1,4 @@ -package com.baeldung.datetime +package com.baeldung.dates.datetime import java.time.LocalDate import java.time.Period diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseZonedDateTime.kt b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseZonedDateTime.kt similarity index 88% rename from core-kotlin/src/main/kotlin/com/baeldung/datetime/UseZonedDateTime.kt rename to core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseZonedDateTime.kt index fd1838bd2d..e2f3a207c4 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseZonedDateTime.kt +++ b/core-kotlin-modules/core-kotlin-2/src/main/kotlin/com/baeldung/dates/datetime/UseZonedDateTime.kt @@ -1,4 +1,4 @@ -package com.baeldung.datetime +package com.baeldung.dates.datetime import java.time.LocalDateTime import java.time.ZoneId diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/CreateDateUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/CreateDateUnitTest.kt similarity index 96% rename from kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/CreateDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/CreateDateUnitTest.kt index d52a2f0f19..af5e08ea2d 100644 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/CreateDateUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/CreateDateUnitTest.kt @@ -1,34 +1,34 @@ -package com.baeldung.kotlin.dates - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import java.time.LocalDate -import java.time.format.DateTimeFormatter - -class CreateDateUnitTest { - - @Test - fun givenString_whenDefaultFormat_thenCreated() { - - var date = LocalDate.parse("2018-12-31") - - assertThat(date).isEqualTo("2018-12-31") - } - - @Test - fun givenString_whenCustomFormat_thenCreated() { - - var formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy") - var date = LocalDate.parse("31-12-2018", formatter) - - assertThat(date).isEqualTo("2018-12-31") - } - - @Test - fun givenYMD_whenUsingOf_thenCreated() { - var date = LocalDate.of(2018, 12, 31) - - assertThat(date).isEqualTo("2018-12-31") - } - +package com.baeldung.kotlin.dates + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import java.time.LocalDate +import java.time.format.DateTimeFormatter + +class CreateDateUnitTest { + + @Test + fun givenString_whenDefaultFormat_thenCreated() { + + var date = LocalDate.parse("2018-12-31") + + assertThat(date).isEqualTo("2018-12-31") + } + + @Test + fun givenString_whenCustomFormat_thenCreated() { + + var formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy") + var date = LocalDate.parse("31-12-2018", formatter) + + assertThat(date).isEqualTo("2018-12-31") + } + + @Test + fun givenYMD_whenUsingOf_thenCreated() { + var date = LocalDate.of(2018, 12, 31) + + assertThat(date).isEqualTo("2018-12-31") + } + } \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/ExtractDateUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/ExtractDateUnitTest.kt similarity index 96% rename from kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/ExtractDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/ExtractDateUnitTest.kt index ef3841752b..d297f4b6c3 100644 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/ExtractDateUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/ExtractDateUnitTest.kt @@ -1,29 +1,29 @@ -package com.baeldung.kotlin.dates - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import java.time.DayOfWeek -import java.time.LocalDate -import java.time.Month - -class ExtractDateUnitTest { - - @Test - fun givenDate_thenExtractedYMD() { - var date = LocalDate.parse("2018-12-31") - - assertThat(date.year).isEqualTo(2018) - assertThat(date.month).isEqualTo(Month.DECEMBER) - assertThat(date.dayOfMonth).isEqualTo(31) - } - - @Test - fun givenDate_thenExtractedEraDowDoy() { - var date = LocalDate.parse("2018-12-31") - - assertThat(date.era.toString()).isEqualTo("CE") - assertThat(date.dayOfWeek).isEqualTo(DayOfWeek.MONDAY) - assertThat(date.dayOfYear).isEqualTo(365) - } - +package com.baeldung.kotlin.dates + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import java.time.DayOfWeek +import java.time.LocalDate +import java.time.Month + +class ExtractDateUnitTest { + + @Test + fun givenDate_thenExtractedYMD() { + var date = LocalDate.parse("2018-12-31") + + assertThat(date.year).isEqualTo(2018) + assertThat(date.month).isEqualTo(Month.DECEMBER) + assertThat(date.dayOfMonth).isEqualTo(31) + } + + @Test + fun givenDate_thenExtractedEraDowDoy() { + var date = LocalDate.parse("2018-12-31") + + assertThat(date.era.toString()).isEqualTo("CE") + assertThat(date.dayOfWeek).isEqualTo(DayOfWeek.MONDAY) + assertThat(date.dayOfYear).isEqualTo(365) + } + } \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/FormatDateUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/FormatDateUnitTest.kt similarity index 96% rename from kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/FormatDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/FormatDateUnitTest.kt index 11ff6ec9f0..f7ca414aee 100644 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/FormatDateUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/FormatDateUnitTest.kt @@ -1,29 +1,29 @@ -package com.baeldung.kotlin.dates - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import java.time.LocalDate -import java.time.format.DateTimeFormatter - -class FormatDateUnitTest { - - @Test - fun givenDate_whenDefaultFormat_thenFormattedString() { - - var date = LocalDate.parse("2018-12-31") - - assertThat(date.toString()).isEqualTo("2018-12-31") - } - - @Test - fun givenDate_whenCustomFormat_thenFormattedString() { - - var date = LocalDate.parse("2018-12-31") - - var formatter = DateTimeFormatter.ofPattern("dd-MMMM-yyyy") - var formattedDate = date.format(formatter) - - assertThat(formattedDate).isEqualTo("31-December-2018") - } - +package com.baeldung.kotlin.dates + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import java.time.LocalDate +import java.time.format.DateTimeFormatter + +class FormatDateUnitTest { + + @Test + fun givenDate_whenDefaultFormat_thenFormattedString() { + + var date = LocalDate.parse("2018-12-31") + + assertThat(date.toString()).isEqualTo("2018-12-31") + } + + @Test + fun givenDate_whenCustomFormat_thenFormattedString() { + + var date = LocalDate.parse("2018-12-31") + + var formatter = DateTimeFormatter.ofPattern("dd-MMMM-yyyy") + var formattedDate = date.format(formatter) + + assertThat(formattedDate).isEqualTo("31-December-2018") + } + } \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/PeriodDateUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/PeriodDateUnitTest.kt similarity index 96% rename from kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/PeriodDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/PeriodDateUnitTest.kt index e6b66634d3..e8ca2971e8 100644 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/dates/PeriodDateUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/PeriodDateUnitTest.kt @@ -1,48 +1,48 @@ -package com.baeldung.kotlin.dates - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import java.time.LocalDate -import java.time.Period - -class PeriodDateUnitTest { - - @Test - fun givenYMD_thenCreatePeriod() { - var period = Period.of(1, 2, 3) - - assertThat(period.toString()).isEqualTo("P1Y2M3D") - } - - @Test - fun givenPeriod_whenAdd_thenModifiedDate() { - var period = Period.of(1, 2, 3) - - var date = LocalDate.of(2018, 6, 25) - var modifiedDate = date.plus(period) - - assertThat(modifiedDate).isEqualTo("2019-08-28") - } - - @Test - fun givenPeriod_whenSubtracted_thenModifiedDate() { - var period = Period.of(1, 2, 3) - - var date = LocalDate.of(2018, 6, 25) - var modifiedDate = date.minus(period) - - assertThat(modifiedDate).isEqualTo("2017-04-22") - } - - @Test - fun givenTwoDate_whenUsingBetween_thenDiffOfDates() { - - var date1 = LocalDate.parse("2018-06-25") - var date2 = LocalDate.parse("2018-12-25") - - var period = Period.between(date1, date2) - - assertThat(period.toString()).isEqualTo("P6M") - } - +package com.baeldung.kotlin.dates + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import java.time.LocalDate +import java.time.Period + +class PeriodDateUnitTest { + + @Test + fun givenYMD_thenCreatePeriod() { + var period = Period.of(1, 2, 3) + + assertThat(period.toString()).isEqualTo("P1Y2M3D") + } + + @Test + fun givenPeriod_whenAdd_thenModifiedDate() { + var period = Period.of(1, 2, 3) + + var date = LocalDate.of(2018, 6, 25) + var modifiedDate = date.plus(period) + + assertThat(modifiedDate).isEqualTo("2019-08-28") + } + + @Test + fun givenPeriod_whenSubtracted_thenModifiedDate() { + var period = Period.of(1, 2, 3) + + var date = LocalDate.of(2018, 6, 25) + var modifiedDate = date.minus(period) + + assertThat(modifiedDate).isEqualTo("2017-04-22") + } + + @Test + fun givenTwoDate_whenUsingBetween_thenDiffOfDates() { + + var date1 = LocalDate.parse("2018-06-25") + var date2 = LocalDate.parse("2018-12-25") + + var period = Period.between(date1, date2) + + assertThat(period.toString()).isEqualTo("P6M") + } + } \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateTimeUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateTimeUnitTest.kt similarity index 92% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateTimeUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateTimeUnitTest.kt index 8f9f8374ed..f3615a527c 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateTimeUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateTimeUnitTest.kt @@ -1,14 +1,12 @@ package com.baeldung.kotlin.datetime -import com.baeldung.datetime.UseLocalDateTime +import com.baeldung.dates.datetime.UseLocalDateTime +import org.junit.Assert.assertEquals +import org.junit.Test import java.time.LocalDate import java.time.LocalTime import java.time.Month -import org.junit.Test - -import org.junit.Assert.assertEquals - class UseLocalDateTimeUnitTest { var useLocalDateTime = UseLocalDateTime() diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateUnitTest.kt similarity index 97% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateUnitTest.kt index ac42e91c6c..e6353c9dab 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateUnitTest.kt @@ -1,6 +1,6 @@ package com.baeldung.kotlin.datetime -import com.baeldung.datetime.UseLocalDate +import com.baeldung.dates.datetime.UseLocalDate import org.junit.Assert import org.junit.Test import java.time.DayOfWeek diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalTimeUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalTimeUnitTest.kt similarity index 95% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalTimeUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalTimeUnitTest.kt index 83fc57f850..1afe03ca48 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalTimeUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseLocalTimeUnitTest.kt @@ -1,10 +1,9 @@ package com.baeldung.kotlin.datetime -import com.baeldung.datetime.UseLocalTime -import java.time.LocalTime - +import com.baeldung.dates.datetime.UseLocalTime import org.junit.Assert import org.junit.Test +import java.time.LocalTime class UseLocalTimeUnitTest { diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UsePeriodUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UsePeriodUnitTest.kt similarity index 94% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UsePeriodUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UsePeriodUnitTest.kt index 48be72feb0..36e1e5533a 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UsePeriodUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UsePeriodUnitTest.kt @@ -1,11 +1,10 @@ package com.baeldung.kotlin.datetime -import com.baeldung.datetime.UsePeriod -import java.time.LocalDate -import java.time.Period - +import com.baeldung.dates.datetime.UsePeriod import org.junit.Assert import org.junit.Test +import java.time.LocalDate +import java.time.Period class UsePeriodUnitTest { diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseZonedDateTimeUnitTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseZonedDateTimeUnitTest.kt similarity index 90% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseZonedDateTimeUnitTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseZonedDateTimeUnitTest.kt index a9d7d973ef..aa2cdaa4f3 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseZonedDateTimeUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/dates/datetime/UseZonedDateTimeUnitTest.kt @@ -1,6 +1,6 @@ package com.baeldung.kotlin.datetime -import com.baeldung.datetime.UseZonedDateTime +import com.baeldung.dates.datetime.UseZonedDateTime import org.junit.Assert import org.junit.Test import java.time.LocalDateTime diff --git a/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt new file mode 100644 index 0000000000..a41e213c44 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt @@ -0,0 +1,54 @@ +package com.baeldung.sequeces + +import org.junit.Test +import kotlin.test.assertEquals +import java.time.Instant + +class SequencesTest { + + @Test + fun shouldBuildSequenceWhenUsingFromElements() { + val seqOfElements = sequenceOf("first" ,"second", "third") + .toList() + assertEquals(3, seqOfElements.count()) + } + + @Test + fun shouldBuildSequenceWhenUsingFromFunction() { + val seqFromFunction = generateSequence(Instant.now()) {it.plusSeconds(1)} + .take(3) + .toList() + assertEquals(3, seqFromFunction.count()) + } + + @Test + fun shouldBuildSequenceWhenUsingFromChunks() { + val seqFromChunks = sequence { + yield(1) + yieldAll((2..5).toList()) + }.toList() + assertEquals(5, seqFromChunks.count()) + } + + @Test + fun shouldBuildSequenceWhenUsingFromCollection() { + val seqFromIterable = (1..10) + .asSequence() + .toList() + assertEquals(10, seqFromIterable.count()) + } + + @Test + fun shouldShowNoCountDiffWhenUsingWithAndWithoutSequence() { + val withSequence = (1..10).asSequence() + .filter{it % 2 == 1} + .map { it * 2 } + .toList() + val withoutSequence = (1..10) + .filter{it % 2 == 1} + .map { it * 2 } + .toList() + assertEquals(withSequence.count(), withoutSequence.count()) + } + +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt b/core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt similarity index 100% rename from core-kotlin-2/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt rename to core-kotlin-modules/core-kotlin-2/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt diff --git a/core-kotlin-modules/core-kotlin-lang-oop-2/README.md b/core-kotlin-modules/core-kotlin-lang-oop-2/README.md index 83d8f6f38a..27536273dc 100644 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/README.md +++ b/core-kotlin-modules/core-kotlin-lang-oop-2/README.md @@ -1,4 +1,4 @@ -## Core Kotlin +## Core Kotlin Lang OOP This module contains articles about Object-Oriented Programming in Kotlin @@ -7,4 +7,4 @@ This module contains articles about Object-Oriented Programming in Kotlin - [Generics in Kotlin](https://www.baeldung.com/kotlin-generics) - [Delegated Properties in Kotlin](https://www.baeldung.com/kotlin-delegated-properties) - [Delegation Pattern in Kotlin](https://www.baeldung.com/kotlin-delegation-pattern) -- [[<-- Prev]](/core-kotlin-lang-oop) +- [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang-oop) diff --git a/core-kotlin-modules/core-kotlin-lang-oop/README.md b/core-kotlin-modules/core-kotlin-lang-oop/README.md index 461635f1b5..0c1aeb7850 100644 --- a/core-kotlin-modules/core-kotlin-lang-oop/README.md +++ b/core-kotlin-modules/core-kotlin-lang-oop/README.md @@ -14,4 +14,4 @@ This module contains articles about Object-Oriented Programming in Kotlin - [Guide to Kotlin Interfaces](https://www.baeldung.com/kotlin-interfaces) - [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes) - [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods) -- More articles: [[next -->]](/core-kotlin-lang-oop-2) +- More articles: [[next -->]](/core-kotlin-modules/core-kotlin-lang-oop-2) diff --git a/core-kotlin-modules/core-kotlin/README.md b/core-kotlin-modules/core-kotlin/README.md new file mode 100644 index 0000000000..8815b0fadd --- /dev/null +++ b/core-kotlin-modules/core-kotlin/README.md @@ -0,0 +1,16 @@ +## Core Kotlin + +This module contains articles about Kotlin core features. + +### Relevant articles: +- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin) +- [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability) +- [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number) +- [Create a Java and Kotlin Project with Maven](https://www.baeldung.com/kotlin-maven-java-project) +- [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort) +- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern) +- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions) +- [Implementing a Binary Tree in Kotlin](https://www.baeldung.com/kotlin-binary-tree) +- [JUnit 5 for Kotlin Developers](https://www.baeldung.com/junit-5-kotlin) +- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class) +- [[More --> ]](/core-kotlin-modules/core-kotlin-2) diff --git a/core-kotlin-modules/core-kotlin/pom.xml b/core-kotlin-modules/core-kotlin/pom.xml new file mode 100644 index 0000000000..6e36b7c8ef --- /dev/null +++ b/core-kotlin-modules/core-kotlin/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + core-kotlin + core-kotlin + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + + 1.1.1 + + + \ No newline at end of file diff --git a/core-kotlin/src/main/java/com/baeldung/java/ArrayExample.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/ArrayExample.java similarity index 91% rename from core-kotlin/src/main/java/com/baeldung/java/ArrayExample.java rename to core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/ArrayExample.java index ef91db517b..93b9a3984a 100644 --- a/core-kotlin/src/main/java/com/baeldung/java/ArrayExample.java +++ b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/ArrayExample.java @@ -1,4 +1,4 @@ -package com.baeldung.java; +package com.baeldung.interoperability; import java.io.File; import java.io.FileReader; diff --git a/core-kotlin/src/main/java/com/baeldung/java/Customer.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/Customer.java similarity index 91% rename from core-kotlin/src/main/java/com/baeldung/java/Customer.java rename to core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/Customer.java index 0156bf7b44..4a070a0f97 100644 --- a/core-kotlin/src/main/java/com/baeldung/java/Customer.java +++ b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/Customer.java @@ -1,4 +1,4 @@ -package com.baeldung.java; +package com.baeldung.interoperability; public class Customer { diff --git a/core-kotlin/src/main/java/com/baeldung/java/StringUtils.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/introduction/StringUtils.java similarity index 77% rename from core-kotlin/src/main/java/com/baeldung/java/StringUtils.java rename to core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/introduction/StringUtils.java index f405924cdf..1c477ce039 100644 --- a/core-kotlin/src/main/java/com/baeldung/java/StringUtils.java +++ b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/introduction/StringUtils.java @@ -1,4 +1,4 @@ -package com.baeldung.java; +package com.baeldung.introduction; public class StringUtils { public static String toUpperCase(String name) { diff --git a/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java similarity index 91% rename from core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java rename to core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java index e2cc0f1e01..ac933d6228 100644 --- a/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java +++ b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java @@ -1,7 +1,6 @@ package com.baeldung.mavenjavakotlin; import com.baeldung.mavenjavakotlin.services.JavaService; -import com.baeldung.mavenjavakotlin.services.KotlinService; public class Application { diff --git a/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/services/JavaService.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/services/JavaService.java similarity index 100% rename from core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/services/JavaService.java rename to core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/services/JavaService.java diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Main.kt similarity index 93% rename from core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Main.kt index 4fd8aa27c7..eee10fbd8b 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Main.kt @@ -1,4 +1,4 @@ -package com.baeldung.datastructures +package com.baeldung.binarytree /** * Example of how to use the {@link Node} class. diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Node.kt similarity index 99% rename from core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Node.kt index b81afe1e4c..77bb98f828 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/binarytree/Node.kt @@ -1,4 +1,4 @@ -package com.baeldung.datastructures +package com.baeldung.binarytree /** * An ADT for a binary search tree. diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/Example1.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Example1.kt similarity index 63% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/Example1.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Example1.kt index bca1e54a6c..aacd8f7915 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/Example1.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Example1.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.introduction fun main(args: Array){ println("hello word") diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/Item.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Item.kt similarity index 89% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/Item.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Item.kt index 36994e4994..bb91dd1eae 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/Item.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Item.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.introduction open class Item(val id: String, val name: String = "unknown_name") { open fun getIdOfItem(): String { diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/ItemService.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ItemService.kt similarity index 98% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/ItemService.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ItemService.kt index 88de1aa9be..dfcf17df7c 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/ItemService.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ItemService.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.introduction import java.util.* diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/ListExtension.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ListExtension.kt similarity index 90% rename from core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/ListExtension.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ListExtension.kt index da1773b7c9..e71292c60a 100644 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/ListExtension.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ListExtension.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.introduction import java.util.concurrent.ThreadLocalRandom diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/MathematicsOperations.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/MathematicsOperations.kt similarity index 75% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/MathematicsOperations.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/MathematicsOperations.kt index 924f9d2323..0ed30ed5b4 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/MathematicsOperations.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/MathematicsOperations.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.introduction class MathematicsOperations { fun addTwoNumbers(a: Int, b: Int): Int { diff --git a/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/services/KotlinService.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/KotlinService.kt similarity index 70% rename from core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/services/KotlinService.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/KotlinService.kt index 114b1c88df..10d6a792d8 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/services/KotlinService.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/KotlinService.kt @@ -1,4 +1,4 @@ -package com.baeldung.mavenjavakotlin.services +package com.baeldung.mavenjavakotlin class KotlinService { diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt similarity index 100% rename from core-kotlin-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt similarity index 97% rename from core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt index 2309d23c36..bf3163bc8f 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt @@ -1,7 +1,5 @@ package com.baeldung.sorting -import kotlin.comparisons.* - fun sortMethodUsage() { val sortedValues = mutableListOf(1, 2, 7, 6, 5, 6) sortedValues.sort() diff --git a/core-kotlin/src/test/java/com/baeldung/kotlin/JavaCallToKotlinUnitTest.java b/core-kotlin-modules/core-kotlin/src/test/java/com/baeldung/introduction/JavaCallToKotlinUnitTest.java similarity index 90% rename from core-kotlin/src/test/java/com/baeldung/kotlin/JavaCallToKotlinUnitTest.java rename to core-kotlin-modules/core-kotlin/src/test/java/com/baeldung/introduction/JavaCallToKotlinUnitTest.java index 370f24785a..2c386eaad3 100644 --- a/core-kotlin/src/test/java/com/baeldung/kotlin/JavaCallToKotlinUnitTest.java +++ b/core-kotlin-modules/core-kotlin/src/test/java/com/baeldung/introduction/JavaCallToKotlinUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.kotlin; +package com.baeldung.introduction; import org.junit.Test; diff --git a/core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/binarytree/NodeTest.kt similarity index 98% rename from core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/binarytree/NodeTest.kt index 8a46c5f6ec..9414d7dde9 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/binarytree/NodeTest.kt @@ -1,7 +1,8 @@ -package com.baeldung.datastructures +package com.baeldung.binarytree import org.junit.After -import org.junit.Assert.* +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test diff --git a/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/gson/GsonUnitTest.kt similarity index 87% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/gson/GsonUnitTest.kt index bdf44d3b49..9159be96be 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/gson/GsonUnitTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.gson +package com.baeldung.gson import com.google.gson.Gson @@ -11,7 +11,7 @@ class GsonUnitTest { @Test fun givenObject_thenGetJSONString() { - var jsonString = gson.toJson(TestModel(1,"Test")) + var jsonString = gson.toJson(TestModel(1, "Test")) Assert.assertEquals(jsonString, "{\"id\":1,\"description\":\"Test\"}") } diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ArrayTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/ArrayTest.kt similarity index 82% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/ArrayTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/ArrayTest.kt index f7d1c53b13..8e9467f92a 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ArrayTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/ArrayTest.kt @@ -1,7 +1,5 @@ -package com.baeldung.kotlin +package com.baeldung.interoperability -import com.baeldung.java.ArrayExample -import com.baeldung.java.Customer import org.junit.Test import kotlin.test.assertEquals @@ -29,7 +27,7 @@ class ArrayTest { val constructors = instance.constructors assertEquals(constructors.size, 1) - assertEquals(constructors[0].name, "com.baeldung.java.Customer") + assertEquals(constructors[0].name, "com.baeldung.interoperability.Customer") } fun makeReadFile() { diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CustomerTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/CustomerTest.kt similarity index 88% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/CustomerTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/CustomerTest.kt index 6395dfcfed..c1b09cd0c1 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CustomerTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/CustomerTest.kt @@ -1,6 +1,5 @@ -package com.baeldung.kotlin +package com.baeldung.interoperability -import com.baeldung.java.Customer import org.junit.Test import kotlin.test.assertEquals diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ItemServiceTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ItemServiceTest.kt similarity index 92% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/ItemServiceTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ItemServiceTest.kt index 3d730b1283..2ba14a7462 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ItemServiceTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ItemServiceTest.kt @@ -1,9 +1,10 @@ -package com.baeldung.kotlin +package com.baeldung.introduction import org.junit.Test import kotlin.test.assertNotNull class ItemServiceTest { + @Test fun givenItemId_whenGetForOptionalItem_shouldMakeActionOnNonNullValue() { //given diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KotlinJavaInteroperabilityTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/KotlinJavaInteroperabilityTest.kt similarity index 84% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/KotlinJavaInteroperabilityTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/KotlinJavaInteroperabilityTest.kt index 91ccaabf6f..5dddf9bfc9 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KotlinJavaInteroperabilityTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/KotlinJavaInteroperabilityTest.kt @@ -1,6 +1,5 @@ -package com.baeldung.kotlin +package com.baeldung.introduction -import com.baeldung.java.StringUtils import org.junit.Test import kotlin.test.assertEquals diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LambdaTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/LambdaTest.kt similarity index 91% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/LambdaTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/LambdaTest.kt index 34217336a0..5e5166074e 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LambdaTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/LambdaTest.kt @@ -1,10 +1,11 @@ -package com.baeldung.kotlin +package com.baeldung.introduction import org.junit.Test import kotlin.test.assertEquals class LambdaTest { + @Test fun givenListOfNumber_whenDoingOperationsUsingLambda_shouldReturnProperResult() { //given diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/ListExtensionTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ListExtensionTest.kt similarity index 79% rename from core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/ListExtensionTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ListExtensionTest.kt index 7a496e7437..38f244297b 100644 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/ListExtensionTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ListExtensionTest.kt @@ -1,12 +1,12 @@ -package com.baeldung.kotlin +package com.baeldung.introduction -import com.baeldung.kotlin.ListExtension import org.junit.Test import kotlin.test.assertTrue class ListExtensionTest { + @Test - fun givenList_whenExecuteExtensionFunctionOnList_shouldReturnRandomElementOfList(){ + fun givenList_whenExecuteExtensionFunctionOnList_shouldReturnRandomElementOfList() { //given val elements = listOf("a", "b", "c") diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/Calculator.kt similarity index 91% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/Calculator.kt index 1b61c05887..9f6e3ab2b9 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/Calculator.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.junit5 +package com.baeldung.junit5 class Calculator { fun add(a: Int, b: Int) = a + b diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/CalculatorUnitTest.kt similarity index 97% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/CalculatorUnitTest.kt index daaedca5a3..07cab3b76e 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/CalculatorUnitTest.kt @@ -1,9 +1,9 @@ -package com.baeldung.kotlin.junit5 +package com.baeldung.junit5 import org.junit.jupiter.api.* import org.junit.jupiter.api.function.Executable -class CalculatorTest5 { +class CalculatorUnitTest { private val calculator = Calculator() @Test diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/DivideByZeroException.kt similarity index 64% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/DivideByZeroException.kt index 60bc4e2944..5675367fd5 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/DivideByZeroException.kt @@ -1,3 +1,3 @@ -package com.baeldung.kotlin.junit5 +package com.baeldung.junit5 class DivideByZeroException(val numerator: Int) : Exception() diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/SimpleUnitTest.kt similarity index 88% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/SimpleUnitTest.kt index 15ff201430..e3fe998efd 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/junit5/SimpleUnitTest.kt @@ -1,10 +1,10 @@ -package com.baeldung.kotlin.junit5 +package com.baeldung.junit5 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test -class SimpleTest5 { +class SimpleUnitTest { @Test fun `isEmpty should return true for empty lists`() { diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt similarity index 100% rename from core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt similarity index 86% rename from core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt index 8a94e29c2f..7ac0efa4ef 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt @@ -1,9 +1,8 @@ package com.baeldung.sorting +import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.junit.jupiter.api.Assertions.* - class SortingExampleKtTest { @Test diff --git a/core-kotlin-modules/pom.xml b/core-kotlin-modules/pom.xml index e49b5fb85d..24bdc189be 100644 --- a/core-kotlin-modules/pom.xml +++ b/core-kotlin-modules/pom.xml @@ -15,6 +15,8 @@ + core-kotlin + core-kotlin-2 core-kotlin-advanced core-kotlin-annotations core-kotlin-collections diff --git a/core-kotlin/.gitignore b/core-kotlin/.gitignore deleted file mode 100644 index 0c017e8f8c..0000000000 --- a/core-kotlin/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -/bin/ - -#ignore gradle -.gradle/ - - -#ignore build and generated files -build/ -node/ -out/ - -#ignore installed node modules and package lock file -node_modules/ -package-lock.json diff --git a/core-kotlin/README.md b/core-kotlin/README.md deleted file mode 100644 index 89e1b7287e..0000000000 --- a/core-kotlin/README.md +++ /dev/null @@ -1,32 +0,0 @@ -## Core Kotlin - -This module contains articles about core Kotlin. - -### Relevant articles: - -- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin) -- [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability) -- [Generics in Kotlin](https://www.baeldung.com/kotlin-generics) -- [Data Classes in Kotlin](https://www.baeldung.com/kotlin-data-classes) -- [Delegated Properties in Kotlin](https://www.baeldung.com/kotlin-delegated-properties) -- [Sealed Classes in Kotlin](https://www.baeldung.com/kotlin-sealed-classes) -- [JUnit 5 for Kotlin Developers](https://www.baeldung.com/junit-5-kotlin) -- [Extension Methods in Kotlin](https://www.baeldung.com/kotlin-extension-methods) -- [Objects in Kotlin](https://www.baeldung.com/kotlin-objects) -- [Working with Enums in Kotlin](https://www.baeldung.com/kotlin-enum) -- [Create a Java and Kotlin Project with Maven](https://www.baeldung.com/kotlin-maven-java-project) -- [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number) -- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors) -- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern) -- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes) -- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel) -- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant) -- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class) -- [Guide to Kotlin Interfaces](https://www.baeldung.com/kotlin-interfaces) -- [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort) -- [Dependency Injection for Kotlin with Injekt](https://www.baeldung.com/kotlin-dependency-injection-with-injekt) -- [Implementing a Binary Tree in Kotlin](https://www.baeldung.com/kotlin-binary-tree) -- [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes) -- [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods) -- [Delegation Pattern in Kotlin](https://www.baeldung.com/kotlin-delegation-pattern) -- More articles: [[next -->]](/core-kotlin-2) diff --git a/core-kotlin/build.gradle b/core-kotlin/build.gradle deleted file mode 100755 index 2b6527fca7..0000000000 --- a/core-kotlin/build.gradle +++ /dev/null @@ -1,48 +0,0 @@ - - -group 'com.baeldung.ktor' -version '1.0-SNAPSHOT' - - -buildscript { - ext.kotlin_version = '1.2.41' - - repositories { - mavenCentral() - } - dependencies { - - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -apply plugin: 'java' -apply plugin: 'kotlin' -apply plugin: 'application' - -mainClassName = 'APIServer.kt' - -sourceCompatibility = 1.8 -compileKotlin { kotlinOptions.jvmTarget = "1.8" } -compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } - -kotlin { experimental { coroutines "enable" } } - -repositories { - mavenCentral() - jcenter() - maven { url "https://dl.bintray.com/kotlin/ktor" } -} -sourceSets { - main{ - kotlin{ - srcDirs 'com/baeldung/ktor' - } - } - -} - -dependencies { - compile "ch.qos.logback:logback-classic:1.2.1" - testCompile group: 'junit', name: 'junit', version: '4.12' -} \ No newline at end of file diff --git a/core-kotlin/gradle/wrapper/gradle-wrapper.jar b/core-kotlin/gradle/wrapper/gradle-wrapper.jar deleted file mode 100755 index 01b8bf6b1f..0000000000 Binary files a/core-kotlin/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/core-kotlin/gradle/wrapper/gradle-wrapper.properties b/core-kotlin/gradle/wrapper/gradle-wrapper.properties deleted file mode 100755 index 0b83b5a3e3..0000000000 --- a/core-kotlin/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip diff --git a/core-kotlin/gradlew b/core-kotlin/gradlew deleted file mode 100755 index cccdd3d517..0000000000 --- a/core-kotlin/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env sh - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/core-kotlin/gradlew.bat b/core-kotlin/gradlew.bat deleted file mode 100755 index e95643d6a2..0000000000 --- a/core-kotlin/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml deleted file mode 100644 index 5fe8a47f62..0000000000 --- a/core-kotlin/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - 4.0.0 - core-kotlin - core-kotlin - jar - - - com.baeldung - parent-kotlin - 1.0.0-SNAPSHOT - ../parent-kotlin - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - com.h2database - h2 - ${h2.version} - - - com.github.kittinunf.fuel - fuel - ${fuel.version} - - - com.github.kittinunf.fuel - fuel-gson - ${fuel.version} - - - com.github.kittinunf.fuel - fuel-rxjava - ${fuel.version} - - - com.github.kittinunf.fuel - fuel-coroutines - ${fuel.version} - - - nl.komponents.kovenant - kovenant - ${kovenant.version} - pom - - - uy.kohesive.injekt - injekt-core - ${injekt-core.version} - - - - - 1.1.1 - 5.2.0 - 3.10.0 - 1.15.0 - 3.3.0 - 1.16.1 - - - diff --git a/core-kotlin/resources/logback.xml b/core-kotlin/resources/logback.xml deleted file mode 100755 index 274cdcdb02..0000000000 --- a/core-kotlin/resources/logback.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - \ No newline at end of file diff --git a/core-kotlin/settings.gradle b/core-kotlin/settings.gradle deleted file mode 100755 index 13bbce9583..0000000000 --- a/core-kotlin/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ -rootProject.name = 'KtorWithKotlin' - diff --git a/core-scala/pom.xml b/core-scala/pom.xml index d6793cf4c6..d72727dd39 100644 --- a/core-scala/pom.xml +++ b/core-scala/pom.xml @@ -28,7 +28,7 @@ net.alchim31.maven scala-maven-plugin - 3.3.2 + ${scala.plugin.version} @@ -49,6 +49,7 @@ 2.12.7 + 3.3.2 diff --git a/core-scala/src/test/scala/com/baeldung/scala/RegexUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/RegexUnitTest.scala new file mode 100644 index 0000000000..94263d620a --- /dev/null +++ b/core-scala/src/test/scala/com/baeldung/scala/RegexUnitTest.scala @@ -0,0 +1,73 @@ +package com.baeldung.scala + +import org.junit.Test +import org.junit.Assert.assertEquals + +class RegexUnitTest { + private val polishPostalCode = "([0-9]{2})\\-([0-9]{3})".r + private val timestamp = "([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{3})".r + private val timestampUnanchored = timestamp.unanchored + + @Test + def givenRegularExpression_whenCallingFindFirstIn_thenShouldFindCorrectMatches(): Unit = { + val postCode = polishPostalCode.findFirstIn("Warsaw 01-011, Jerusalem Avenue") + assertEquals(Some("01-011"), postCode) + } + + @Test + def givenRegularExpression_whenCallingFindFirstMatchIn_thenShouldFindCorrectMatches(): Unit = { + val postCodes = polishPostalCode.findFirstMatchIn("Warsaw 01-011, Jerusalem Avenue") + assertEquals(Some("011"), for (m <- postCodes) yield m.group(2)) + } + + @Test + def givenRegularExpression_whenCallingFindAllIn_thenShouldFindCorrectMatches(): Unit = { + val postCodes = polishPostalCode.findAllIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue") + .toList + assertEquals(List("01-011", "30-059"), postCodes) + + polishPostalCode.findAllIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue") + } + + @Test + def givenRegularExpression_whenCallingFindAlMatchlIn_thenShouldFindCorrectMatches(): Unit = { + val postCodes = polishPostalCode.findAllMatchIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue") + .toList + val postalDistricts = for (m <- postCodes) yield m.group(1) + assertEquals(List("01", "30"), postalDistricts) + } + + @Test + def givenRegularExpression_whenExtractingValues_thenShouldExtractCorrectValues(): Unit = { + val description = "11:34:01.411" match { + case timestamp(hour, minutes, _, _) => s"It's $minutes minutes after $hour" + } + + assertEquals("It's 34 minutes after 11", description) + } + + @Test + def givenUnanchoredRegularExpression_whenExtractingValues_thenShouldExtractCorrectValues(): Unit = { + val description = "Timestamp: 11:34:01.411 error appeared" match { + case timestampUnanchored(hour, minutes, _, _) => s"It's $minutes minutes after $hour" + } + + assertEquals("It's 34 minutes after 11", description) + } + + @Test + def givenRegularExpression_whenCallingReplaceAllIn_thenShouldReplaceText(): Unit = { + val minutes = timestamp.replaceAllIn("11:34:01.311", m => m.group(2)) + + assertEquals("34", minutes) + } + + @Test + def givenRegularExpression_whenCallingReplaceAllInWithMatcher_thenShouldReplaceText(): Unit = { + val secondsThatDayInTotal = timestamp.replaceAllIn("11:34:01.311", _ match { + case timestamp(hours, minutes, seconds, _) => s"$hours-$minutes" + }) + + assertEquals("11-34", secondsThatDayInTotal) + } +} diff --git a/data-structures/pom.xml b/data-structures/pom.xml index e8f4628062..f4a8ea3a14 100644 --- a/data-structures/pom.xml +++ b/data-structures/pom.xml @@ -12,6 +12,21 @@ 1.0.0-SNAPSHOT + + + github.release.repo + https://raw.github.com/bulldog2011/bulldog-repo/master/repo/releases/ + + + + + + com.leansoft + bigqueue + 0.7.0 + + + diff --git a/data-structures/src/test/java/com/baeldung/bigqueue/BigQueueLiveTest.java b/data-structures/src/test/java/com/baeldung/bigqueue/BigQueueLiveTest.java new file mode 100644 index 0000000000..c0305a7ca3 --- /dev/null +++ b/data-structures/src/test/java/com/baeldung/bigqueue/BigQueueLiveTest.java @@ -0,0 +1,82 @@ +package com.baeldung.bigqueue; + +import com.leansoft.bigqueue.BigQueueImpl; +import com.leansoft.bigqueue.IBigQueue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@RunWith(JUnit4.class) +public class BigQueueLiveTest { + + private IBigQueue bigQueue; + + @Before + public void setup() throws IOException { + String queueDir = System.getProperty("user.home"); + String queueName = "baeldung-queue"; + bigQueue = new BigQueueImpl(queueDir, queueName); + } + + @After + public void emptyQueue() throws IOException { + bigQueue.removeAll(); + bigQueue.gc(); + bigQueue.close(); + } + + @Test + public void whenAddingRecords_ThenTheSizeIsCorrect() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + + assertEquals(100, bigQueue.size()); + } + + @Test + public void whenAddingRecords_ThenTheyCanBeRetrieved() throws IOException { + bigQueue.enqueue(String.valueOf("new_record").getBytes()); + + String record = new String(bigQueue.dequeue()); + assertEquals("new_record", record); + } + + @Test + public void whenDequeueingRecords_ThenTheyAreConsumed() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + bigQueue.dequeue(); + + assertEquals(99, bigQueue.size()); + } + + @Test + public void whenPeekingRecords_ThenSizeDoesntChange() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + String firstRecord = new String(bigQueue.peek()); + + assertEquals("1", firstRecord); + assertEquals(100, bigQueue.size()); + } + + @Test + public void whenEmptyingTheQueue_ThenItSizeIs0() throws IOException { + for (int i = 1; i <= 100; i++) { + bigQueue.enqueue(String.valueOf(i).getBytes()); + } + bigQueue.removeAll(); + + assertEquals(0, bigQueue.size()); + } + +} diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index 0e84fa1516..c143b86ff8 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -44,12 +44,13 @@ org.apache.httpcomponents httpclient - 4.3.5 + ${httpclient.version} 0.9.1 + 4.3.5 diff --git a/dropwizard/README.md b/dropwizard/README.md new file mode 100644 index 0000000000..e713b2f1e6 --- /dev/null +++ b/dropwizard/README.md @@ -0,0 +1 @@ +# Dropwizard \ No newline at end of file diff --git a/dropwizard/pom.xml b/dropwizard/pom.xml new file mode 100644 index 0000000000..ddc9aa1949 --- /dev/null +++ b/dropwizard/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + dropwizard + 0.0.1-SNAPSHOT + dropwizard + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + io.dropwizard + dropwizard-core + ${dropwizard.version} + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + true + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + package + + shade + + + + + + com.baeldung.dropwizard.introduction.IntroductionApplication + + + + + + + + + + + 2.0.0 + + + \ No newline at end of file diff --git a/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/IntroductionApplication.java b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/IntroductionApplication.java new file mode 100644 index 0000000000..d9af590017 --- /dev/null +++ b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/IntroductionApplication.java @@ -0,0 +1,51 @@ +package com.baeldung.dropwizard.introduction; + +import com.baeldung.dropwizard.introduction.configuration.ApplicationHealthCheck; +import com.baeldung.dropwizard.introduction.configuration.BasicConfiguration; +import com.baeldung.dropwizard.introduction.domain.Brand; +import com.baeldung.dropwizard.introduction.repository.BrandRepository; +import com.baeldung.dropwizard.introduction.resource.BrandResource; +import io.dropwizard.Application; +import io.dropwizard.configuration.ResourceConfigurationSourceProvider; +import io.dropwizard.setup.Bootstrap; +import io.dropwizard.setup.Environment; + +import java.util.ArrayList; +import java.util.List; + +public class IntroductionApplication extends Application { + + public static void main(final String[] args) throws Exception { + new IntroductionApplication().run("server", "introduction-config.yml"); + } + + @Override + public void run(final BasicConfiguration basicConfiguration, final Environment environment) { + final int defaultSize = basicConfiguration.getDefaultSize(); + final BrandRepository brandRepository = new BrandRepository(initBrands()); + final BrandResource brandResource = new BrandResource(defaultSize, brandRepository); + environment + .jersey() + .register(brandResource); + + final ApplicationHealthCheck healthCheck = new ApplicationHealthCheck(); + environment + .healthChecks() + .register("application", healthCheck); + } + + @Override + public void initialize(final Bootstrap bootstrap) { + bootstrap.setConfigurationSourceProvider(new ResourceConfigurationSourceProvider()); + super.initialize(bootstrap); + } + + private List initBrands() { + final List brands = new ArrayList<>(); + brands.add(new Brand(1L, "Brand1")); + brands.add(new Brand(2L, "Brand2")); + brands.add(new Brand(3L, "Brand3")); + + return brands; + } +} diff --git a/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/configuration/ApplicationHealthCheck.java b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/configuration/ApplicationHealthCheck.java new file mode 100644 index 0000000000..bf4b710937 --- /dev/null +++ b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/configuration/ApplicationHealthCheck.java @@ -0,0 +1,10 @@ +package com.baeldung.dropwizard.introduction.configuration; + +import com.codahale.metrics.health.HealthCheck; + +public class ApplicationHealthCheck extends HealthCheck { + @Override + protected Result check() throws Exception { + return Result.healthy(); + } +} diff --git a/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/configuration/BasicConfiguration.java b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/configuration/BasicConfiguration.java new file mode 100644 index 0000000000..5098f89d62 --- /dev/null +++ b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/configuration/BasicConfiguration.java @@ -0,0 +1,20 @@ +package com.baeldung.dropwizard.introduction.configuration; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.dropwizard.Configuration; + +import javax.validation.constraints.NotNull; + +public class BasicConfiguration extends Configuration { + @NotNull private final int defaultSize; + + @JsonCreator + public BasicConfiguration(@JsonProperty("defaultSize") final int defaultSize) { + this.defaultSize = defaultSize; + } + + public int getDefaultSize() { + return defaultSize; + } +} diff --git a/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/domain/Brand.java b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/domain/Brand.java new file mode 100644 index 0000000000..c83f67bb6e --- /dev/null +++ b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/domain/Brand.java @@ -0,0 +1,19 @@ +package com.baeldung.dropwizard.introduction.domain; + +public class Brand { + private final Long id; + private final String name; + + public Brand(final Long id, final String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } +} diff --git a/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/repository/BrandRepository.java b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/repository/BrandRepository.java new file mode 100644 index 0000000000..3f187df3de --- /dev/null +++ b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/repository/BrandRepository.java @@ -0,0 +1,32 @@ +package com.baeldung.dropwizard.introduction.repository; + +import com.baeldung.dropwizard.introduction.domain.Brand; +import com.google.common.collect.ImmutableList; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +public class BrandRepository { + private final List brands; + + public BrandRepository(final List brands) { + this.brands = ImmutableList.copyOf(brands); + } + + public List findAll(final int size) { + return brands + .stream() + .limit(size) + .collect(Collectors.toList()); + } + + public Optional findById(final Long id) { + return brands + .stream() + .filter(brand -> brand + .getId() + .equals(id)) + .findFirst(); + } +} diff --git a/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/resource/BrandResource.java b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/resource/BrandResource.java new file mode 100644 index 0000000000..5f97e26faf --- /dev/null +++ b/dropwizard/src/main/java/com/baeldung/dropwizard/introduction/resource/BrandResource.java @@ -0,0 +1,35 @@ +package com.baeldung.dropwizard.introduction.resource; + +import com.baeldung.dropwizard.introduction.domain.Brand; +import com.baeldung.dropwizard.introduction.repository.BrandRepository; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.List; +import java.util.Optional; + +@Path("/brands") +@Produces(MediaType.APPLICATION_JSON) +public class BrandResource { + private final int defaultSize; + private final BrandRepository brandRepository; + + public BrandResource(final int defaultSize, final BrandRepository brandRepository) { + this.defaultSize = defaultSize; + this.brandRepository = brandRepository; + + } + + @GET + public List getBrands(@QueryParam("size") final Optional size) { + return brandRepository.findAll(size.orElse(defaultSize)); + } + + @GET + @Path("/{id}") + public Brand getById(@PathParam("id") final Long id) { + return brandRepository + .findById(id) + .orElseThrow(RuntimeException::new); + } +} diff --git a/dropwizard/src/main/resources/introduction-config.yml b/dropwizard/src/main/resources/introduction-config.yml new file mode 100644 index 0000000000..02ff36de05 --- /dev/null +++ b/dropwizard/src/main/resources/introduction-config.yml @@ -0,0 +1 @@ +defaultSize: 5 \ No newline at end of file diff --git a/dropwizard/src/test/java/com/baeldung/dropwizard/introduction/repository/BrandRepositoryUnitTest.java b/dropwizard/src/test/java/com/baeldung/dropwizard/introduction/repository/BrandRepositoryUnitTest.java new file mode 100644 index 0000000000..b996883ee5 --- /dev/null +++ b/dropwizard/src/test/java/com/baeldung/dropwizard/introduction/repository/BrandRepositoryUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.dropwizard.introduction.repository; + +import com.baeldung.dropwizard.introduction.domain.Brand; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class BrandRepositoryUnitTest { + + private static final Brand BRAND_1 = new Brand(1L, "Brand1"); + + private final BrandRepository brandRepository = new BrandRepository(getBrands()); + + @Test + void givenSize_whenFindingAll_thenReturnList() { + final int size = 2; + + final List result = brandRepository.findAll(size); + + assertEquals(size, result.size()); + } + + @Test + void givenId_whenFindingById_thenReturnFoundBrand() { + final Long id = BRAND_1.getId(); + + final Optional result = brandRepository.findById(id); + + Assertions.assertTrue(result.isPresent()); + assertEquals(BRAND_1, result.get()); + } + + + private List getBrands() { + final List brands = new ArrayList<>(); + brands.add(BRAND_1); + brands.add(new Brand(2L, "Brand2")); + brands.add(new Brand(3L, "Brand3")); + + return brands; + } +} \ No newline at end of file diff --git a/ethereum/pom.xml b/ethereum/pom.xml index 6fc31208d2..da0a7ebda8 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -175,10 +175,10 @@ maven-compiler-plugin - 3.1 + ${compiler.plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} @@ -215,5 +215,8 @@ 1.2.3 1.7.25 2.0.4.RELEASE + 3.1 + 1.8 + 1.8 diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml index e79b43c5e5..37e423b3af 100644 --- a/google-web-toolkit/pom.xml +++ b/google-web-toolkit/pom.xml @@ -63,7 +63,7 @@ net.ltgt.gwt.maven gwt-maven-plugin - 1.0-rc-8 + ${gwt.plugin.version} @@ -78,7 +78,7 @@ true - 1.8 + ${maven.compiler.source} @@ -98,7 +98,7 @@ maven-surefire-plugin - 2.17 + ${surefire.plugin.version} true @@ -119,6 +119,8 @@ UTF-8 UTF-8 2.8.2 + 1.0-rc-8 + 2.17 diff --git a/graphql/graphql-java/pom.xml b/graphql/graphql-java/pom.xml index 3613d89ae7..793a02458a 100644 --- a/graphql/graphql-java/pom.xml +++ b/graphql/graphql-java/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../.. diff --git a/guest/core-kotlin/pom.xml b/guest/core-kotlin/pom.xml index 2d4a0c6144..ad0368c6ab 100644 --- a/guest/core-kotlin/pom.xml +++ b/guest/core-kotlin/pom.xml @@ -46,19 +46,19 @@ org.jetbrains.spek spek-api - 1.1.5 + ${spek.api.version} test org.jetbrains.spek spek-subject-extension - 1.1.5 + ${spek.subject.version} test org.jetbrains.spek spek-junit-platform-engine - 1.1.5 + ${spek.junit.version} test @@ -195,6 +195,9 @@ 5.2.0 3.10.0 3.7.0 + 1.1.5 + 1.1.5 + 1.1.5 diff --git a/intelliJ/remote-debugging/pom.xml b/intelliJ/remote-debugging/pom.xml index d18625e8f6..b8845e49d2 100644 --- a/intelliJ/remote-debugging/pom.xml +++ b/intelliJ/remote-debugging/pom.xml @@ -9,13 +9,16 @@ gs-scheduling-tasks - org.springframework.boot - spring-boot-starter-parent - 2.1.6.RELEASE + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 1.8 + 3.1.2 + 2.1.6.RELEASE @@ -31,7 +34,7 @@ org.awaitility awaitility - 3.1.2 + ${awaitility.version} test @@ -44,5 +47,4 @@ - diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml index 912a2cabac..a2d9443d67 100644 --- a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml +++ b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml @@ -12,12 +12,16 @@ java-ee-8-security-api 1.0-SNAPSHOT + + + 4.0.4 + com.unboundid unboundid-ldapsdk - 4.0.4 + ${unboundid.ldapsdk.version} diff --git a/java-numbers-2/pom.xml b/java-numbers-2/pom.xml index ba40ef0a38..5c81b00756 100644 --- a/java-numbers-2/pom.xml +++ b/java-numbers-2/pom.xml @@ -21,6 +21,11 @@ jmh-generator-annprocess ${jmh-generator.version} + + it.unimi.dsi + dsiutils + ${dsiutils.version} + @@ -33,4 +38,8 @@ + + 2.6.0 + + diff --git a/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java b/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java index 68382c26ea..7af8c5d58d 100644 --- a/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java +++ b/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java @@ -7,7 +7,7 @@ public class BruteForcePrimeChecker implements PrimeChecker { @Override public boolean isPrime(Integer number) { - return number > 2 ? IntStream.range(2, number) + return number > 1 ? IntStream.range(2, number) .noneMatch(n -> (number % n == 0)) : false; } diff --git a/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java b/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java index 3dc372ad22..3019c76eb4 100644 --- a/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java +++ b/java-numbers-2/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java @@ -6,7 +6,7 @@ public class OptimisedPrimeChecker implements PrimeChecker { @Override public boolean isPrime(Integer number) { - return number > 2 ? IntStream.rangeClosed(2, (int) Math.sqrt(number)) + return number > 1 ? IntStream.rangeClosed(2, (int) Math.sqrt(number)) .noneMatch(n -> (number % n == 0)) : false; } diff --git a/java-numbers-2/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java index 9f8ba8defd..6e425b3051 100644 --- a/java-numbers-2/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java +++ b/java-numbers-2/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java @@ -11,22 +11,24 @@ public class PrimeCheckerUnitTest { @Test public void whenCheckIsPrime_thenTrue() { - assertTrue(primeChecker.isPrime(13l)); + assertTrue(primeChecker.isPrime(2L)); + assertTrue(primeChecker.isPrime(13L)); assertTrue(primeChecker.isPrime(1009L)); assertTrue(primeChecker.isPrime(74207281L)); } @Test public void whenCheckIsPrime_thenFalse() { - assertTrue(!primeChecker.isPrime(50L)); - assertTrue(!primeChecker.isPrime(1001L)); - assertTrue(!primeChecker.isPrime(74207282L)); + assertFalse(primeChecker.isPrime(50L)); + assertFalse(primeChecker.isPrime(1001L)); + assertFalse(primeChecker.isPrime(74207282L)); } private final BruteForcePrimeChecker bfPrimeChecker = new BruteForcePrimeChecker(); @Test public void whenBFCheckIsPrime_thenTrue() { + assertTrue(bfPrimeChecker.isPrime(2)); assertTrue(bfPrimeChecker.isPrime(13)); assertTrue(bfPrimeChecker.isPrime(1009)); } @@ -41,6 +43,7 @@ public class PrimeCheckerUnitTest { @Test public void whenOptCheckIsPrime_thenTrue() { + assertTrue(optimisedPrimeChecker.isPrime(2)); assertTrue(optimisedPrimeChecker.isPrime(13)); assertTrue(optimisedPrimeChecker.isPrime(1009)); } @@ -55,6 +58,7 @@ public class PrimeCheckerUnitTest { @Test public void whenPrimesCheckIsPrime_thenTrue() { + assertTrue(primesPrimeChecker.isPrime(2)); assertTrue(primesPrimeChecker.isPrime(13)); assertTrue(primesPrimeChecker.isPrime(1009)); } diff --git a/java-numbers-3/pom.xml b/java-numbers-3/pom.xml index 3dd8e16bc7..e3c64064c7 100644 --- a/java-numbers-3/pom.xml +++ b/java-numbers-3/pom.xml @@ -12,6 +12,14 @@ 0.0.1-SNAPSHOT ../parent-java + + + + it.unimi.dsi + dsiutils + 2.6.0 + + java-numbers-3 diff --git a/java-numbers-3/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java b/java-numbers-3/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java new file mode 100644 index 0000000000..50a072371e --- /dev/null +++ b/java-numbers-3/src/main/java/com/baeldung/randomnumbers/RandomNumbersGenerator.java @@ -0,0 +1,103 @@ +package com.baeldung.randomnumbers; + +import java.security.SecureRandom; +import java.util.Random; +import java.util.SplittableRandom; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.IntStream; + +import org.apache.commons.math3.random.RandomDataGenerator; + +import it.unimi.dsi.util.XoRoShiRo128PlusRandom; + +public class RandomNumbersGenerator { + + public Integer generateRandomWithMathRandom(int max, int min) { + return (int) ((Math.random() * (max - min)) + min); + } + + public Integer generateRandomWithNextInt() { + Random random = new Random(); + int randomWithNextInt = random.nextInt(); + return randomWithNextInt; + } + + public Integer generateRandomWithNextIntWithinARange(int min, int max) { + Random random = new Random(); + int randomWintNextIntWithinARange = random.nextInt(max - min) + min; + return randomWintNextIntWithinARange; + } + + public IntStream generateRandomUnlimitedIntStream() { + Random random = new Random(); + IntStream unlimitedIntStream = random.ints(); + return unlimitedIntStream; + } + + public IntStream generateRandomLimitedIntStream(long streamSize) { + Random random = new Random(); + IntStream limitedIntStream = random.ints(streamSize); + return limitedIntStream; + } + + public IntStream generateRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) { + Random random = new Random(); + IntStream limitedIntStreamWithinARange = random.ints(streamSize, min, max); + return limitedIntStreamWithinARange; + } + + public Integer generateRandomWithThreadLocalRandom() { + int randomWithThreadLocalRandom = ThreadLocalRandom.current() + .nextInt(); + return randomWithThreadLocalRandom; + } + + public Integer generateRandomWithThreadLocalRandomInARange(int min, int max) { + int randomWithThreadLocalRandomInARange = ThreadLocalRandom.current() + .nextInt(min, max); + return randomWithThreadLocalRandomInARange; + } + + public Integer generateRandomWithThreadLocalRandomFromZero(int max) { + int randomWithThreadLocalRandomFromZero = ThreadLocalRandom.current() + .nextInt(max); + return randomWithThreadLocalRandomFromZero; + } + + public Integer generateRandomWithSplittableRandom(int min, int max) { + SplittableRandom splittableRandom = new SplittableRandom(); + int randomWithSplittableRandom = splittableRandom.nextInt(min, max); + return randomWithSplittableRandom; + } + + public IntStream generateRandomWithSplittableRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) { + SplittableRandom splittableRandom = new SplittableRandom(); + IntStream limitedIntStreamWithinARangeWithSplittableRandom = splittableRandom.ints(streamSize, min, max); + return limitedIntStreamWithinARangeWithSplittableRandom; + } + + public Integer generateRandomWithSecureRandom() { + SecureRandom secureRandom = new SecureRandom(); + int randomWithSecureRandom = secureRandom.nextInt(); + return randomWithSecureRandom; + } + + public Integer generateRandomWithSecureRandomWithinARange(int min, int max) { + SecureRandom secureRandom = new SecureRandom(); + int randomWithSecureRandomWithinARange = secureRandom.nextInt(max - min) + min; + return randomWithSecureRandomWithinARange; + } + + public Integer generateRandomWithRandomDataGenerator(int min, int max) { + RandomDataGenerator randomDataGenerator = new RandomDataGenerator(); + int randomWithRandomDataGenerator = randomDataGenerator.nextInt(min, max); + return randomWithRandomDataGenerator; + } + + public Integer generateRandomWithXoRoShiRo128PlusRandom(int min, int max) { + XoRoShiRo128PlusRandom xoroRandom = new XoRoShiRo128PlusRandom(); + int randomWithXoRoShiRo128PlusRandom = xoroRandom.nextInt(max - min) + min; + return randomWithXoRoShiRo128PlusRandom; + } + +} diff --git a/java-numbers-3/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java new file mode 100644 index 0000000000..bdd955a4ee --- /dev/null +++ b/java-numbers-3/src/test/java/com/baeldung/randomnumbers/RandomNumbersGeneratorUnitTest.java @@ -0,0 +1,154 @@ +package com.baeldung.randomnumbers; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.stream.IntStream; + +import org.junit.Test; + +public class RandomNumbersGeneratorUnitTest { + + private static final int MIN_RANGE = 1; + private static final int MAX_RANGE = 10; + private static final int MIN_RANGE_NEGATIVE = -10; + private static final int ITERATIONS = 50; + private static final long STREAM_SIZE = 50; + + @Test + public void whenGenerateRandomWithMathRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumer = generator.generateRandomWithMathRandom(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumer, MIN_RANGE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithNextInt_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithNextInt(); + assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } + } + + @Test + public void whenGenerateRandomWithNextIntWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithNextIntWithinARange(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomUnlimitedIntStream_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + IntStream stream = generator.generateRandomUnlimitedIntStream(); + assertNotNull(stream); + Integer randomNumber = stream.findFirst() + .getAsInt(); + assertNotNull(randomNumber); + assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } + + @Test + public void whenGenerateRandomLimitedIntStream_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + generator.generateRandomLimitedIntStream(STREAM_SIZE) + .forEach(randomNumber -> assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE))); + } + + @Test + public void whenGenerateRandomLimitedIntStreamWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + generator.generateRandomLimitedIntStreamWithinARange(MIN_RANGE, MAX_RANGE, STREAM_SIZE) + .forEach(randomNumber -> assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE))); + } + + @Test + public void whenGenerateRandomWithThreadLocalRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithThreadLocalRandom(); + assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } + } + + @Test + public void whenGenerateRandomWithThreadLocalRandomInARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithThreadLocalRandomInARange(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithThreadLocalRandomFromZero_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithThreadLocalRandomFromZero(MAX_RANGE); + assertTrue(isInRange(randomNumber, 0, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithSplittableRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithSplittableRandom(MIN_RANGE_NEGATIVE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE_NEGATIVE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithSplittableRandomLimitedIntStreamWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + generator.generateRandomWithSplittableRandomLimitedIntStreamWithinARange(MIN_RANGE, MAX_RANGE, STREAM_SIZE) + .forEach(randomNumber -> assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE))); + } + + @Test + public void whenGenerateRandomWithSecureRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithSecureRandom(); + assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } + } + + @Test + public void whenGenerateRandomWithSecureRandomWithinARange_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithSecureRandomWithinARange(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)); + } + } + + @Test + public void whenGenerateRandomWithRandomDataGenerator_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithRandomDataGenerator(MIN_RANGE, MAX_RANGE); + // RandomDataGenerator top is inclusive + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE + 1)); + } + } + + @Test + public void whenGenerateRandomWithXoRoShiRo128PlusRandom_returnsSuccessfully() { + RandomNumbersGenerator generator = new RandomNumbersGenerator(); + for (int i = 0; i < ITERATIONS; i++) { + int randomNumber = generator.generateRandomWithXoRoShiRo128PlusRandom(MIN_RANGE, MAX_RANGE); + assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)); + } + } + + private boolean isInRange(int number, int min, int max) { + return min <= number && number < max; + } + +} diff --git a/jee-7/pom.xml b/jee-7/pom.xml index 635d820c2b..a2593e46a5 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -118,7 +118,7 @@ javax.mvc javax.mvc-api - 20160715 + ${mvc.api.version} org.glassfish.ozark @@ -215,7 +215,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} @@ -506,6 +506,8 @@ + 1.0.0 + 20160715 1.8 3.0.0 7.0 diff --git a/jee-kotlin/pom.xml b/jee-kotlin/pom.xml index 80c5ea4e22..9191885bd4 100644 --- a/jee-kotlin/pom.xml +++ b/jee-kotlin/pom.xml @@ -253,7 +253,7 @@ org.wildfly.arquillian wildfly-arquillian-container-remote - 2.2.0.Final + ${wildfly.arquillian.version} test @@ -261,6 +261,7 @@ + 2.2.0.Final UTF-8 false 8.0 diff --git a/jhipster/jhipster-microservice/car-app/pom.xml b/jhipster/jhipster-microservice/car-app/pom.xml index 86d94d0a44..c53ea8358e 100644 --- a/jhipster/jhipster-microservice/car-app/pom.xml +++ b/jhipster/jhipster-microservice/car-app/pom.xml @@ -17,6 +17,7 @@ + 1.0.0 -Djava.security.egd=file:/dev/./urandom -Xmx256m 3.6.2 2.0.0 @@ -433,7 +434,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} diff --git a/jhipster/jhipster-microservice/dealer-app/pom.xml b/jhipster/jhipster-microservice/dealer-app/pom.xml index 3051399ae6..a0bcc73e31 100644 --- a/jhipster/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster/jhipster-microservice/dealer-app/pom.xml @@ -92,6 +92,7 @@ 1.4.10.Final 1.1.0.Final v0.21.3 + 1.0.0 @@ -427,7 +428,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} diff --git a/jhipster/jhipster-microservice/gateway-app/pom.xml b/jhipster/jhipster-microservice/gateway-app/pom.xml index 4e2c19ed2d..c6dcbb3f3e 100644 --- a/jhipster/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster/jhipster-microservice/gateway-app/pom.xml @@ -96,6 +96,7 @@ 1.4.10.Final 1.1.0.Final v0.21.3 + 1.0.0 @@ -469,7 +470,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml index 12dead99df..04f790faf5 100644 --- a/jhipster/jhipster-monolithic/pom.xml +++ b/jhipster/jhipster-monolithic/pom.xml @@ -302,7 +302,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} @@ -398,8 +398,8 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${source.version} + ${target.version} org.mapstruct @@ -881,6 +881,9 @@ + 1.8 + 1.8 + 1.0.0 -Djava.security.egd=file:/dev/./urandom -Xmx256m 3.6.2 2.0.0 diff --git a/jhipster/jhipster-uaa/gateway/pom.xml b/jhipster/jhipster-uaa/gateway/pom.xml index 0f815bedad..1b85877a9b 100644 --- a/jhipster/jhipster-uaa/gateway/pom.xml +++ b/jhipster/jhipster-uaa/gateway/pom.xml @@ -236,7 +236,7 @@ org.zalando problem-spring-web - 0.24.0-RC.0 + ${spring.web.version} org.springframework.security.oauth @@ -559,7 +559,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} @@ -1012,6 +1012,8 @@ + 1.0.0 + 0.24.0-RC.0 3.0.0 1.8 diff --git a/jhipster/jhipster-uaa/uaa/pom.xml b/jhipster/jhipster-uaa/uaa/pom.xml index 2c4dd9d0f0..27a056820d 100644 --- a/jhipster/jhipster-uaa/uaa/pom.xml +++ b/jhipster/jhipster-uaa/uaa/pom.xml @@ -232,7 +232,7 @@ org.zalando problem-spring-web - 0.24.0-RC.0 + ${spring.web.version} org.springframework.security.oauth @@ -543,7 +543,7 @@ org.eclipse.m2e lifecycle-mapping - 1.0.0 + ${lifecycle.mapping.version} @@ -834,6 +834,8 @@ + 1.0.0 + 0.24.0-RC.0 3.0.0 1.8 diff --git a/json-2/README.md b/json-2/README.md new file mode 100644 index 0000000000..e7c3043339 --- /dev/null +++ b/json-2/README.md @@ -0,0 +1,5 @@ +## JSON + +This module contains articles about JSON. + +### Relevant Articles: diff --git a/json-2/pom.xml b/json-2/pom.xml new file mode 100644 index 0000000000..72b3295b2b --- /dev/null +++ b/json-2/pom.xml @@ -0,0 +1,41 @@ + + + com.baeldung + json-2 + 0.0.1-SNAPSHOT + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + + + com.jsoniter + jsoniter + ${jsoniter.version} + + + + junit + junit + ${junit.version} + test + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + 0.9.23 + 3.11.1 + + diff --git a/json-2/src/main/java/com/baeldung/jsoniter/model/Name.java b/json-2/src/main/java/com/baeldung/jsoniter/model/Name.java new file mode 100644 index 0000000000..ed5e221235 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsoniter/model/Name.java @@ -0,0 +1,22 @@ +package com.baeldung.jsoniter.model; + +public class Name { + private String firstName; + private String surname; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } +} diff --git a/json-2/src/main/java/com/baeldung/jsoniter/model/Student.java b/json-2/src/main/java/com/baeldung/jsoniter/model/Student.java new file mode 100644 index 0000000000..07c73dd18e --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsoniter/model/Student.java @@ -0,0 +1,26 @@ +package com.baeldung.jsoniter.model; + +import com.jsoniter.annotation.JsonProperty; +import com.jsoniter.fuzzy.MaybeStringIntDecoder; + +public class Student { + @JsonProperty(decoder = MaybeStringIntDecoder.class) + private int id; + private Name name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Name getName() { + return name; + } + + public void setName(Name name) { + this.name = name; + } +} diff --git a/json-2/src/test/java/com/baeldung/jsoniter/JsoniterIntroUnitTest.java b/json-2/src/test/java/com/baeldung/jsoniter/JsoniterIntroUnitTest.java new file mode 100644 index 0000000000..09f82567a2 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/jsoniter/JsoniterIntroUnitTest.java @@ -0,0 +1,85 @@ +package com.baeldung.jsoniter; + +import com.baeldung.jsoniter.model.Name; +import com.baeldung.jsoniter.model.Student; +import com.jsoniter.JsonIterator; +import com.jsoniter.ValueType; +import com.jsoniter.any.Any; + +import org.junit.Test; + +import static com.jsoniter.ValueType.STRING; +import static org.assertj.core.api.Assertions.assertThat; + +public class JsoniterIntroUnitTest { + + @Test + public void whenParsedUsingBindAPI_thenConvertedToJavaObjectCorrectly() { + String input = "{\"id\":1,\"name\":{\"firstName\":\"Joe\",\"surname\":\"Blogg\"}}"; + + Student student = JsonIterator.deserialize(input, Student.class); + + assertThat(student.getId()).isEqualTo(1); + assertThat(student.getName().getFirstName()).isEqualTo("Joe"); + assertThat(student.getName().getSurname()).isEqualTo("Blogg"); + } + + @Test + public void givenTypeInJsonFuzzy_whenFieldIsMaybeDecoded_thenFieldParsedCorrectly() { + String input = "{\"id\":\"1\",\"name\":{\"firstName\":\"Joe\",\"surname\":\"Blogg\"}}"; + + Student student = JsonIterator.deserialize(input, Student.class); + + assertThat(student.getId()).isEqualTo(1); + } + + @Test + public void whenParsedUsingAnyAPI_thenFieldValueCanBeExtractedUsingTheFieldName() { + String input = "{\"id\":1,\"name\":{\"firstName\":\"Joe\",\"surname\":\"Blogg\"}}"; + + Any any = JsonIterator.deserialize(input); + + assertThat(any.toInt("id")).isEqualTo(1); + assertThat(any.toString("name", "firstName")).isEqualTo("Joe"); + assertThat(any.toString("name", "surname")).isEqualTo("Blogg"); + } + + @Test + public void whenParsedUsingAnyAPI_thenFieldValueTypeIsCorrect() { + String input = "{\"id\":1,\"name\":{\"firstName\":\"Joe\",\"surname\":\"Blogg\"}}"; + + Any any = JsonIterator.deserialize(input); + + assertThat(any.get("id").valueType()).isEqualTo(ValueType.NUMBER); + assertThat(any.get("name").valueType()).isEqualTo(ValueType.OBJECT); + assertThat(any.get("error").valueType()).isEqualTo(ValueType.INVALID); + } + + @Test + public void whenParsedUsingIteratorAPI_thenFieldValuesExtractedCorrectly() throws Exception { + Name name = new Name(); + String input = "{ \"firstName\" : \"Joe\", \"surname\" : \"Blogg\" }"; + JsonIterator iterator = JsonIterator.parse(input); + + for (String field = iterator.readObject(); field != null; field = iterator.readObject()) { + switch (field) { + case "firstName": + if (iterator.whatIsNext() == ValueType.STRING) { + name.setFirstName(iterator.readString()); + } + continue; + case "surname": + if (iterator.whatIsNext() == ValueType.STRING) { + name.setSurname(iterator.readString()); + } + continue; + default: + iterator.skip(); + } + } + + assertThat(name.getFirstName()).isEqualTo("Joe"); + assertThat(name.getSurname()).isEqualTo("Blogg"); + } + +} diff --git a/json-2/src/test/resources/Student.json b/json-2/src/test/resources/Student.json new file mode 100644 index 0000000000..7ff3351e8e --- /dev/null +++ b/json-2/src/test/resources/Student.json @@ -0,0 +1 @@ +{"id":1,"name":{"firstName": "Joe", "surname":"Blogg"}} diff --git a/kotlin-libraries-2/README.md b/kotlin-libraries-2/README.md index 4064ef67d8..f725048acd 100644 --- a/kotlin-libraries-2/README.md +++ b/kotlin-libraries-2/README.md @@ -8,4 +8,7 @@ This module contains articles about Kotlin Libraries. - [Introduction to RxKotlin](https://www.baeldung.com/rxkotlin) - [MockK: A Mocking Library for Kotlin](https://www.baeldung.com/kotlin-mockk) - [Kotlin Immutable Collections](https://www.baeldung.com/kotlin-immutable-collections) +- [Dependency Injection for Kotlin with Injekt](https://www.baeldung.com/kotlin-dependency-injection-with-injekt) +- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel) +- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant) - More articles: [[<-- prev]](/kotlin-libraries) diff --git a/kotlin-libraries-2/pom.xml b/kotlin-libraries-2/pom.xml index 518142403e..27dc91d156 100644 --- a/kotlin-libraries-2/pom.xml +++ b/kotlin-libraries-2/pom.xml @@ -39,6 +39,37 @@ kotlinx-collections-immutable ${kotlinx-collections-immutable.version} + + uy.kohesive.injekt + injekt-core + ${injekt-core.version} + + + com.github.kittinunf.fuel + fuel + ${fuel.version} + + + com.github.kittinunf.fuel + fuel-gson + ${fuel.version} + + + com.github.kittinunf.fuel + fuel-rxjava + ${fuel.version} + + + com.github.kittinunf.fuel + fuel-coroutines + ${fuel.version} + + + nl.komponents.kovenant + kovenant + ${kovenant.version} + pom + io.mockk @@ -49,6 +80,9 @@ + 1.16.1 + 1.15.0 + 3.3.0 27.1-jre 1.9.3 0.1 diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/Interceptors.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Interceptors.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/fuel/Interceptors.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Interceptors.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Post.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Post.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/injekt/DelegateInjectionApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/DelegateInjectionApplication.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/injekt/DelegateInjectionApplication.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/DelegateInjectionApplication.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt similarity index 80% rename from core-kotlin/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt index 744459b7fe..4205678981 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt +++ b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt @@ -1,8 +1,12 @@ package com.baeldung.injekt import org.slf4j.LoggerFactory -import uy.kohesive.injekt.* -import uy.kohesive.injekt.api.* +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.InjektMain +import uy.kohesive.injekt.api.InjektRegistrar +import uy.kohesive.injekt.api.addPerKeyFactory +import uy.kohesive.injekt.api.addSingletonFactory +import uy.kohesive.injekt.api.get class KeyedApplication { companion object : InjektMain() { diff --git a/core-kotlin/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt similarity index 94% rename from core-kotlin/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt index e802f3f6d5..96a0c9556a 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt +++ b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt @@ -1,7 +1,8 @@ package com.baeldung.injekt import org.slf4j.LoggerFactory -import uy.kohesive.injekt.* +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.InjektMain import uy.kohesive.injekt.api.* class ModularApplication { diff --git a/core-kotlin/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt similarity index 84% rename from core-kotlin/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt index a42f314349..f3167bc223 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt +++ b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt @@ -1,8 +1,12 @@ package com.baeldung.injekt import org.slf4j.LoggerFactory -import uy.kohesive.injekt.* -import uy.kohesive.injekt.api.* +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.InjektMain +import uy.kohesive.injekt.api.InjektRegistrar +import uy.kohesive.injekt.api.addPerThreadFactory +import uy.kohesive.injekt.api.addSingletonFactory +import uy.kohesive.injekt.api.get import java.util.* import java.util.concurrent.Executors import java.util.concurrent.TimeUnit diff --git a/core-kotlin/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt similarity index 75% rename from core-kotlin/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt rename to kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt index 2b07cd059f..5c2dc28ba5 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt +++ b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt @@ -1,8 +1,12 @@ package com.baeldung.injekt import org.slf4j.LoggerFactory -import uy.kohesive.injekt.* -import uy.kohesive.injekt.api.* +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.InjektMain +import uy.kohesive.injekt.api.InjektRegistrar +import uy.kohesive.injekt.api.addSingleton +import uy.kohesive.injekt.api.addSingletonFactory +import uy.kohesive.injekt.api.get class SimpleApplication { companion object : InjektMain() { diff --git a/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt rename to kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTest.kt similarity index 99% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt rename to kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTest.kt index 469118f0f6..046b7380f7 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt +++ b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.kovenant import nl.komponents.kovenant.* import nl.komponents.kovenant.Kovenant.deferred @@ -12,6 +12,7 @@ import java.util.* import java.util.concurrent.TimeUnit class KovenantTest { + @Before fun setupTestMode() { Kovenant.testMode { error -> diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTimeoutTest.kt similarity index 96% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt rename to kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTimeoutTest.kt index e37d2cc2fa..d98f9c538f 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt +++ b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTimeoutTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin +package com.baeldung.kovenant import nl.komponents.kovenant.Promise import nl.komponents.kovenant.any diff --git a/kotlin-libraries/README.md b/kotlin-libraries/README.md index 99a57c8293..570bf9b1e5 100644 --- a/kotlin-libraries/README.md +++ b/kotlin-libraries/README.md @@ -10,7 +10,6 @@ This module contains articles about Kotlin Libraries. - [Writing Specifications with Kotlin and Spek](https://www.baeldung.com/kotlin-spek) - [Processing JSON with Kotlin and Klaxson](https://www.baeldung.com/kotlin-json-klaxson) - [Guide to the Kotlin Exposed Framework](https://www.baeldung.com/kotlin-exposed-persistence) -- [Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates) - [Introduction to Arrow in Kotlin](https://www.baeldung.com/kotlin-arrow) - [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor) - [REST API With Kotlin and Kovert](https://www.baeldung.com/kotlin-kovert) diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml index dfd1dc363f..0d6e589377 100644 --- a/kotlin-libraries/pom.xml +++ b/kotlin-libraries/pom.xml @@ -33,19 +33,19 @@ org.jetbrains.spek spek-api - 1.1.5 + ${spek.version} test org.jetbrains.spek spek-subject-extension - 1.1.5 + ${spek.version} test org.jetbrains.spek spek-junit-platform-engine - 1.1.5 + ${spek.version} test @@ -166,6 +166,7 @@ 2.6 2.3.0 0.7.3 + 1.1.5 diff --git a/kotlin-quasar/pom.xml b/kotlin-quasar/pom.xml index a12d27c565..f5fbce6ed7 100644 --- a/kotlin-quasar/pom.xml +++ b/kotlin-quasar/pom.xml @@ -103,7 +103,7 @@ maven-dependency-plugin - 3.1.1 + ${dependency.plugin.version} getClasspathFilenames @@ -116,7 +116,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.1 + ${surefire.plugin.version} -Dco.paralleluniverse.fibers.verifyInstrumentation=true -javaagent:${co.paralleluniverse:quasar-core:jar} @@ -125,7 +125,7 @@ org.codehaus.mojo exec-maven-plugin - 1.3.2 + ${exec.plugin.version} target/classes echo @@ -145,6 +145,9 @@ 1.3.31 1.7.21 1.1.7 + 3.1.1 + 2.22.1 + 1.3.2 diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java index 6749f7fe0a..aa29e4c441 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java @@ -7,6 +7,8 @@ import com.github.jknack.handlebars.Template; import com.github.jknack.handlebars.io.ClassPathTemplateLoader; import com.github.jknack.handlebars.io.TemplateLoader; import java.io.IOException; + +import org.junit.Ignore; import org.junit.Test; /** @@ -18,6 +20,7 @@ public class BuiltinHelperUnitTest { private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html"); + @Ignore @Test public void whenUsedWith_ThenContextChanges() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); @@ -30,6 +33,7 @@ public class BuiltinHelperUnitTest { assertThat(templateString).isEqualTo("\n

I live in World

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

I live in World

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

Baeldung is busy.

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

Hi Baeldung!

\n

This is the page Baeldung

"); } + @Ignore @Test public void whenBlockIsDefined_ThenCanOverrideWithPartial() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index c8980fd309..5a73e19b19 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -8,8 +8,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -23,10 +24,63 @@ lombok ${lombok.version}
+ + + org.springframework.boot + spring-boot-starter-web + + + + net.sourceforge.barbecue + barbecue + ${barbecue.version} + + + + net.sf.barcode4j + barcode4j + ${barcode4j.version} + + + + com.google.zxing + core + ${zxing.version} + + + com.google.zxing + javase + ${zxing.version} + + + + com.github.kenglxn.qrgen + javase + ${qrgen.version} + + + org.cactoos + cactoos + ${cactoos.version} + + + + + jitpack.io + https://jitpack.io + + + 1.78 1.18.6 + 1.5-beta1 + 2.1 + 3.3.0 + 2.6.0 + + 0.43 diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/BarcodesController.java b/libraries-3/src/main/java/com/baeldung/barcodes/BarcodesController.java new file mode 100644 index 0000000000..171d703621 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/barcodes/BarcodesController.java @@ -0,0 +1,99 @@ +package com.baeldung.barcodes; + +import com.baeldung.barcodes.generators.BarbecueBarcodeGenerator; +import com.baeldung.barcodes.generators.Barcode4jBarcodeGenerator; +import com.baeldung.barcodes.generators.QRGenBarcodeGenerator; +import com.baeldung.barcodes.generators.ZxingBarcodeGenerator; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.awt.image.BufferedImage; + +@RestController +@RequestMapping("/barcodes") +public class BarcodesController { + + //Barbecue library + + @GetMapping(value = "/barbecue/upca/{barcode}", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barbecueUPCABarcode(@PathVariable("barcode") String barcode) throws Exception { + return okResponse(BarbecueBarcodeGenerator.generateUPCABarcodeImage(barcode)); + } + + @GetMapping(value = "/barbecue/ean13/{barcode}", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barbecueEAN13Barcode(@PathVariable("barcode") String barcode) throws Exception { + return okResponse(BarbecueBarcodeGenerator.generateEAN13BarcodeImage(barcode)); + } + + @PostMapping(value = "/barbecue/code128", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barbecueCode128Barcode(@RequestBody String barcode) throws Exception { + return okResponse(BarbecueBarcodeGenerator.generateCode128BarcodeImage(barcode)); + } + + @PostMapping(value = "/barbecue/pdf417", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barbecuePDF417Barcode(@RequestBody String barcode) throws Exception { + return okResponse(BarbecueBarcodeGenerator.generatePDF417BarcodeImage(barcode)); + } + + //Barcode4j library + + @GetMapping(value = "/barcode4j/upca/{barcode}", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barcode4jUPCABarcode(@PathVariable("barcode") String barcode) { + return okResponse(Barcode4jBarcodeGenerator.generateUPCABarcodeImage(barcode)); + } + + @GetMapping(value = "/barcode4j/ean13/{barcode}", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barcode4jEAN13Barcode(@PathVariable("barcode") String barcode) { + return okResponse(Barcode4jBarcodeGenerator.generateEAN13BarcodeImage(barcode)); + } + + @PostMapping(value = "/barcode4j/code128", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barcode4jCode128Barcode(@RequestBody String barcode) { + return okResponse(Barcode4jBarcodeGenerator.generateCode128BarcodeImage(barcode)); + } + + @PostMapping(value = "/barcode4j/pdf417", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity barcode4jPDF417Barcode(@RequestBody String barcode) { + return okResponse(Barcode4jBarcodeGenerator.generatePDF417BarcodeImage(barcode)); + } + + //Zxing library + + @GetMapping(value = "/zxing/upca/{barcode}", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity zxingUPCABarcode(@PathVariable("barcode") String barcode) throws Exception { + return okResponse(ZxingBarcodeGenerator.generateUPCABarcodeImage(barcode)); + } + + @GetMapping(value = "/zxing/ean13/{barcode}", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity zxingEAN13Barcode(@PathVariable("barcode") String barcode) throws Exception { + return okResponse(ZxingBarcodeGenerator.generateEAN13BarcodeImage(barcode)); + } + + @PostMapping(value = "/zxing/code128", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity zxingCode128Barcode(@RequestBody String barcode) throws Exception { + return okResponse(ZxingBarcodeGenerator.generateCode128BarcodeImage(barcode)); + } + + @PostMapping(value = "/zxing/pdf417", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity zxingPDF417Barcode(@RequestBody String barcode) throws Exception { + return okResponse(ZxingBarcodeGenerator.generatePDF417BarcodeImage(barcode)); + } + + @PostMapping(value = "/zxing/qrcode", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity zxingQRCode(@RequestBody String barcode) throws Exception { + return okResponse(ZxingBarcodeGenerator.generateQRCodeImage(barcode)); + } + + //QRGen + + @PostMapping(value = "/qrgen/qrcode", produces = MediaType.IMAGE_PNG_VALUE) + public ResponseEntity qrgenQRCode(@RequestBody String barcode) throws Exception { + return okResponse(QRGenBarcodeGenerator.generateQRCodeImage(barcode)); + } + + private ResponseEntity okResponse(BufferedImage image) { + return new ResponseEntity<>(image, HttpStatus.OK); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/SpringBootApp.java b/libraries-3/src/main/java/com/baeldung/barcodes/SpringBootApp.java new file mode 100644 index 0000000000..991b3b11ce --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/barcodes/SpringBootApp.java @@ -0,0 +1,23 @@ +package com.baeldung.barcodes; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.http.converter.BufferedImageHttpMessageConverter; +import org.springframework.http.converter.HttpMessageConverter; + +import java.awt.image.BufferedImage; + +@SpringBootApplication +public class SpringBootApp { + + public static void main(String[] args) { + SpringApplication.run(SpringBootApp.class, args); + } + + @Bean + public HttpMessageConverter createImageHttpMessageConverter() { + return new BufferedImageHttpMessageConverter(); + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java b/libraries-3/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java new file mode 100644 index 0000000000..353f824d98 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java @@ -0,0 +1,43 @@ +package com.baeldung.barcodes.generators; + +import net.sourceforge.barbecue.Barcode; +import net.sourceforge.barbecue.BarcodeFactory; +import net.sourceforge.barbecue.BarcodeImageHandler; + +import java.awt.*; +import java.awt.image.BufferedImage; + +public class BarbecueBarcodeGenerator { + + private static final Font BARCODE_TEXT_FONT = new Font(Font.SANS_SERIF, Font.PLAIN, 14); + + public static BufferedImage generateUPCABarcodeImage(String barcodeText) throws Exception { + Barcode barcode = BarcodeFactory.createUPCA(barcodeText); //checksum is automatically added + barcode.setFont(BARCODE_TEXT_FONT); + barcode.setResolution(400); + + return BarcodeImageHandler.getImage(barcode); + } + + public static BufferedImage generateEAN13BarcodeImage(String barcodeText) throws Exception { + Barcode barcode = BarcodeFactory.createEAN13(barcodeText); //checksum is automatically added + barcode.setFont(BARCODE_TEXT_FONT); + + return BarcodeImageHandler.getImage(barcode); + } + + public static BufferedImage generateCode128BarcodeImage(String barcodeText) throws Exception { + Barcode barcode = BarcodeFactory.createCode128(barcodeText); + barcode.setFont(BARCODE_TEXT_FONT); + + return BarcodeImageHandler.getImage(barcode); + } + + public static BufferedImage generatePDF417BarcodeImage(String barcodeText) throws Exception { + Barcode barcode = BarcodeFactory.createPDF417(barcodeText); + barcode.setFont(BARCODE_TEXT_FONT); + + return BarcodeImageHandler.getImage(barcode); + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java b/libraries-3/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java new file mode 100644 index 0000000000..a2fee044e5 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java @@ -0,0 +1,46 @@ +package com.baeldung.barcodes.generators; + +import org.krysalis.barcode4j.impl.code128.Code128Bean; +import org.krysalis.barcode4j.impl.pdf417.PDF417Bean; +import org.krysalis.barcode4j.impl.upcean.EAN13Bean; +import org.krysalis.barcode4j.impl.upcean.UPCABean; +import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider; + +import java.awt.image.BufferedImage; + +public class Barcode4jBarcodeGenerator { + + public static BufferedImage generateUPCABarcodeImage(String barcodeText) { + UPCABean barcodeGenerator = new UPCABean(); + BitmapCanvasProvider canvas = new BitmapCanvasProvider(160, BufferedImage.TYPE_BYTE_BINARY, false, 0); + + barcodeGenerator.generateBarcode(canvas, barcodeText); + return canvas.getBufferedImage(); + } + + public static BufferedImage generateEAN13BarcodeImage(String barcodeText) { + EAN13Bean barcodeGenerator = new EAN13Bean(); + BitmapCanvasProvider canvas = new BitmapCanvasProvider(160, BufferedImage.TYPE_BYTE_BINARY, false, 0); + + barcodeGenerator.generateBarcode(canvas, barcodeText); + return canvas.getBufferedImage(); + } + + public static BufferedImage generateCode128BarcodeImage(String barcodeText) { + Code128Bean barcodeGenerator = new Code128Bean(); + BitmapCanvasProvider canvas = new BitmapCanvasProvider(160, BufferedImage.TYPE_BYTE_BINARY, false, 0); + + barcodeGenerator.generateBarcode(canvas, barcodeText); + return canvas.getBufferedImage(); + } + + public static BufferedImage generatePDF417BarcodeImage(String barcodeText) { + PDF417Bean barcodeGenerator = new PDF417Bean(); + BitmapCanvasProvider canvas = new BitmapCanvasProvider(160, BufferedImage.TYPE_BYTE_BINARY, false, 0); + barcodeGenerator.setColumns(10); + + barcodeGenerator.generateBarcode(canvas, barcodeText); + return canvas.getBufferedImage(); + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java b/libraries-3/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java new file mode 100644 index 0000000000..46d17ac500 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java @@ -0,0 +1,21 @@ +package com.baeldung.barcodes.generators; + +import net.glxn.qrgen.javase.QRCode; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +public class QRGenBarcodeGenerator { + + public static BufferedImage generateQRCodeImage(String barcodeText) throws Exception { + ByteArrayOutputStream stream = QRCode + .from(barcodeText) + .withSize(250, 250) + .stream(); + ByteArrayInputStream bis = new ByteArrayInputStream(stream.toByteArray()); + + return ImageIO.read(bis); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java b/libraries-3/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java new file mode 100644 index 0000000000..e9aa2975da --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java @@ -0,0 +1,51 @@ +package com.baeldung.barcodes.generators; + +import com.google.zxing.BarcodeFormat; +import com.google.zxing.client.j2se.MatrixToImageWriter; +import com.google.zxing.common.BitMatrix; +import com.google.zxing.oned.Code128Writer; +import com.google.zxing.oned.EAN13Writer; +import com.google.zxing.oned.UPCAWriter; +import com.google.zxing.pdf417.PDF417Writer; +import com.google.zxing.qrcode.QRCodeWriter; + +import java.awt.image.BufferedImage; + +public class ZxingBarcodeGenerator { + + public static BufferedImage generateUPCABarcodeImage(String barcodeText) throws Exception { + UPCAWriter barcodeWriter = new UPCAWriter(); + BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.UPC_A, 300, 150); + + return MatrixToImageWriter.toBufferedImage(bitMatrix); + } + + public static BufferedImage generateEAN13BarcodeImage(String barcodeText) throws Exception { + EAN13Writer barcodeWriter = new EAN13Writer(); + BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.EAN_13, 300, 150); + + return MatrixToImageWriter.toBufferedImage(bitMatrix); + } + + public static BufferedImage generateCode128BarcodeImage(String barcodeText) throws Exception { + Code128Writer barcodeWriter = new Code128Writer(); + BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.CODE_128, 300, 150); + + return MatrixToImageWriter.toBufferedImage(bitMatrix); + } + + public static BufferedImage generatePDF417BarcodeImage(String barcodeText) throws Exception { + PDF417Writer barcodeWriter = new PDF417Writer(); + BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.PDF_417, 700, 700); + + return MatrixToImageWriter.toBufferedImage(bitMatrix); + } + + public static BufferedImage generateQRCodeImage(String barcodeText) throws Exception { + QRCodeWriter barcodeWriter = new QRCodeWriter(); + BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.QR_CODE, 200, 200); + + return MatrixToImageWriter.toBufferedImage(bitMatrix); + } + +} \ No newline at end of file diff --git a/libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java new file mode 100644 index 0000000000..717c63ae63 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java @@ -0,0 +1,28 @@ +package com.baeldung.cactoos; + +import java.util.Collection; +import java.util.List; + +import org.cactoos.collection.Filtered; +import org.cactoos.iterable.IterableOf; +import org.cactoos.list.ListOf; +import org.cactoos.scalar.And; +import org.cactoos.text.FormattedText; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CactoosCollectionUtils { + + final Logger LOGGER = LoggerFactory.getLogger(CactoosCollectionUtils.class); + + public void iterateCollection(List strings) throws Exception { + new And((String input) -> LOGGER.info(new FormattedText("%s\n", input).asString()), strings).value(); + } + + public Collection getFilteredList(List strings) { + Collection filteredStrings = new ListOf<>( + new Filtered<>(string -> string.length() == 5, new IterableOf<>(strings))); + return filteredStrings; + } + +} diff --git a/libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java new file mode 100644 index 0000000000..3e2903ebf4 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java @@ -0,0 +1,37 @@ +package com.baeldung.cactoos; + +import java.io.IOException; + +import org.cactoos.text.FormattedText; +import org.cactoos.text.IsBlank; +import org.cactoos.text.Lowered; +import org.cactoos.text.TextOf; +import org.cactoos.text.Upper; + +public class CactoosStringUtils { + + public String createString() throws IOException { + String testString = new TextOf("Test String").asString(); + return testString; + } + + public String createdFormattedString(String stringToFormat) throws IOException { + String formattedString = new FormattedText("Hello %s", stringToFormat).asString(); + return formattedString; + } + + public String toLowerCase(String testString) throws IOException { + String lowerCaseString = new Lowered(new TextOf(testString)).asString(); + return lowerCaseString; + } + + public String toUpperCase(String testString) throws Exception { + String upperCaseString = new Upper(new TextOf(testString)).asString(); + return upperCaseString; + } + + public boolean isBlank(String testString) throws Exception { + return new IsBlank(new TextOf(testString)) != null; + } + +} diff --git a/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java new file mode 100644 index 0000000000..c6bcbd7df7 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.cactoos; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; + +import org.junit.Test; + +public class CactoosCollectionUtilsUnitTest { + + @Test + public void whenFilteredClassIsCalledWithSpecificArgs_thenCorrespondingFilteredCollectionShouldBeReturned() throws IOException { + + CactoosCollectionUtils obj = new CactoosCollectionUtils(); + + // when + List strings = new ArrayList() { + { + add("Hello"); + add("John"); + add("Smith"); + add("Eric"); + add("Dizzy"); + } + }; + int size = obj.getFilteredList(strings).size(); + + // then + assertEquals(3, size); + + } + +} diff --git a/libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java new file mode 100644 index 0000000000..67dd6d91e4 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.cactoos; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; + +import org.junit.Test; + +public class CactoosStringUtilsUnitTest { + + @Test + public void whenFormattedTextIsPassedWithArgs_thenFormattedStringIsReturned() throws IOException { + + CactoosStringUtils obj = new CactoosStringUtils(); + + // when + String formattedString = obj.createdFormattedString("John"); + + // then + assertEquals("Hello John", formattedString); + + } + + @Test + public void whenStringIsPassesdToLoweredOrUpperClass_thenCorrespondingStringIsReturned() throws Exception { + + CactoosStringUtils obj = new CactoosStringUtils(); + + // when + String lowerCaseString = obj.toLowerCase("TeSt StrIng"); + String upperCaseString = obj.toUpperCase("TeSt StrIng"); + + // then + assertEquals("test string", lowerCaseString); + assertEquals("TEST STRING", upperCaseString); + + } + + @Test + public void whenEmptyStringIsPassesd_thenIsBlankReturnsTrue() throws Exception { + + CactoosStringUtils obj = new CactoosStringUtils(); + + // when + boolean isBlankEmptyString = obj.isBlank(""); + boolean isBlankNull = obj.isBlank(null); + + // then + assertEquals(true, isBlankEmptyString); + assertEquals(true, isBlankNull); + + } + +} diff --git a/libraries-data-db/pom.xml b/libraries-data-db/pom.xml index 682a6ed185..f028ffe8c3 100644 --- a/libraries-data-db/pom.xml +++ b/libraries-data-db/pom.xml @@ -183,7 +183,7 @@ io.ebean ebean-maven-plugin - 11.11.2 + ${ebean.plugin.version} @@ -202,6 +202,7 @@
+ 11.11.2 16.5.1 3.0.0 1.8 diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 2086ecb614..1267982c49 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -74,19 +74,19 @@ commons-cli commons-cli - 1.2 + ${commons.cli.version} provided commons-io commons-io - 2.1 + ${commons.io.version} provided commons-httpclient commons-httpclient - 3.0.1 + ${httpclient.version} provided @@ -133,7 +133,7 @@ org.apache.maven.plugins maven-assembly-plugin - 2.3 + ${assembly.plugin.version} src/main/resources/assembly/hadoop-job.xml @@ -158,6 +158,10 @@ + 2.3 + 1.2 + 2.1 + 3.0.1 1.2.2 1.0.0 2.4.0 diff --git a/libraries-http/pom.xml b/libraries-http/pom.xml index 6261456486..cbc74ce132 100644 --- a/libraries-http/pom.xml +++ b/libraries-http/pom.xml @@ -71,7 +71,7 @@ com.google.code.gson gson - 2.8.5 + ${gson.version} @@ -116,6 +116,7 @@ + 2.8.5 4.5.3 2.9.8 3.6.2 diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index c84f8dda76..3ffbb291a0 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -127,7 +127,7 @@ org.asciidoctor asciidoctor-maven-plugin - 1.5.7.1 + ${asciidoctor.version} @@ -154,7 +154,8 @@ - 1.9.9 + 1.5.7.1 + 1.9.9 1.9.0 1.9.0 1.9.27 diff --git a/libraries/pom.xml b/libraries/pom.xml index 13f91711fd..b5340d1ebb 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -523,7 +523,7 @@ org.apache.maven.plugins maven-shade-plugin - 2.2 + ${shade.plugin.version} package @@ -556,6 +556,7 @@ + 2.2 0.7.0 3.2.7 1.2 diff --git a/linux-bash/functions/src/main/bash/functions.sh b/linux-bash/functions/src/main/bash/functions.sh new file mode 100755 index 0000000000..41ff0ca434 --- /dev/null +++ b/linux-bash/functions/src/main/bash/functions.sh @@ -0,0 +1,208 @@ +#!/bin/bash + +# Subsection 2.1 +simple_function() { + for ((i=0;i<5;++i)) do + echo -n " "$i" "; + done +} + +function simple_function_no_parantheses { + for ((i=0;i<5;++i)) do + echo -n " "$i" "; + done +} + +function simple_for_loop() + for ((i=0;i<5;++i)) do + echo -n " "$i" "; + done + +function simple_comparison() + if [[ "$1" -lt 5 ]]; then + echo "$1 is smaller than 5" + else + echo "$1 is greater than 5" + fi + +# Subsection 2.2 +function simple_inputs() { + echo "This is the first argument [$1]" + echo "This is the second argument [$2]" + echo "Calling function with $# aruments" +} + +# Subsection 2.3 +global_sum=0 +function global_sum_outputs() { + global_sum=$(($1+$2)) +} + +function cs_sum_outputs() { + sum=$(($1+$2)) + echo $sum +} + +# Subsection 2.4 +function arg_ref_sum_outputs() { + declare -n sum_ref=$3 + sum_ref=$(($1+$2)) +} + +# Subsection 3.1 +variable="baeldung" +function variable_scope2() { + echo "Variable inside function variable_scope2: [$variable]" + local variable="ipsum" +} + +function variable_scope() { + local variable="lorem" + echo "Variable inside function variable_scope: [$variable]" + variable_scope2 +} + +# Subsection 3.2 +subshell_sum=0 +function simple_subshell_sum() ( + subshell_sum=$(($1+$2)) + echo "Value of sum in function with global variables: [$subshell_sum]" +) + +function simple_subshell_ref_sum() ( + declare -n sum_ref=$3 + sum_ref=$(($1+$2)) + echo "Value of sum in function with ref arguments: [$sum_ref]" +) + +# Subsection 3.3 +function redirection_in() { + while read input; + do + echo "$input" + done +} < infile + +function redirection_in_ps() { + read + while read -a input; + do + echo "User[${input[2]}]->File[${input[8]}]" + done +} < <(ls -ll /) + +function redirection_out_ps() { + declare -a output=("baeldung" "lorem" "ipsum" "caracg") + for element in "${output[@]}" + do + echo "$element" + done +} > >(grep "g") + +function redirection_out() { + declare -a output=("baeldung" "lorem" "ipsum") + for element in "${output[@]}" + do + echo "$element" + done +} > outfile + +# Subsection 3.4 +function fibonnaci_recursion() { + argument=$1 + if [[ "$argument" -eq 0 ]] || [[ "$argument" -eq 1 ]]; then + echo $argument + else + first=$(fibonnaci_recursion $(($argument-1))) + second=$(fibonnaci_recursion $(($argument-2))) + echo $(( $first + $second )) + fi +} + +# main menu entry point +echo "****Functions samples menu*****" +PS3="Your choice (1,2,3 etc.):" +options=("function_definitions" "function_input_args" "function_outputs" \ + "function_variables" "function_subshells" "function_redirections" \ + "function_recursion" "quit") +select option in "${options[@]}" +do + case $option in + "function_definitions") + echo -e "\n" + echo "**Different ways to define a function**" + echo -e "No function keyword:" + simple_function + echo -e "\nNo function parantheses:" + simple_function_no_parantheses + echo -e "\nOmitting curly braces:" + simple_for_loop + echo -e "\n" + ;; + "function_input_args") + echo -e "\n" + echo "**Passing inputs to a function**" + simple_inputs lorem ipsum + echo -e "\n" + ;; + "function_outputs") + echo -e "\n" + echo "**Getting outputs from a function**" + global_sum_outputs 1 2 + echo -e ">1+2 using global variables: [$global_sum]" + cs_sum=$(cs_sum_outputs 1 2) + echo -e ">1+2 using command substitution: [$cs_sum]" + arg_ref_sum_outputs 1 2 arg_ref_sum + echo -e ">1+2 using argument references: [$arg_ref_sum]" + echo -e "\n" + ;; + "function_variables") + echo -e "\n" + echo "**Overriding variable scopes**" + echo "Global value of variable: [$variable]" + variable_scope + echo -e "\n" + ;; + "function_subshells") + echo -e "\n" + echo "**Running function in subshell**" + echo "Global value of sum: [$subshell_sum]" + simple_subshell_sum 1 2 + echo "Value of sum after subshell function with \ +global variables: [$subshell_sum]" + subshell_sum_arg_ref=0 + simple_subshell_ref_sum 1 2 subshell_sum_arg_ref + echo "Value of sum after subshell function with \ +ref arguments: [$subshell_sum_arg_ref]" + echo -e "\n" + ;; + "function_redirections") + echo -e "\n" + echo "**Function redirections**" + echo -e ">Function input redirection from file:" + redirection_in + echo -e ">Function input redirection from command:" + redirection_in_ps + echo -e ">Function output redirection to file:" + redirection_out + cat outfile + echo -e ">Function output redirection to command:" + red_ps=$(redirection_out_ps) + echo "$red_ps" + echo -e "\n" + ;; + "function_recursion") + echo -e "\n" + echo "**Function recursion**" + fibo_res1=$(fibonnaci_recursion 7) + echo "The 7th Fibonnaci number: [$fibo_res1]" + fibo_res2=$(fibonnaci_recursion 15) + echo "The 15th Fibonnaci number: [$fibo_res2]" + echo -e "\n" + ;; + "quit") + break + ;; + *) echo "Invalid option";; + esac +done \ No newline at end of file diff --git a/linux-bash/functions/src/main/bash/infile b/linux-bash/functions/src/main/bash/infile new file mode 100644 index 0000000000..b1fa680af4 --- /dev/null +++ b/linux-bash/functions/src/main/bash/infile @@ -0,0 +1,3 @@ +Honda Insight 2010 +Honda Element 2006 +Chevrolet Avalanche 2002 diff --git a/logging-modules/flogger/pom.xml b/logging-modules/flogger/pom.xml index c27e2c8d7a..f553a4a961 100644 --- a/logging-modules/flogger/pom.xml +++ b/logging-modules/flogger/pom.xml @@ -15,26 +15,26 @@ com.google.flogger flogger - 0.4 + ${flogger.version} com.google.flogger flogger-system-backend - 0.4 + ${flogger.version} runtime com.google.flogger flogger-slf4j-backend - 0.4 + ${flogger.version} com.google.flogger flogger-log4j-backend - 0.4 + ${flogger.version} com.sun.jmx @@ -54,13 +54,18 @@ log4j log4j - 1.2.17 + ${log4j.version} log4j apache-log4j-extras - 1.2.17 + ${log4j.version} + + 0.4 + 1.2.17 + + \ No newline at end of file diff --git a/machine-learning/pom.xml b/machine-learning/pom.xml index 7bc0332012..24162b7b9c 100644 --- a/machine-learning/pom.xml +++ b/machine-learning/pom.xml @@ -19,6 +19,15 @@ 1.7 1.3.50 0.9.1 + 3.1.0 + 3.0.2 + 3.0.2 + 3.8.0 + 2.22.1 + 2.5.2 + 2.8.2 + 3.7.1 + 3.0.0 @@ -63,41 +72,41 @@ maven-clean-plugin - 3.1.0 + ${clean.plugin.version} maven-resources-plugin - 3.0.2 + ${resources.plugin.version} maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} maven-surefire-plugin - 2.22.1 + ${surefire.plugin.version} maven-jar-plugin - 3.0.2 + ${jar.plugin.version} maven-install-plugin - 2.5.2 + ${install.plugin.version} maven-deploy-plugin - 2.8.2 + ${deploy.plugin.version} maven-site-plugin - 3.7.1 + ${site.plugin.version} maven-project-info-reports-plugin - 3.0.0 + ${report.plugin.version} diff --git a/maven-all/compiler-plugin-java-9/pom.xml b/maven-all/compiler-plugin-java-9/pom.xml index 1975e1f7cd..6baadb451c 100644 --- a/maven-all/compiler-plugin-java-9/pom.xml +++ b/maven-all/compiler-plugin-java-9/pom.xml @@ -12,13 +12,19 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 9 - 9 + ${source.version} + ${target.version} + + 3.8.0 + 9 + 9 + + \ No newline at end of file diff --git a/maven-all/maven-custom-plugin/usage-example/pom.xml b/maven-all/maven-custom-plugin/usage-example/pom.xml index 542a02b3eb..bd2b16475e 100644 --- a/maven-all/maven-custom-plugin/usage-example/pom.xml +++ b/maven-all/maven-custom-plugin/usage-example/pom.xml @@ -8,16 +8,21 @@ 0.0.1-SNAPSHOT pom + + 3.9 + 4.12 + + org.apache.commons commons-lang3 - 3.9 + ${commons.lang3.version} junit junit - 4.12 + ${junit.version} test diff --git a/maven-all/maven-war-plugin/pom.xml b/maven-all/maven-war-plugin/pom.xml index 233a9f3571..915be306ca 100644 --- a/maven-all/maven-war-plugin/pom.xml +++ b/maven-all/maven-war-plugin/pom.xml @@ -14,7 +14,7 @@ maven-war-plugin - 3.1.0 + ${war.plugin.version} false @@ -26,6 +26,7 @@ false + 3.1.0 \ No newline at end of file diff --git a/maven-all/pom.xml b/maven-all/pom.xml new file mode 100644 index 0000000000..3a79a2a686 --- /dev/null +++ b/maven-all/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + maven-all + 0.0.1-SNAPSHOT + maven-all + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + maven + maven-custom-plugin/counter-maven-plugin + maven-war-plugin + profiles + versions-maven-plugin + + + diff --git a/maven-all/versions-maven-plugin/pom.xml b/maven-all/versions-maven-plugin/pom.xml index 3ce25d16f9..9793f55b28 100644 --- a/maven-all/versions-maven-plugin/pom.xml +++ b/maven-all/versions-maven-plugin/pom.xml @@ -12,19 +12,19 @@ commons-io commons-io - 2.3 + ${commons.io.version} org.apache.commons commons-collections4 - 4.0 + ${commons.collections4.version} org.apache.commons commons-lang3 - 3.0 + ${commons.lang3.version} @@ -36,7 +36,7 @@ commons-beanutils commons-beanutils - 1.9.1 + ${commons.beanutils.version} @@ -45,7 +45,7 @@ org.codehaus.mojo versions-maven-plugin - 2.7 + ${versions.plugin.version} org.apache.commons:commons-collections4 @@ -71,6 +71,11 @@ 1.15 + 2.3 + 2.7 + 1.9.1 + 3.0 + 4.0 \ No newline at end of file diff --git a/maven-archetype/src/main/resources/archetype-resources/pom.xml b/maven-archetype/src/main/resources/archetype-resources/pom.xml index a5c813652d..2a73687e2c 100644 --- a/maven-archetype/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetype/src/main/resources/archetype-resources/pom.xml @@ -14,6 +14,8 @@ ${liberty-plugin-version} 9080 9443 + 2.0 + 2.1 @@ -65,14 +67,14 @@ javax.enterprise cdi-api - 2.0 + ${cdi.api.version} provided javax.ws.rs javax.ws.rs-api - 2.1 + ${rsapi.api.version} provided diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml b/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml index 42b06bbebd..a4a6575906 100644 --- a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml @@ -12,23 +12,26 @@ com.baeldung.multimodule-maven-project multimodule-maven-project 1.0 + 1.0 + 1.0 + 1.0 com.baeldung.entitymodule entitymodule - 1.0 + ${entitymodule.version} com.baeldung.daomodule daomodule - 1.0 + ${daomodule.version} com.baeldung.userdaomodule userdaomodule - 1.0 + ${userdaomodule.version} diff --git a/maven-java-11/multimodule-maven-project/pom.xml b/maven-java-11/multimodule-maven-project/pom.xml index a79dff93d3..65f5b7a814 100644 --- a/maven-java-11/multimodule-maven-project/pom.xml +++ b/maven-java-11/multimodule-maven-project/pom.xml @@ -26,13 +26,13 @@ junit junit - 4.12 + ${junit.version} test org.assertj assertj-core - 3.12.2 + ${assertj.version} test @@ -44,10 +44,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + ${compiler.plugin.version} - 11 - 11 + ${source.version} + ${target.version} @@ -56,6 +56,11 @@ UTF-8 + 4.12 + 3.12.2 + 3.8.0 + 11 + 11 diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml index 3eb5897f8b..cfa59bdc39 100644 --- a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml @@ -14,16 +14,21 @@ 1.0 + + 1.0 + 1.0 + + com.baeldung.entitymodule entitymodule - 1.0 + ${entitymodule.version}1.0 com.baeldung.daomodule daomodule - 1.0 + ${daomodule.version} junit diff --git a/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-polyglot/maven-polyglot-json-extension/pom.xml index 0043bae151..15166046c1 100644 --- a/maven-polyglot/maven-polyglot-json-extension/pom.xml +++ b/maven-polyglot/maven-polyglot-json-extension/pom.xml @@ -34,7 +34,7 @@ org.codehaus.plexus plexus-component-metadata - 1.7.1 + ${plexus.component.version} @@ -48,6 +48,7 @@ 3.5.4 + 1.7.1 \ No newline at end of file diff --git a/maven-polyglot/pom.xml b/maven-polyglot/pom.xml new file mode 100644 index 0000000000..eb4e629a96 --- /dev/null +++ b/maven-polyglot/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + maven-polyglot + 0.0.1-SNAPSHOT + maven-polyglot + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + maven-polyglot-json-extension + + + + diff --git a/micronaut/pom.xml b/micronaut/pom.xml index 13639c11ff..2cb05cc1b9 100644 --- a/micronaut/pom.xml +++ b/micronaut/pom.xml @@ -49,7 +49,7 @@ javax.annotation javax.annotation-api - 1.3.2 + ${annotation.api.version} compile @@ -60,19 +60,19 @@ ch.qos.logback logback-classic - 1.2.3 + ${lombok.version} runtime junit junit - 4.12 + ${junit.version} test io.projectreactor reactor-core - 3.1.6.RELEASE + ${reactor.version} @@ -81,7 +81,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.1.0 + ${shade.plugin.version} package @@ -102,7 +102,7 @@ org.codehaus.mojo exec-maven-plugin - 1.6.0 + ${exec.plugin.version} java @@ -118,7 +118,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.7.0 + ${compiler.plugin.version} ${jdk.version} ${jdk.version} @@ -142,6 +142,13 @@ com.baeldung.micronaut.helloworld.server.ServerApplication 1.0.0.RC2 1.8 + 1.3.2 + 1.2.3 + 4.12 + 3.1.6.RELEASE + 3.7.0 + 1.6.0 + 3.1.0 diff --git a/micronaut/src/main/resources/application.yml b/micronaut/src/main/resources/application.yml index 4119026dd6..32daacd4aa 100644 --- a/micronaut/src/main/resources/application.yml +++ b/micronaut/src/main/resources/application.yml @@ -2,4 +2,4 @@ micronaut: application: name: hello-world-server server: - port: 9080 \ No newline at end of file + port: ${random.port} \ No newline at end of file diff --git a/netflix-modules/genie/pom.xml b/netflix-modules/genie/pom.xml index 835bbf2b50..2c7c04b26b 100644 --- a/netflix-modules/genie/pom.xml +++ b/netflix-modules/genie/pom.xml @@ -3,7 +3,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 genie - 1.0.0-SNAPSHOT Genie jar Sample project for Netflix Genie diff --git a/netflix-modules/pom.xml b/netflix-modules/pom.xml index 5a082e8f1a..9ed22498d8 100644 --- a/netflix-modules/pom.xml +++ b/netflix-modules/pom.xml @@ -3,7 +3,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 netflix-modules - 1.0.0-SNAPSHOT Netflix Modules pom Module for Netflix projects diff --git a/ninja/pom.xml b/ninja/pom.xml index 8ec2422d9f..b66225f693 100644 --- a/ninja/pom.xml +++ b/ninja/pom.xml @@ -13,6 +13,9 @@ 6.5.0 9.4.18.v20190429 + 3.3.4 + 2.1.3 + 1.4.186 @@ -156,17 +159,17 @@ org.webjars bootstrap - 3.3.4 + ${bootstrap.version} org.webjars jquery - 2.1.3 + ${jquery.version} com.h2database h2 - 1.4.186 + ${h2.version} org.ninjaframework diff --git a/osgi/pom.xml b/osgi/pom.xml index ed708e8004..afc980c8bd 100644 --- a/osgi/pom.xml +++ b/osgi/pom.xml @@ -11,7 +11,6 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - .. diff --git a/parent-java/pom.xml b/parent-java/pom.xml index 47965fc36d..e4ec2255c6 100644 --- a/parent-java/pom.xml +++ b/parent-java/pom.xml @@ -27,11 +27,22 @@ commons-io ${commons.io.version} + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + 23.0 2.6 + 1.19 diff --git a/patterns/design-patterns-architectural/pom.xml b/patterns/design-patterns-architectural/pom.xml index 81cc55aa21..d1945a1d0a 100644 --- a/patterns/design-patterns-architectural/pom.xml +++ b/patterns/design-patterns-architectural/pom.xml @@ -11,7 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. @@ -22,11 +21,6 @@ test - - javax - javaee-api - ${javaee.version} - org.hibernate hibernate-core @@ -41,11 +35,7 @@ - UTF-8 - 1.8 - 1.8 3.9.1 - 8.0 5.2.16.Final 6.0.6 diff --git a/patterns/design-patterns-behavioral-2/pom.xml b/patterns/design-patterns-behavioral-2/pom.xml index 4cbe6e32b9..3a6d21353e 100644 --- a/patterns/design-patterns-behavioral-2/pom.xml +++ b/patterns/design-patterns-behavioral-2/pom.xml @@ -11,7 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. @@ -24,9 +23,6 @@ - UTF-8 - 1.8 - 1.8 3.12.2 diff --git a/patterns/design-patterns-behavioral/pom.xml b/patterns/design-patterns-behavioral/pom.xml index c4ae00435e..aceaabf582 100644 --- a/patterns/design-patterns-behavioral/pom.xml +++ b/patterns/design-patterns-behavioral/pom.xml @@ -11,7 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. @@ -41,9 +40,6 @@ - UTF-8 - 1.8 - 1.8 16.0.2 3.9.1 diff --git a/patterns/design-patterns-cloud/pom.xml b/patterns/design-patterns-cloud/pom.xml index 51f6a42f76..34defb7eac 100644 --- a/patterns/design-patterns-cloud/pom.xml +++ b/patterns/design-patterns-cloud/pom.xml @@ -9,47 +9,4 @@ design-patterns-cloud pom - - - junit - junit - ${junit.version} - test - - - org.mockito - mockito-core - ${mockito-core.version} - test - - - io.github.resilience4j - resilience4j-retry - ${resilience4j.version} - test - - - org.slf4j - slf4j-api - ${slf4j.version} - test - - - org.slf4j - slf4j-simple - ${slf4j.version} - test - - - - - UTF-8 - 1.8 - 1.8 - 4.12 - 2.27.0 - 1.7.26 - 0.16.0 - - diff --git a/patterns/design-patterns-creational/pom.xml b/patterns/design-patterns-creational/pom.xml index aa20c1c085..7c2742ade4 100644 --- a/patterns/design-patterns-creational/pom.xml +++ b/patterns/design-patterns-creational/pom.xml @@ -11,7 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. @@ -36,10 +35,6 @@ - UTF-8 - 1.8 - 1.8 - 2.4.1 3.0.2 3.9.1 diff --git a/patterns/design-patterns-functional/pom.xml b/patterns/design-patterns-functional/pom.xml index ec37ad1e8d..e5166dc61e 100644 --- a/patterns/design-patterns-functional/pom.xml +++ b/patterns/design-patterns-functional/pom.xml @@ -11,13 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. - - UTF-8 - 1.8 - 1.8 - - diff --git a/patterns/design-patterns-structural/pom.xml b/patterns/design-patterns-structural/pom.xml index 97e0b9b38b..c37b6845be 100644 --- a/patterns/design-patterns-structural/pom.xml +++ b/patterns/design-patterns-structural/pom.xml @@ -11,7 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. @@ -22,10 +21,4 @@ - - UTF-8 - 1.8 - 1.8 - - diff --git a/patterns/dip/pom.xml b/patterns/dip/pom.xml index 37c980f2e3..7217c4fdcc 100644 --- a/patterns/dip/pom.xml +++ b/patterns/dip/pom.xml @@ -12,16 +12,9 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. - - junit - junit - ${junit.version} - test - org.assertj assertj-core @@ -31,9 +24,6 @@ - UTF-8 - 11 - 11 3.12.1 diff --git a/patterns/front-controller/pom.xml b/patterns/front-controller/pom.xml index 1de3b82fcd..dc10250946 100644 --- a/patterns/front-controller/pom.xml +++ b/patterns/front-controller/pom.xml @@ -10,7 +10,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. diff --git a/patterns/intercepting-filter/pom.xml b/patterns/intercepting-filter/pom.xml index 435c1e13cf..7f2f57b5e1 100644 --- a/patterns/intercepting-filter/pom.xml +++ b/patterns/intercepting-filter/pom.xml @@ -10,7 +10,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. @@ -27,15 +26,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - org.apache.maven.plugins maven-war-plugin diff --git a/patterns/pom.xml b/patterns/pom.xml index 8a510769a9..4c17055231 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -10,21 +10,20 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - .. - front-controller - intercepting-filter design-patterns-architectural design-patterns-behavioral design-patterns-behavioral-2 + design-patterns-cloud design-patterns-creational design-patterns-functional design-patterns-structural - solid dip - design-patterns-cloud + front-controller + intercepting-filter + solid diff --git a/patterns/solid/pom.xml b/patterns/solid/pom.xml index 1b0e35339d..ad76ea89fd 100644 --- a/patterns/solid/pom.xml +++ b/patterns/solid/pom.xml @@ -11,7 +11,6 @@ com.baeldung patterns 1.0.0-SNAPSHOT - .. diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/MappingFrameworksPerformance.java b/performance-tests/src/main/java/com/baeldung/performancetests/MappingFrameworksPerformance.java index 1c9e4c5dc4..66251eb078 100644 --- a/performance-tests/src/main/java/com/baeldung/performancetests/MappingFrameworksPerformance.java +++ b/performance-tests/src/main/java/com/baeldung/performancetests/MappingFrameworksPerformance.java @@ -1,4 +1,4 @@ -package com.baeldung.performancetests.benchmark; +package com.baeldung.performancetests; import com.baeldung.performancetests.dozer.DozerConverter; import com.baeldung.performancetests.jmapper.JMapperConverter; diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernatelogging/HibernateLoggingIntegrationTest.java b/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java similarity index 97% rename from persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernatelogging/HibernateLoggingIntegrationTest.java rename to persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java index 8ec722671d..f609c75834 100644 --- a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernatelogging/HibernateLoggingIntegrationTest.java +++ b/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.hibernatelogging; +package com.baeldung.hibernate.logging; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; diff --git a/persistence-modules/redis/pom.xml b/persistence-modules/redis/pom.xml index c4a928bb4a..98b8ef30f3 100644 --- a/persistence-modules/redis/pom.xml +++ b/persistence-modules/redis/pom.xml @@ -38,7 +38,7 @@ - 2.9.0 + 3.2.0 0.6 3.3.0 5.0.1.RELEASE diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/client/RedisClient.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/client/RedisClient.java new file mode 100644 index 0000000000..2fe7a787e0 --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/client/RedisClient.java @@ -0,0 +1,149 @@ +package com.baeldung.redis_scan.client; + +import com.baeldung.redis_scan.iterator.RedisIterator; +import com.baeldung.redis_scan.strategy.ScanStrategy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; + +public class RedisClient { + private static Logger log = LoggerFactory.getLogger(RedisClient.class); + + private static volatile RedisClient instance = null; + + private static JedisPool jedisPool; + + public static RedisClient getInstance(String ip, final int port) { + if (instance == null) { + synchronized (RedisClient.class) { + if (instance == null) { + instance = new RedisClient(ip, port); + } + } + } + return instance; + } + + private RedisClient(String ip, int port) { + try { + if (jedisPool == null) { + jedisPool = new JedisPool(new URI("http://" + ip + ":" + port)); + } + } catch (URISyntaxException e) { + log.error("Malformed server address", e); + } + } + + public Long lpush(final String key, final String[] strings) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.lpush(key, strings); + } catch (Exception ex) { + log.error("Exception caught in lpush", ex); + } + return null; + } + + public List lrange(final String key, final long start, final long stop) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.lrange(key, start, stop); + } catch (Exception ex) { + log.error("Exception caught in lrange", ex); + } + return new LinkedList(); + } + + public String hmset(final String key, final Map hash) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.hmset(key, hash); + } catch (Exception ex) { + log.error("Exception caught in hmset", ex); + } + return null; + } + + public Map hgetAll(final String key) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.hgetAll(key); + } catch (Exception ex) { + log.error("Exception caught in hgetAll", ex); + } + return new HashMap(); + } + + public Long sadd(final String key, final String... members) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.sadd(key, members); + } catch (Exception ex) { + log.error("Exception caught in sadd", ex); + } + return null; + } + + public Set smembers(final String key) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.smembers(key); + } catch (Exception ex) { + log.error("Exception caught in smembers", ex); + } + return new HashSet(); + } + + public Long zadd(final String key, final Map scoreMembers) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.zadd(key, scoreMembers); + } catch (Exception ex) { + log.error("Exception caught in zadd", ex); + } + return 0L; + } + + public Set zrange(final String key, final long start, final long stop) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.zrange(key, start, stop); + } catch (Exception ex) { + log.error("Exception caught in zrange", ex); + } + return new HashSet(); + } + + public String mset(final HashMap keysValues) { + try (Jedis jedis = jedisPool.getResource()) { + ArrayList keysValuesArrayList = new ArrayList(); + keysValues.forEach((key, value) -> { + keysValuesArrayList.add(key); + keysValuesArrayList.add(value); + }); + return jedis.mset((keysValuesArrayList.toArray(new String[keysValues.size()]))); + } catch (Exception ex) { + log.error("Exception caught in mset", ex); + } + return null; + } + + public Set keys(final String pattern) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.keys(pattern); + } catch (Exception ex) { + log.error("Exception caught in keys", ex); + } + return new HashSet(); + } + + public RedisIterator iterator(int initialScanCount, String pattern, ScanStrategy strategy) { + return new RedisIterator(jedisPool, initialScanCount, pattern, strategy); + } + + public void flushAll() { + try (Jedis jedis = jedisPool.getResource()) { + jedis.flushAll(); + } catch (Exception ex) { + log.error("Exception caught in flushAll", ex); + } + } + +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/iterator/RedisIterator.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/iterator/RedisIterator.java new file mode 100644 index 0000000000..5fbd798ac2 --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/iterator/RedisIterator.java @@ -0,0 +1,60 @@ +package com.baeldung.redis_scan.iterator; + +import com.baeldung.redis_scan.strategy.ScanStrategy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +public class RedisIterator implements Iterator> { + + private static Logger log = LoggerFactory.getLogger(RedisIterator.class); + private static final int DEFAULT_SCAN_COUNT = 10; + + private final JedisPool jedisPool; + private ScanParams scanParams; + private String cursor; + private ScanStrategy strategy; + + public RedisIterator(JedisPool jedisPool, int initialScanCount, String pattern, ScanStrategy strategy) { + super(); + this.jedisPool = jedisPool; + this.scanParams = new ScanParams().match(pattern).count(initialScanCount); + this.strategy = strategy; + } + + public RedisIterator(JedisPool jedisPool, String pattern, ScanStrategy strategy) { + super(); + this.jedisPool = jedisPool; + this.scanParams = new ScanParams().match(pattern).count(DEFAULT_SCAN_COUNT); + this.strategy = strategy; + } + + @Override + public boolean hasNext() { + return !"0".equals(cursor); + } + + @Override + public List next() { + if (cursor == null) { + cursor = "0"; + } + try (Jedis jedis = jedisPool.getResource()) { + ScanResult scanResult = strategy.scan(jedis, cursor, scanParams); + cursor = scanResult.getCursor(); + return scanResult.getResult(); + + } catch (Exception ex) { + log.error("Exception caught in next()", ex); + } + return new LinkedList(); + } + +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/ScanStrategy.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/ScanStrategy.java new file mode 100644 index 0000000000..39d9e44a63 --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/ScanStrategy.java @@ -0,0 +1,9 @@ +package com.baeldung.redis_scan.strategy; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; + +public interface ScanStrategy { + ScanResult scan(Jedis jedis, String cursor, ScanParams scanParams); +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Hscan.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Hscan.java new file mode 100644 index 0000000000..fd5ecd14ec --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Hscan.java @@ -0,0 +1,25 @@ +package com.baeldung.redis_scan.strategy.impl; + +import com.baeldung.redis_scan.strategy.ScanStrategy; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; + +import java.util.Map; +import java.util.Map.Entry; + +public class Hscan implements ScanStrategy> { + + private String key; + + public Hscan(String key) { + super(); + this.key = key; + } + + @Override + public ScanResult> scan(Jedis jedis, String cursor, ScanParams scanParams) { + return jedis.hscan(key, cursor, scanParams); + } + +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Scan.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Scan.java new file mode 100644 index 0000000000..f28b56e34c --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Scan.java @@ -0,0 +1,14 @@ +package com.baeldung.redis_scan.strategy.impl; + +import com.baeldung.redis_scan.strategy.ScanStrategy; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; + +public class Scan implements ScanStrategy { + + + public ScanResult scan(Jedis jedis, String cursor, ScanParams scanParams) { + return jedis.scan(cursor, scanParams); + } +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Sscan.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Sscan.java new file mode 100644 index 0000000000..ed47f7087e --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Sscan.java @@ -0,0 +1,29 @@ +package com.baeldung.redis_scan.strategy.impl; + +import com.baeldung.redis_scan.strategy.ScanStrategy; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; + +public class Sscan implements ScanStrategy { + + private String key; + + + public Sscan(String key) { + super(); + this.key = key; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public ScanResult scan(Jedis jedis, String cursor, ScanParams scanParams) { + return jedis.sscan(key, cursor, scanParams); + } +} diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Zscan.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Zscan.java new file mode 100644 index 0000000000..bdffc15883 --- /dev/null +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Zscan.java @@ -0,0 +1,25 @@ +package com.baeldung.redis_scan.strategy.impl; + +import com.baeldung.redis_scan.strategy.ScanStrategy; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; +import redis.clients.jedis.Tuple; + +public class Zscan implements ScanStrategy { + + private String key; + + + public Zscan(String key) { + super(); + this.key = key; + } + + + @Override + public ScanResult scan(Jedis jedis, String cursor, ScanParams scanParams) { + return jedis.zscan(key, cursor, scanParams); + } + +} diff --git a/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java new file mode 100644 index 0000000000..c24b88e20c --- /dev/null +++ b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java @@ -0,0 +1,96 @@ +package com.baeldung.redis_scan; + +import com.baeldung.redis_scan.client.RedisClient; +import org.junit.*; +import redis.embedded.RedisServer; + +import java.io.IOException; +import java.net.ServerSocket; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class NaiveApproachIntegrationTest { + private static RedisServer redisServer; + private static int port; + private static RedisClient redisClient; + + @BeforeClass + public static void setUp() throws IOException { + + // Take an available port + ServerSocket s = new ServerSocket(0); + port = s.getLocalPort(); + s.close(); + + redisServer = new RedisServer(port); + redisServer.start(); + } + + @AfterClass + public static void destroy() { + if (redisServer.isActive()) + redisServer.stop(); + } + + @Before + public void init() { + if (!redisServer.isActive()) { + redisServer.start(); + } + redisClient = RedisClient.getInstance("127.0.0.1", port); + } + + @After + public void flushAll() { + redisClient.flushAll(); + } + + @Test + public void testKeys() { + HashMap keyValues = new HashMap(); + keyValues.put("balls:cricket", "160"); + keyValues.put("balls:football", "450"); + keyValues.put("balls:volleyball", "270"); + redisClient.mset(keyValues); + Set readKeys = redisClient.keys("ball*"); + Assert.assertEquals(keyValues.size(), readKeys.size()); + + } + + @Test + public void testSmembers() { + HashSet setMembers = new HashSet(); + setMembers.add("cricket_160"); + setMembers.add("football_450"); + setMembers.add("volleyball_270"); + redisClient.sadd("balls", setMembers.toArray(new String[setMembers.size()])); + Set readSetMembers = redisClient.smembers("balls"); + Assert.assertEquals(setMembers.size(), readSetMembers.size()); + } + + @Test + public void testHgetAll() { + HashMap keyValues = new HashMap(); + keyValues.put("balls:cricket", "160"); + keyValues.put("balls:football", "450"); + keyValues.put("balls:volleyball", "270"); + redisClient.hmset("balls", keyValues); + Map readHash = redisClient.hgetAll("balls"); + Assert.assertEquals(keyValues.size(), readHash.size()); + } + + @Test + public void testZRange() { + HashMap scoreMembers = new HashMap(); + scoreMembers.put("cricket", (double) 160); + scoreMembers.put("football", (double) 450); + scoreMembers.put("volleyball", (double) 270); + redisClient.zadd("balls", scoreMembers); + Set readSetMembers = redisClient.zrange("balls", 0, -1); + + Assert.assertEquals(readSetMembers.size(), scoreMembers.size()); + } + +} diff --git a/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java new file mode 100644 index 0000000000..828b7a3183 --- /dev/null +++ b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java @@ -0,0 +1,129 @@ +package com.baeldung.redis_scan; + +import com.baeldung.redis_scan.client.RedisClient; +import com.baeldung.redis_scan.iterator.RedisIterator; +import com.baeldung.redis_scan.strategy.ScanStrategy; +import com.baeldung.redis_scan.strategy.impl.Hscan; +import com.baeldung.redis_scan.strategy.impl.Scan; +import com.baeldung.redis_scan.strategy.impl.Sscan; +import com.baeldung.redis_scan.strategy.impl.Zscan; +import org.junit.*; +import redis.clients.jedis.Tuple; +import redis.embedded.RedisServer; + +import java.io.IOException; +import java.net.ServerSocket; +import java.util.*; + + +public class ScanStrategyIntegrationTest { + + private static RedisServer redisServer; + private static int port; + private static RedisClient redisClient; + + @BeforeClass + public static void setUp() throws IOException { + + // Take an available port + ServerSocket s = new ServerSocket(0); + String ip = "127.0.0.1"; + port = s.getLocalPort(); + s.close(); + + redisServer = new RedisServer(port); + redisServer.start(); + } + + @AfterClass + public static void destroy() { + if (redisServer.isActive()) + redisServer.stop(); + } + + @Before + public void init() { + if (!redisServer.isActive()) { + redisServer.start(); + } + redisClient = RedisClient.getInstance("127.0.0.1", port); + } + + @After + public void flushAll() { + redisClient.flushAll(); + } + + @Test + public void testScanStrategy() { + HashMap keyValues = new HashMap(); + keyValues.put("balls:cricket", "160"); + keyValues.put("balls:football", "450"); + keyValues.put("balls:volleyball", "270"); + redisClient.mset(keyValues); + + ScanStrategy scanStrategy = new Scan(); + int iterationCount = 2; + RedisIterator iterator = redisClient.iterator(iterationCount, "ball*", scanStrategy); + List results = new LinkedList(); + while (iterator.hasNext()) { + results.addAll(iterator.next()); + } + Assert.assertEquals(keyValues.size(), results.size()); + } + + @Test + public void testSscanStrategy() { + HashSet setMembers = new HashSet(); + setMembers.add("cricket_160"); + setMembers.add("football_450"); + setMembers.add("volleyball_270"); + redisClient.sadd("balls", setMembers.toArray(new String[setMembers.size()])); + + Sscan scanStrategy = new Sscan("balls"); + int iterationCount = 2; + RedisIterator iterator = redisClient.iterator(iterationCount, "*", scanStrategy); + List results = new LinkedList(); + while (iterator.hasNext()) { + results.addAll(iterator.next()); + } + Assert.assertEquals(setMembers.size(), results.size()); + } + + @Test + public void testHscanStrategy() { + HashMap hash = new HashMap(); + hash.put("cricket", "160"); + hash.put("football", "450"); + hash.put("volleyball", "270"); + redisClient.hmset("balls", hash); + + Hscan scanStrategy = new Hscan("balls"); + int iterationCount = 2; + RedisIterator iterator = redisClient.iterator(iterationCount, "*", scanStrategy); + List> results = new LinkedList>(); + while (iterator.hasNext()) { + results.addAll(iterator.next()); + } + Assert.assertEquals(hash.size(), results.size()); + } + + @Test + public void testZscanStrategy() { + HashMap memberScores = new HashMap(); + memberScores.put("cricket", (double) 160); + memberScores.put("football", (double) 450); + memberScores.put("volleyball", (double) 270); + redisClient.zadd("balls", memberScores); + + Zscan scanStrategy = new Zscan("balls"); + int iterationCount = 2; + RedisIterator iterator = redisClient.iterator(iterationCount, "*", scanStrategy); + List results = new LinkedList(); + while (iterator.hasNext()) { + results.addAll(iterator.next()); + } + Assert.assertEquals(memberScores.size(), results.size()); + } + +} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java index 022099eed0..6ce9bcad45 100644 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java @@ -5,9 +5,9 @@ import java.util.List; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.PagingAndSortingRepository; -import com.baeldung.multipledb.model.product.ProductMultipleDB; +import com.baeldung.multipledb.model.product.Product; -public interface ProductRepository extends PagingAndSortingRepository { +public interface ProductRepository extends PagingAndSortingRepository { - List findAllByPrice(double price, Pageable pageable); + List findAllByPrice(double price, Pageable pageable); } diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/ProductMultipleDB.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java similarity index 80% rename from persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/ProductMultipleDB.java rename to persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java index 8bdff340ac..eaf471043c 100644 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/ProductMultipleDB.java +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java @@ -6,7 +6,7 @@ import javax.persistence.Table; @Entity @Table(schema = "products") -public class ProductMultipleDB { +public class Product { @Id private int id; @@ -15,19 +15,19 @@ public class ProductMultipleDB { private double price; - public ProductMultipleDB() { + public Product() { super(); } - private ProductMultipleDB(int id, String name, double price) { + private Product(int id, String name, double price) { super(); this.id = id; this.name = name; this.price = price; } - public static ProductMultipleDB from(int id, String name, double price) { - return new ProductMultipleDB(id, name, price); + public static Product from(int id, String name, double price) { + return new Product(id, name, price); } public int getId() { diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java index cdbb307d7f..831790af95 100644 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java @@ -23,7 +23,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; import com.baeldung.multipledb.dao.product.ProductRepository; -import com.baeldung.multipledb.model.product.ProductMultipleDB; +import com.baeldung.multipledb.model.product.Product; @RunWith(SpringRunner.class) @SpringBootTest(classes=MultipleDbApplication.class) @@ -36,22 +36,22 @@ public class ProductRepositoryIntegrationTest { @Before @Transactional("productTransactionManager") public void setUp() { - productRepository.save(ProductMultipleDB.from(1001, "Book", 21)); - productRepository.save(ProductMultipleDB.from(1002, "Coffee", 10)); - productRepository.save(ProductMultipleDB.from(1003, "Jeans", 30)); - productRepository.save(ProductMultipleDB.from(1004, "Shirt", 32)); - productRepository.save(ProductMultipleDB.from(1005, "Bacon", 10)); + productRepository.save(Product.from(1001, "Book", 21)); + productRepository.save(Product.from(1002, "Coffee", 10)); + productRepository.save(Product.from(1003, "Jeans", 30)); + productRepository.save(Product.from(1004, "Shirt", 32)); + productRepository.save(Product.from(1005, "Bacon", 10)); } @Test public void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() { Pageable pageRequest = PageRequest.of(0, 2); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(2)); assertTrue(result.stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .allMatch(id -> Arrays.asList(1001, 1002) .contains(id))); } @@ -60,11 +60,11 @@ public class ProductRepositoryIntegrationTest { public void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() { Pageable pageRequest = PageRequest.of(1, 2); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(2)); assertTrue(result.stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .allMatch(id -> Arrays.asList(1003, 1004) .contains(id))); } @@ -73,11 +73,11 @@ public class ProductRepositoryIntegrationTest { public void whenRequestingLastPage_ThenReturnLastPageWithRemData() { Pageable pageRequest = PageRequest.of(2, 2); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(1)); assertTrue(result.stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .allMatch(id -> Arrays.asList(1005) .contains(id))); } @@ -86,12 +86,12 @@ public class ProductRepositoryIntegrationTest { public void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() { Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name")); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(3)); assertThat(result.getContent() .stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .collect(Collectors.toList()), equalTo(Arrays.asList(1005, 1001, 1002))); } @@ -101,12 +101,12 @@ public class ProductRepositoryIntegrationTest { Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price") .descending()); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(3)); assertThat(result.getContent() .stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001))); } @@ -117,12 +117,12 @@ public class ProductRepositoryIntegrationTest { .descending() .and(Sort.by("name"))); - Page result = productRepository.findAll(pageRequest); + Page result = productRepository.findAll(pageRequest); assertThat(result.getContent(), hasSize(5)); assertThat(result.getContent() .stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001, 1005, 1002))); } @@ -131,11 +131,11 @@ public class ProductRepositoryIntegrationTest { public void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() { Pageable pageRequest = PageRequest.of(0, 2); - List result = productRepository.findAllByPrice(10, pageRequest); + List result = productRepository.findAllByPrice(10, pageRequest); assertThat(result, hasSize(2)); assertTrue(result.stream() - .map(ProductMultipleDB::getId) + .map(Product::getId) .allMatch(id -> Arrays.asList(1002, 1005) .contains(id))); } diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java new file mode 100644 index 0000000000..3f152a6ffc --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.elementcollection; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ElementCollectionApplication { + public static void main(String[] args) { + SpringApplication.run(ElementCollectionApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java new file mode 100644 index 0000000000..8b98164d63 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java @@ -0,0 +1,68 @@ +package com.baeldung.elementcollection.model; + +import javax.persistence.*; +import java.util.List; +import java.util.Objects; + +@Entity +public class Employee { + @Id + private int id; + private String name; + @ElementCollection + @CollectionTable(name = "employee_phone", joinColumns = @JoinColumn(name = "employee_id")) + private List phones; + + public Employee() { + } + + public Employee(int id) { + this.id = id; + } + + public Employee(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getPhones() { + return phones; + } + + public void setPhones(List phones) { + this.phones = phones; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Employee)) { + return false; + } + Employee user = (Employee) o; + return getId() == user.getId(); + } + + @Override + public int hashCode() { + return Objects.hash(getId()); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java new file mode 100644 index 0000000000..d73d30c47a --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java @@ -0,0 +1,62 @@ +package com.baeldung.elementcollection.model; + +import javax.persistence.Embeddable; +import java.util.Objects; + +@Embeddable +public class Phone { + private String type; + private String areaCode; + private String number; + + public Phone() { + } + + public Phone(String type, String areaCode, String number) { + this.type = type; + this.areaCode = areaCode; + this.number = number; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getAreaCode() { + return areaCode; + } + + public void setAreaCode(String areaCode) { + this.areaCode = areaCode; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Phone)) { + return false; + } + Phone phone = (Phone) o; + return getType().equals(phone.getType()) && getAreaCode().equals(phone.getAreaCode()) + && getNumber().equals(phone.getNumber()); + } + + @Override + public int hashCode() { + return Objects.hash(getType(), getAreaCode(), getNumber()); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java new file mode 100644 index 0000000000..49180c35eb --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java @@ -0,0 +1,46 @@ +package com.baeldung.elementcollection.repository; + +import com.baeldung.elementcollection.model.Employee; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityGraph; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import java.util.HashMap; +import java.util.Map; + +@Repository +public class EmployeeRepository { + + @PersistenceContext + private EntityManager em; + + @Transactional + public void save(Employee employee) { + em.persist(employee); + } + + @Transactional + public void remove(int id) { + Employee employee = findById(id); + em.remove(employee); + } + + public Employee findById(int id) { + return em.find(Employee.class, id); + } + + public Employee findByJPQL(int id) { + return em.createQuery("SELECT u FROM Employee AS u JOIN FETCH u.phones WHERE u.id=:id", Employee.class) + .setParameter("id", id).getSingleResult(); + } + + public Employee findByEntityGraph(int id) { + EntityGraph entityGraph = em.createEntityGraph(Employee.class); + entityGraph.addAttributeNodes("name", "phones"); + Map properties = new HashMap<>(); + properties.put("javax.persistence.fetchgraph", entityGraph); + return em.find(Employee.class, id, properties); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java new file mode 100644 index 0000000000..306798aa68 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java @@ -0,0 +1,64 @@ +package com.baeldung.elementcollection; + +import com.baeldung.elementcollection.model.Employee; +import com.baeldung.elementcollection.model.Phone; +import com.baeldung.elementcollection.repository.EmployeeRepository; +import org.junit.After; +import org.junit.Before; +import org.junit.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; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ElementCollectionApplication.class) +public class ElementCollectionIntegrationTest { + + @Autowired + private EmployeeRepository employeeRepository; + + @Before + public void init() { + Employee employee = new Employee(1, "Fred"); + employee.setPhones( + Arrays.asList(new Phone("work", "+55", "99999-9999"), new Phone("home", "+55", "98888-8888"))); + employeeRepository.save(employee); + } + + @After + public void clean() { + employeeRepository.remove(1); + } + + @Test(expected = org.hibernate.LazyInitializationException.class) + public void whenAccessLazyCollection_thenThrowLazyInitializationException() { + Employee employee = employeeRepository.findById(1); + assertThat(employee.getPhones().size(), is(2)); + } + + @Test + public void whenUseJPAQL_thenFetchResult() { + Employee employee = employeeRepository.findByJPQL(1); + assertThat(employee.getPhones().size(), is(2)); + } + + @Test + public void whenUseEntityGraph_thenFetchResult() { + Employee employee = employeeRepository.findByEntityGraph(1); + assertThat(employee.getPhones().size(), is(2)); + } + + @Test + @Transactional + public void whenUseTransaction_thenFetchResult() { + Employee employee = employeeRepository.findById(1); + assertThat(employee.getPhones().size(), is(2)); + } +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java index e202e45b32..7d3a881827 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java @@ -15,6 +15,7 @@ import org.springframework.dao.annotation.PersistenceExceptionTranslationPostPro import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; @@ -39,12 +40,12 @@ public class PersistenceJPAConfig { // beans @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java index fde1857ca2..72031a2232 100644 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java @@ -14,6 +14,7 @@ import org.springframework.dao.annotation.PersistenceExceptionTranslationPostPro import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; @@ -91,12 +92,12 @@ public class PersistenceTransactionalTestConfig { // beans @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); diff --git a/pom.xml b/pom.xml index c28fcdb273..4d04617dcc 100644 --- a/pom.xml +++ b/pom.xml @@ -332,19 +332,23 @@ parent-spring-5 parent-java parent-kotlin - + + akka-http akka-streams + algorithms-genetic algorithms-miscellaneous-1 algorithms-miscellaneous-2 algorithms-miscellaneous-3 algorithms-miscellaneous-4 algorithms-miscellaneous-5 - algorithms-sorting algorithms-searching + algorithms-sorting + algorithms-sorting-2 animal-sniffer-mvn-plugin annotations antlr + apache-avro apache-bval apache-curator @@ -365,12 +369,18 @@ apache-tika apache-velocity apache-zookeeper + asciidoctor asm + atomix + aws aws-lambda + aws-reactive + axon + azure bazel @@ -380,83 +390,18 @@ cas cdi checker-plugin - cloud-foundry-uaa/cf-uaa-oauth2-client - cloud-foundry-uaa/cf-uaa-oauth2-resource-server + + cloud-foundry-uaa code-generation + core-groovy core-groovy-2 core-groovy-collections - - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 - core-java-modules/core-java-annotations - core-java-modules/core-java-streams - core-java-modules/core-java-streams-2 - core-java-modules/core-java-streams-3 - - core-java-modules/core-java-function - core-java-modules/core-java-lang-math - - - core-java-modules/core-java-text - core-java-modules/core-java-lambdas - - - core-java-modules/core-java-arrays - core-java-modules/core-java-arrays-2 - core-java-modules/core-java-collections - core-java-modules/core-java-collections-2 - core-java-modules/core-java-collections-3 - core-java-modules/core-java-collections-list - core-java-modules/core-java-collections-list-2 - core-java-modules/core-java-collections-list-3 - core-java-modules/core-java-collections-array-list - core-java-modules/core-java-collections-set - core-java-modules/core-java-concurrency-basic - core-java-modules/core-java-concurrency-basic-2 - core-java-modules/core-java-concurrency-collections - core-java-modules/core-java-io - core-java-modules/core-java-io-2 - core-java-modules/core-java-io-apis - core-java-modules/core-java-io-conversions - core-java-modules/core-java-nio - core-java-modules/core-java-nio-2 - core-java-modules/core-java-security - core-java-modules/core-java-exceptions - core-java-modules/core-java-lang-syntax - core-java-modules/core-java-lang-syntax-2 - core-java-modules/core-java-lang - core-java-modules/core-java-lang-2 - core-java-modules/core-java-lang-oop - core-java-modules/core-java-lang-oop-2 - core-java-modules/core-java-lang-oop-3 - core-java-modules/core-java-lang-oop-4 + core-java-modules - core-java-modules/core-java-networking - core-java-modules/core-java-perf - core-java-modules/core-java-reflection - core-java-modules/core-java-sun - core-java-modules/core-java-string-conversions - core-java-modules/core-java-string-conversions-2 - core-java-modules/core-java-string-operations - core-java-modules/core-java-string-operations-2 - core-java-modules/core-java-string-algorithms - core-java-modules/core-java-string-algorithms-2 - core-java-modules/core-java-string-apis - core-java-modules/core-java-strings - core-java-modules/core-java - core-java-modules/core-java-jar - core-java-modules/core-java-jvm core-kotlin-modules core-scala + couchbase custom-pmd @@ -467,6 +412,7 @@ disruptor dozer drools + dropwizard dubbo ethereum @@ -478,15 +424,16 @@ google-cloud google-web-toolkit + graphql/graphql-java grpc gson guava - guava-io guava-collections guava-collections-map guava-collections-set + guava-io guava-modules guice @@ -501,12 +448,16 @@ immutables jackson-modules + java-blockchain + java-collections-conversions java-collections-conversions-2 java-collections-maps java-collections-maps-2 - java-jdi + + javafx + java-jdi java-lite java-math java-math-2 @@ -517,12 +468,10 @@ java-spi java-vavr-stream java-websocket - javafx javax-servlets javaxval jaxb - + jee-7 jee-7-security jee-kotlin jersey @@ -537,6 +486,7 @@ jooby jsf json + json-2 json-path jsoup jta @@ -544,52 +494,51 @@ kotlin-libraries kotlin-libraries-2 + kotlin-quasar - libraries libraries-2 libraries-3 + libraries-apache-commons + libraries-apache-commons-collections + libraries-apache-commons-io libraries-data libraries-data-2 libraries-data-db libraries-data-io - libraries-apache-commons - libraries-apache-commons-collections - libraries-apache-commons-io - libraries-primitive - libraries-testing - libraries-security - libraries-server libraries-http libraries-io + libraries-primitive + libraries-security + libraries-server + libraries-testing linkrest logging-modules lombok + lombok-custom lucene + machine-learning mapstruct - - maven-all/maven - maven-all/maven-custom-plugin/counter-maven-plugin - maven-all/maven-war-plugin - maven-all/profiles - maven-all/versions-maven-plugin + + maven-all maven-archetype - - maven-polyglot/maven-polyglot-json-extension - + + maven-polyglot + mesos-marathon metrics - + micronaut microprofile msf4j - + mustache mybatis - ninja netflix-modules + ninja + oauth2-framework-impl optaplanner orika osgi @@ -597,11 +546,12 @@ patterns pdf performance-tests + persistence-modules protobuffer - persistence-modules quarkus + quarkus-extension rabbitmq @@ -609,32 +559,12 @@ reactor-core resteasy restx - - rule-engines rsocket + rule-engines rxjava-core + rxjava-libraries rxjava-observables rxjava-operators - rxjava-libraries - software-security/sql-injection-samples - - tensorflow-java - spf4j - spring-boot-config-jpa-error - spring-boot-flowable - spring-boot-mvc-2 - spring-boot-performance - spring-boot-properties - spring-mvc-basics - spring-security-modules/spring-security-kerberos - oauth2-framework-impl - - spring-boot-nashorn - java-blockchain - machine-learning - webrtc - wildfly - quarkus-extension @@ -670,8 +600,6 @@ - netflix-modules - parent-boot-1 parent-boot-2 parent-spring-4 @@ -680,12 +608,14 @@ parent-kotlin saas + software-security/sql-injection-samples + spark-java + spf4j spring-4 spring-5 - spring-5-webflux spring-5-data-reactive spring-5-mvc spring-5-reactive @@ -694,55 +624,63 @@ spring-5-reactive-oauth spring-5-reactive-security spring-5-security - spring-5-security-oauth spring-5-security-cognito + spring-5-security-oauth + spring-5-webflux spring-activiti spring-akka spring-amqp spring-aop spring-apache-camel + spring-batch spring-bom spring-boot + spring-boot-modules spring-boot-admin spring-boot-angular + spring-boot-artifacts spring-boot-autoconfiguration spring-boot-bootstrap spring-boot-camel - spring-boot-config-jpa-error spring-boot-client - + spring-boot-config-jpa-error spring-boot-crud spring-boot-ctx-fluent spring-boot-custom-starter + spring-boot-data + spring-boot-deployment + spring-boot-di + spring-boot-environment + spring-boot-flowable spring-boot-jasypt spring-boot-keycloak spring-boot-kotlin + spring-boot-libraries spring-boot-logging-log4j2 - spring-boot-mvc + spring-boot-mvc-2 spring-boot-mvc-birt - spring-boot-environment - spring-boot-deployment + spring-boot-nashorn + spring-boot-parent + spring-boot-performance + spring-boot-properties + spring-boot-property-exp + + spring-boot-rest spring-boot-runtime spring-boot-runtime/disabling-console-jul spring-boot-runtime/disabling-console-log4j2 spring-boot-runtime/disabling-console-logback - spring-boot-artifacts - spring-boot-rest - spring-boot-data - spring-boot-parent - spring-boot-property-exp spring-boot-security spring-boot-springdoc spring-boot-testing spring-boot-vue - spring-caching - spring-boot-libraries + spring-caching spring-cloud spring-cloud-bus @@ -756,9 +694,9 @@ spring-data-rest spring-data-rest-querydsl + spring-di spring-dispatcher-servlet spring-drools - spring-di spring-ehcache spring-ejb @@ -783,60 +721,41 @@ spring-mobile spring-mockito - spring-websockets + + spring-mvc-basics + spring-mvc-basics-2 + spring-mvc-basics-3 spring-mvc-basics-4 + spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java spring-mvc-kotlin - spring-mvc-basics-2 - spring-mvc-basics-3 - spring-mvc-views + spring-mvc-velocity + spring-mvc-views spring-mvc-webflow spring-mvc-xml spring-protobuf - - spring-quartz spring-reactive-kotlin spring-reactor spring-remoting - spring-rest-http spring-rest-angular spring-rest-compress - spring-rest-testing spring-rest-hal-browser + spring-rest-http spring-rest-query-language spring-rest-shell spring-rest-simple spring-resttemplate + spring-rest-testing spring-roo + spring-scheduling - spring-security-modules/spring-security-acl - spring-security-modules/spring-security-angular/server - spring-security-modules/spring-security-cache-control - spring-security-modules/spring-security-core - spring-security-modules/spring-security-mvc - spring-security-modules/spring-security-mvc-boot - spring-security-modules/spring-security-mvc-custom - spring-security-modules/spring-security-mvc-digest-auth - spring-security-modules/spring-security-mvc-jsonview - spring-security-modules/spring-security-mvc-ldap - spring-security-modules/spring-security-mvc-login - spring-security-modules/spring-security-mvc-persisted-remember-me - spring-security-modules/spring-security-mvc-socket - spring-security-modules/spring-security-oidc - - spring-security-modules/spring-security-rest - spring-security-modules/spring-security-rest-basic-auth - spring-security-modules/spring-security-rest-custom - spring-security-modules/spring-security-sso - spring-security-modules/spring-security-stormpath - spring-security-modules/spring-security-thymeleaf - spring-security-modules/spring-security-x509 + spring-security-modules spring-session spring-shell spring-sleuth @@ -848,17 +767,20 @@ spring-swagger-codegen spring-thymeleaf + spring-thymeleaf-2 spring-vault spring-vertx spring-webflux-amqp + spring-websockets static-analysis stripe structurizr struts-2 + tensorflow-java testing-modules twilio @@ -871,17 +793,11 @@ video-tutorials vraptor + webrtc wicket - + wildfly xml xstream - - tensorflow-java - spring-boot-flowable - spring-security-modules/spring-security-kerberos - - spring-boot-nashorn - java-blockchain @@ -924,23 +840,11 @@ parent-java parent-kotlin - core-java-modules/core-java-concurrency-advanced - core-java-modules/core-java-concurrency-advanced-2 - core-java-modules/core-java-concurrency-advanced-3 - core-kotlin - core-kotlin-2 - jenkins/plugins jhipster jws libraries - persistence-modules/hibernate5 - persistence-modules/hibernate-mapping - persistence-modules/java-jpa - persistence-modules/java-jpa-2 - persistence-modules/java-mongodb - persistence-modules/jnosql vaadin vavr @@ -976,19 +880,23 @@ parent-spring-5 parent-java parent-kotlin - + + akka-http akka-streams + algorithms-genetic algorithms-miscellaneous-1 algorithms-miscellaneous-2 algorithms-miscellaneous-3 algorithms-miscellaneous-4 algorithms-miscellaneous-5 - algorithms-sorting algorithms-searching + algorithms-sorting + algorithms-sorting-2 animal-sniffer-mvn-plugin annotations antlr + apache-avro apache-bval apache-curator @@ -1009,90 +917,39 @@ apache-tika apache-velocity apache-zookeeper + asciidoctor asm + atomix + aws aws-lambda + aws-reactive + axon + azure + bazel + blade bootique cas cdi checker-plugin - cloud-foundry-uaa/cf-uaa-oauth2-client - cloud-foundry-uaa/cf-uaa-oauth2-resource-server + + cloud-foundry-uaa code-generation + core-groovy core-groovy-2 core-groovy-collections - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 - core-java-modules/core-java-annotations - core-java-modules/core-java-streams - core-java-modules/core-java-streams-2 - core-java-modules/core-java-streams-3 - - core-java-modules/core-java-function - core-java-modules/core-java-lang-math - - - core-java-modules/core-java-text - - - core-java-modules/core-java-arrays - core-java-modules/core-java-arrays-2 - core-java-modules/core-java-collections - core-java-modules/core-java-collections-2 - core-java-modules/core-java-collections-3 - core-java-modules/core-java-collections-list - core-java-modules/core-java-collections-list-2 - core-java-modules/core-java-collections-list-3 - core-java-modules/core-java-collections-array-list - core-java-modules/core-java-collections-set - core-java-modules/core-java-concurrency-basic - core-java-modules/core-java-concurrency-basic-2 - core-java-modules/core-java-concurrency-collections - core-java-modules/core-java-io - core-java-modules/core-java-io-2 - core-java-modules/core-java-io-apis - core-java-modules/core-java-io-conversions - core-java-modules/core-java-nio - core-java-modules/core-java-nio-2 - core-java-modules/core-java-security - core-java-modules/core-java-exceptions - core-java-modules/core-java-lang-syntax - core-java-modules/core-java-lang-syntax-2 - core-java-modules/core-java-lang - core-java-modules/core-java-lang-2 - core-java-modules/core-java-lang-oop - core-java-modules/core-java-lang-oop-2 - core-java-modules/core-java-lang-oop-3 - core-java-modules/core-java-lang-oop-4 + core-java-modules - core-java-modules/core-java-networking - core-java-modules/core-java-perf - core-java-modules/core-java-sun - core-java-modules/core-java-string-conversions - core-java-modules/core-java-string-conversions-2 - core-java-modules/core-java-string-operations - core-java-modules/core-java-string-operations-2 - core-java-modules/core-java-string-algorithms - core-java-modules/core-java-string-algorithms-2 - core-java-modules/core-java-string-apis - core-java-modules/core-java-strings core-kotlin-modules core-scala + couchbase custom-pmd @@ -1103,6 +960,7 @@ disruptor dozer drools + dropwizard dubbo ethereum @@ -1114,15 +972,16 @@ google-cloud google-web-toolkit + graphql/graphql-java grpc gson guava - guava-io guava-collections guava-collections-map guava-collections-set + guava-io guava-modules guice @@ -1137,15 +996,19 @@ immutables jackson-modules + java-blockchain + java-collections-conversions java-collections-conversions-2 java-collections-maps java-collections-maps-2 + + + javafx java-jdi - java-ee-8-security-api java-lite java-math - java-math-2 + java-math-2 java-numbers java-numbers-2 java-numbers-3 @@ -1153,12 +1016,10 @@ java-spi java-vavr-stream java-websocket - javafx javax-servlets javaxval jaxb - + jee-7 jee-7-security jee-kotlin jersey @@ -1179,50 +1040,52 @@ kotlin-libraries + kotlin-libraries-2 + kotlin-quasar - libraries + libraries-2 libraries-3 + libraries-apache-commons + libraries-apache-commons-collections + libraries-apache-commons-io libraries-data libraries-data-2 libraries-data-db libraries-data-io - libraries-apache-commons - libraries-apache-commons-collections - libraries-apache-commons-io - libraries-testing + libraries-http + libraries-io + libraries-primitive libraries-security libraries-server - libraries-http + libraries-testing linkrest logging-modules lombok + lombok-custom lucene + machine-learning mapstruct - - maven-all/maven - maven-all/maven-custom-plugin/counter-maven-plugin - maven-all/maven-war-plugin - maven-all/profiles - maven-all/versions-maven-plugin - + + maven-all maven-archetype - - maven-polyglot/maven-polyglot-json-extension - + + maven-polyglot + mesos-marathon metrics - + micronaut microprofile msf4j - + mustache mybatis - ninja netflix-modules + ninja + oauth2-framework-impl optaplanner orika osgi @@ -1230,10 +1093,12 @@ patterns pdf performance-tests + persistence-modules protobuffer - persistence-modules + quarkus + quarkus-extension rabbitmq @@ -1241,20 +1106,12 @@ reactor-core resteasy restx - - rule-engines rsocket + rule-engines rxjava-core + rxjava-libraries rxjava-observables rxjava-operators - rxjava-libraries - oauth2-framework-impl - spf4j - spring-boot-performance - spring-boot-properties - spring-mvc-basics - - @@ -1290,7 +1147,10 @@ parent-kotlin saas + software-security/sql-injection-samples + spark-java + spf4j spring-4 @@ -1303,48 +1163,65 @@ spring-5-reactive-oauth spring-5-reactive-security spring-5-security - spring-5-security-oauth spring-5-security-cognito + spring-5-security-oauth + spring-5-webflux + spring-activiti spring-akka spring-amqp spring-aop spring-apache-camel + spring-batch spring-bom spring-boot + spring-boot-modules spring-boot-admin spring-boot-angular + spring-boot-artifacts spring-boot-autoconfiguration spring-boot-bootstrap spring-boot-camel spring-boot-client + spring-boot-config-jpa-error spring-boot-crud spring-boot-ctx-fluent spring-boot-custom-starter + spring-boot-data + spring-boot-deployment + spring-boot-di + spring-boot-environment + spring-boot-flowable spring-boot-jasypt spring-boot-keycloak + spring-boot-kotlin + spring-boot-libraries spring-boot-logging-log4j2 spring-boot-mvc + spring-boot-mvc-2 spring-boot-mvc-birt - spring-boot-environment - spring-boot-deployment + spring-boot-nashorn + spring-boot-parent + spring-boot-performance + spring-boot-properties + spring-boot-property-exp + + spring-boot-rest spring-boot-runtime spring-boot-runtime/disabling-console-jul spring-boot-runtime/disabling-console-log4j2 spring-boot-runtime/disabling-console-logback - spring-boot-artifacts - spring-boot-rest - spring-boot-data - spring-boot-parent - spring-boot-property-exp spring-boot-security spring-boot-springdoc + spring-boot-testing spring-boot-vue + spring-caching + spring-cloud spring-cloud-bus @@ -1357,9 +1234,9 @@ spring-data-rest spring-data-rest-querydsl + spring-di spring-dispatcher-servlet spring-drools - spring-di spring-ehcache spring-ejb @@ -1384,60 +1261,41 @@ spring-mobile spring-mockito - spring-websockets + + spring-mvc-basics + spring-mvc-basics-2 + spring-mvc-basics-3 + spring-mvc-basics-4 + spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java spring-mvc-kotlin - spring-mvc-basics-2 - spring-mvc-basics-3 - spring-mvc-basics-4 - spring-mvc-views + spring-mvc-velocity + spring-mvc-views spring-mvc-webflow spring-mvc-xml spring-protobuf - - spring-quartz spring-reactive-kotlin spring-reactor spring-remoting - spring-rest-http spring-rest-angular spring-rest-compress - spring-rest-testing spring-rest-hal-browser + spring-rest-http spring-rest-query-language spring-rest-shell spring-rest-simple spring-resttemplate + spring-rest-testing spring-roo spring-scheduling - spring-security-modules/spring-security-acl - spring-security-modules/spring-security-angular/server - spring-security-modules/spring-security-cache-control - spring-security-modules/spring-security-core - spring-security-modules/spring-security-mvc - spring-security-modules/spring-security-mvc-boot - spring-security-modules/spring-security-mvc-custom - spring-security-modules/spring-security-mvc-digest-auth - spring-security-modules/spring-security-mvc-ldap - spring-security-modules/spring-security-mvc-login - spring-security-modules/spring-security-mvc-persisted-remember-me - spring-security-modules/spring-security-mvc-socket - spring-security-modules/spring-security-oidc - - spring-security-modules/spring-security-rest - spring-security-modules/spring-security-rest-basic-auth - spring-security-modules/spring-security-rest-custom - spring-security-modules/spring-security-sso - spring-security-modules/spring-security-stormpath - spring-security-modules/spring-security-thymeleaf - spring-security-modules/spring-security-x509 + spring-security-modules spring-session spring-shell spring-sleuth @@ -1449,17 +1307,20 @@ spring-swagger-codegen spring-thymeleaf + spring-thymeleaf-2 spring-vault spring-vertx spring-webflux-amqp + spring-websockets static-analysis stripe structurizr struts-2 + tensorflow-java testing-modules twilio @@ -1472,8 +1333,9 @@ video-tutorials vraptor + webrtc wicket - + wildfly xml xstream @@ -1510,27 +1372,12 @@ parent-java parent-kotlin - core-java-modules/core-java - core-java-modules/core-java-jar - core-java-modules/core-java-concurrency-advanced - core-java-modules/core-java-concurrency-advanced-2 - core-java-modules/core-java-concurrency-advanced-3 - core-kotlin - core-kotlin-2 - jenkins/plugins jhipster jws libraries - persistence-modules/hibernate5 - persistence-modules/hibernate-mapping - persistence-modules/java-jpa - persistence-modules/java-jpa-2 - persistence-modules/java-mongodb - persistence-modules/jnosql - vaadin vavr diff --git a/quarkus-extension/quarkus-app/pom.xml b/quarkus-extension/quarkus-app/pom.xml index 6e4cce3ae7..ad57228c44 100644 --- a/quarkus-extension/quarkus-app/pom.xml +++ b/quarkus-extension/quarkus-app/pom.xml @@ -22,7 +22,7 @@ com.baeldung.quarkus.liquibase - quarkus-liquibase + quarkus-liquibase-runtime 1.0-SNAPSHOT diff --git a/quarkus-extension/quarkus-liquibase/deployment/pom.xml b/quarkus-extension/quarkus-liquibase/deployment/pom.xml index f005ac4e8c..488d1e9ce5 100644 --- a/quarkus-extension/quarkus-liquibase/deployment/pom.xml +++ b/quarkus-extension/quarkus-liquibase/deployment/pom.xml @@ -30,7 +30,7 @@ com.baeldung.quarkus.liquibase - quarkus-liquibase + quarkus-liquibase-runtime ${project.version} diff --git a/quarkus-extension/quarkus-liquibase/runtime/pom.xml b/quarkus-extension/quarkus-liquibase/runtime/pom.xml index a1d705c691..e616060d03 100644 --- a/quarkus-extension/quarkus-liquibase/runtime/pom.xml +++ b/quarkus-extension/quarkus-liquibase/runtime/pom.xml @@ -42,7 +42,7 @@ extension-descriptor - ${project.groupId}:${project.artifactId}-deployment:${project.version} + ${project.groupId}:quarkus-liquibase-deployment:${project.version} diff --git a/slack/pom.xml b/slack/pom.xml new file mode 100644 index 0000000000..ebe5ce2f60 --- /dev/null +++ b/slack/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + com.baeldung.examples + slack + 1.0 + slack + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.hubspot.slack + slack-base + ${slack.version} + + + com.hubspot.slack + slack-java-client + ${slack.version} + + + + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven-jar-plugin.version} + + + + true + com.baeldung.examples.slack.MainClass + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + com.baeldung.examples.slack.MainClass + + + + + + + 1.4 + 2.4 + + + diff --git a/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java b/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java new file mode 100644 index 0000000000..7a3f5cd607 --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java @@ -0,0 +1,42 @@ +package com.baeldung.examples.slack; + +import java.io.IOException; +import java.nio.file.FileSystems; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DiskSpaceErrorChecker implements ErrorChecker { + private static final Logger LOG = LoggerFactory.getLogger(DiskSpaceErrorChecker.class); + + private final ErrorReporter errorReporter; + + private final double limit; + + public DiskSpaceErrorChecker(ErrorReporter errorReporter, double limit) { + this.errorReporter = errorReporter; + this.limit = limit; + } + + @Override + public void check() { + LOG.info("Checking disk space"); + FileSystems.getDefault().getFileStores().forEach(fileStore -> { + try { + long totalSpace = fileStore.getTotalSpace(); + long usableSpace = fileStore.getUsableSpace(); + double usablePercentage = ((double) usableSpace) / totalSpace; + LOG.debug("File store {} has {} of {} ({}) usable space", + fileStore, usableSpace, totalSpace, usablePercentage); + + if (totalSpace > 0 && usablePercentage < limit) { + String error = String.format("File store %s only has %d%% usable disk space", + fileStore.name(), (int)(usablePercentage * 100)); + errorReporter.reportProblem(error); + } + } catch (IOException e) { + LOG.error("Error getting disk space for file store {}", fileStore, e); + } + }); + } +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java b/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java new file mode 100644 index 0000000000..08db9a7817 --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.slack; + +public interface ErrorChecker { + void check(); +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java b/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java new file mode 100644 index 0000000000..ba6165af9b --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.slack; + +public interface ErrorReporter { + void reportProblem(String problem); +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/MainClass.java b/slack/src/main/java/com/baeldung/examples/slack/MainClass.java new file mode 100644 index 0000000000..ac25e97cf6 --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/MainClass.java @@ -0,0 +1,41 @@ +package com.baeldung.examples.slack; + +import java.io.IOException; +import java.util.Timer; +import java.util.TimerTask; + +import com.hubspot.slack.client.SlackClient; +import com.hubspot.slack.client.SlackClientFactory; +import com.hubspot.slack.client.SlackClientRuntimeConfig; + +public class MainClass { + public static final long MINUTES = 1000 * 60; + + public static void main(String[] args) throws IOException { + SlackClientRuntimeConfig runtimeConfig = SlackClientRuntimeConfig.builder() + .setTokenSupplier(() -> "") + .build(); + + SlackClient slackClient = SlackClientFactory.defaultFactory().build(runtimeConfig); + + ErrorReporter slackChannelErrorReporter = new SlackChannelErrorReporter(slackClient, "general"); + ErrorReporter slackUserErrorReporter = new SlackUserErrorReporter(slackClient, "testuser@baeldung.com"); + + ErrorChecker diskSpaceErrorChecker10pct = new DiskSpaceErrorChecker(slackChannelErrorReporter, 0.1); + ErrorChecker diskSpaceErrorChecker2pct = new DiskSpaceErrorChecker(slackUserErrorReporter, 0.02); + + Timer timer = new Timer(); + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + diskSpaceErrorChecker10pct.check(); + } + }, 0, 5 * MINUTES); + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + diskSpaceErrorChecker2pct.check(); + } + }, 0, 5 * MINUTES); + } +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java b/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java new file mode 100644 index 0000000000..f7abcecc2e --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java @@ -0,0 +1,30 @@ +package com.baeldung.examples.slack; + +import com.hubspot.slack.client.SlackClient; +import com.hubspot.slack.client.methods.params.chat.ChatPostMessageParams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SlackChannelErrorReporter implements ErrorReporter { + private static final Logger LOG = LoggerFactory.getLogger(SlackChannelErrorReporter.class); + + private final SlackClient slackClient; + + private final String channel; + + public SlackChannelErrorReporter(SlackClient slackClient, String channel) { + this.slackClient = slackClient; + this.channel = channel; + } + + @Override + public void reportProblem(String problem) { + LOG.debug("Sending message to channel {}: {}", channel, problem); + slackClient.postMessage( + ChatPostMessageParams.builder() + .setText(problem) + .setChannelId(channel) + .build() + ).join().unwrapOrElseThrow(); + } +} diff --git a/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java b/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java new file mode 100644 index 0000000000..8fa4f9016b --- /dev/null +++ b/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java @@ -0,0 +1,52 @@ +package com.baeldung.examples.slack; + +import java.util.List; + +import com.hubspot.slack.client.SlackClient; +import com.hubspot.slack.client.methods.params.chat.ChatPostMessageParams; +import com.hubspot.slack.client.methods.params.conversations.ConversationCreateParams; +import com.hubspot.slack.client.methods.params.im.ImOpenParams; +import com.hubspot.slack.client.methods.params.users.UserEmailParams; +import com.hubspot.slack.client.methods.params.users.UsersInfoParams; +import com.hubspot.slack.client.models.response.im.ImOpenResponse; +import com.hubspot.slack.client.models.response.users.UsersInfoResponse; +import com.hubspot.slack.client.models.users.SlackUser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SlackUserErrorReporter implements ErrorReporter { + private static final Logger LOG = LoggerFactory.getLogger(SlackUserErrorReporter.class); + + private final SlackClient slackClient; + + private final String user; + + public SlackUserErrorReporter(SlackClient slackClient, String user) { + this.slackClient = slackClient; + this.user = user; + } + + @Override + public void reportProblem(String problem) { + LOG.debug("Sending message to user {}: {}", user, problem); + UsersInfoResponse usersInfoResponse = slackClient + .lookupUserByEmail(UserEmailParams.builder() + .setEmail(user) + .build() + ).join().unwrapOrElseThrow(); + + ImOpenResponse imOpenResponse = slackClient.openIm(ImOpenParams.builder() + .setUserId(usersInfoResponse.getUser().getId()) + .build() + ).join().unwrapOrElseThrow(); + + imOpenResponse.getChannel().ifPresent(channel -> { + slackClient.postMessage( + ChatPostMessageParams.builder() + .setText(problem) + .setChannelId(channel.getId()) + .build() + ).join().unwrapOrElseThrow(); + }); + } +} diff --git a/core-kotlin-2/src/main/resources/logback.xml b/slack/src/main/resources/logback.xml similarity index 93% rename from core-kotlin-2/src/main/resources/logback.xml rename to slack/src/main/resources/logback.xml index 7d900d8ea8..c8c077ba1d 100644 --- a/core-kotlin-2/src/main/resources/logback.xml +++ b/slack/src/main/resources/logback.xml @@ -7,7 +7,7 @@ - + \ No newline at end of file diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml index bb1e656963..356272c807 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml @@ -10,7 +10,7 @@ com.baeldung parent-boot-1 0.0.1-SNAPSHOT - ../../spring-boot-custom-starter + ../../parent-boot-1 diff --git a/spring-boot-modules/README.md b/spring-boot-modules/README.md new file mode 100644 index 0000000000..cd916f48a7 --- /dev/null +++ b/spring-boot-modules/README.md @@ -0,0 +1,3 @@ +## Spring Boot Modules + +This module contains various modules of Spring Boot diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml new file mode 100644 index 0000000000..b4f8328386 --- /dev/null +++ b/spring-boot-modules/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + com.baeldung.spring-boot-modules + spring-boot-modules + spring-boot-modules + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + diff --git a/spring-boot-mvc-2/pom.xml b/spring-boot-mvc-2/pom.xml index 0f5a4bcd77..654b67d0f5 100644 --- a/spring-boot-mvc-2/pom.xml +++ b/spring-boot-mvc-2/pom.xml @@ -9,10 +9,10 @@ Module For Spring Boot MVC Web Fn - org.springframework.boot - spring-boot-starter-parent - 2.2.0.BUILD-SNAPSHOT - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -102,6 +102,7 @@ 3.0.0-SNAPSHOT com.baeldung.swagger2boot.SpringBootSwaggerApplication + 2.2.0.BUILD-SNAPSHOT \ No newline at end of file diff --git a/spring-boot-parent/spring-boot-with-custom-parent/pom.xml b/spring-boot-parent/spring-boot-with-custom-parent/pom.xml index 8a55f252d6..1eb4255c7e 100644 --- a/spring-boot-parent/spring-boot-with-custom-parent/pom.xml +++ b/spring-boot-parent/spring-boot-with-custom-parent/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT + ../../parent-boot-2 diff --git a/spring-boot-parent/spring-boot-with-starter-parent/pom.xml b/spring-boot-parent/spring-boot-with-starter-parent/pom.xml index ed2cb8646c..05c61fc4cc 100644 --- a/spring-boot-parent/spring-boot-with-starter-parent/pom.xml +++ b/spring-boot-parent/spring-boot-with-starter-parent/pom.xml @@ -9,10 +9,10 @@ spring-boot-with-starter-parent - org.springframework.boot - spring-boot-starter-parent - 2.1.5.RELEASE - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 @@ -38,7 +38,7 @@ 1.8 - 2.1.1.RELEASE + 2.1.5.RELEASE 4.11 diff --git a/spring-boot-properties/src/test/resources/configprops-test.properties b/spring-boot-properties/src/test/resources/configprops-test.properties index 5eed93a22b..3fc1195b98 100644 --- a/spring-boot-properties/src/test/resources/configprops-test.properties +++ b/spring-boot-properties/src/test/resources/configprops-test.properties @@ -24,3 +24,5 @@ item.size=21 #Additional properties additional.unit=km additional.max=100 + +key.something=val \ No newline at end of file diff --git a/spring-boot-properties/src/test/resources/foo.properties b/spring-boot-properties/src/test/resources/foo.properties index c9f0304f65..b5ae2aedd4 100644 --- a/spring-boot-properties/src/test/resources/foo.properties +++ b/spring-boot-properties/src/test/resources/foo.properties @@ -1 +1,2 @@ -foo=bar \ No newline at end of file +foo=bar +key.something=val \ No newline at end of file diff --git a/spring-boot-rest/README.md b/spring-boot-rest/README.md index 3909a99c65..f78c88d30b 100644 --- a/spring-boot-rest/README.md +++ b/spring-boot-rest/README.md @@ -10,7 +10,6 @@ This module contains articles about Spring Boot RESTful APIs. - [Testing REST with multiple MIME types](https://www.baeldung.com/testing-rest-api-with-multiple-media-types) - [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) - [Spring Boot Consuming and Producing JSON](https://www.baeldung.com/spring-boot-json) -- [Error Handling for REST with Spring](https://www.baeldung.com/exception-handling-for-rest-with-spring) ### E-book @@ -26,3 +25,6 @@ These articles are part of the Spring REST E-book: 8. [An Intro to Spring HATEOAS](https://www.baeldung.com/spring-hateoas-tutorial) 9. [REST Pagination in Spring](https://www.baeldung.com/rest-api-pagination-in-spring) 10. [Test a REST API with Java](https://www.baeldung.com/integration-testing-a-rest-api) + +NOTE: +Since this is a module tied to an e-book, it should not be moved or used to store the code for any further article. diff --git a/spring-boot-rest/src/test/java/com/baeldung/springhateoas/CustomerControllerIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/springhateoas/CustomerControllerIntegrationTest.java index b08da6d2cd..644ce5132a 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/springhateoas/CustomerControllerIntegrationTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/springhateoas/CustomerControllerIntegrationTest.java @@ -70,7 +70,7 @@ public class CustomerControllerIntegrationTest { this.mvc.perform(get("/customers/" + DEFAULT_CUSTOMER_ID + "/orders").accept(MediaTypes.HAL_JSON_VALUE)) .andExpect(status().isOk()) - .andExpect(jsonPath("$._embedded.orderList[0]._links.self.href", + .andExpect(jsonPath("$._embedded.orders[0]._links.self.href", is("http://localhost/customers/customer1/order1"))) .andExpect(jsonPath("$._links.self.href", is("http://localhost/customers/customer1/orders"))); } @@ -89,8 +89,8 @@ public class CustomerControllerIntegrationTest { this.mvc.perform(get("/customers/").accept(MediaTypes.HAL_JSON_VALUE)) .andExpect(status().isOk()) .andExpect( - jsonPath("$._embedded.customerList[0]._links.self.href", is("http://localhost/customers/customer1"))) - .andExpect(jsonPath("$._embedded.customerList[0]._links.allOrders.href", + jsonPath("$._embedded.customers[0]._links.self.href", is("http://localhost/customers/customer1"))) + .andExpect(jsonPath("$._embedded.customers[0]._links.allOrders.href", is("http://localhost/customers/customer1/orders"))) .andExpect(jsonPath("$._links.self.href", is("http://localhost/customers"))); } diff --git a/spring-boot-runtime/disabling-console-logback/pom.xml b/spring-boot-runtime/disabling-console-logback/pom.xml index 1a415328b6..c96dfb6a2f 100644 --- a/spring-boot-runtime/disabling-console-logback/pom.xml +++ b/spring-boot-runtime/disabling-console-logback/pom.xml @@ -8,9 +8,8 @@ com.baeldung - spring-boot-disable-console-logging + spring-boot-runtime 0.0.1-SNAPSHOT - ../ diff --git a/spring-boot-runtime/pom.xml b/spring-boot-runtime/pom.xml index baa7faebf8..fa03ab78d4 100644 --- a/spring-boot-runtime/pom.xml +++ b/spring-boot-runtime/pom.xml @@ -4,7 +4,7 @@ 4.0.0 spring-boot-runtime spring-boot-runtime - war + pom Demo project for Spring Boot diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java index a4a29cddf3..2ca0c74901 100644 --- a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java +++ b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java @@ -1,26 +1,32 @@ package com.baeldung.autoconfig.exclude; -import static org.junit.Assert.assertEquals; +import com.baeldung.boot.Application; import io.restassured.RestAssured; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.boot.Application; +import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) @TestPropertySource(properties = "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration") public class ExcludeAutoConfig1IntegrationTest { + /** + * Encapsulates the random port the test server is listening on. + */ + @LocalServerPort + private int port; + @Test public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { - int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); + int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); assertEquals(HttpStatus.OK.value(), statusCode); } } diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java index cdf79b159c..c0bd6570a1 100644 --- a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java +++ b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java @@ -1,26 +1,32 @@ package com.baeldung.autoconfig.exclude; -import static org.junit.Assert.assertEquals; +import com.baeldung.boot.Application; import io.restassured.RestAssured; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.boot.Application; +import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") public class ExcludeAutoConfig2IntegrationTest { + /** + * Encapsulates the random port the test server is listening on. + */ + @LocalServerPort + private int port; + @Test public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { - int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); + int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); assertEquals(HttpStatus.OK.value(), statusCode); } } diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java index 0e45d1e9e5..1642d4b932 100644 --- a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java +++ b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java @@ -1,27 +1,33 @@ package com.baeldung.autoconfig.exclude; -import static org.junit.Assert.assertEquals; +import com.baeldung.boot.Application; import io.restassured.RestAssured; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.boot.Application; +import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) @EnableAutoConfiguration(exclude=SecurityAutoConfiguration.class) public class ExcludeAutoConfig3IntegrationTest { + /** + * Encapsulates the random port the test server is listening on. + */ + @LocalServerPort + private int port; + @Test public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { - int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); + int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); assertEquals(HttpStatus.OK.value(), statusCode); } } diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java index 8429aed6cd..1aa453348b 100644 --- a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java +++ b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java @@ -1,22 +1,29 @@ package com.baeldung.autoconfig.exclude; -import static org.junit.Assert.assertEquals; import io.restassured.RestAssured; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringRunner; +import static org.junit.Assert.assertEquals; + @RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class ExcludeAutoConfig4IntegrationTest { + /** + * Encapsulates the random port the test server is listening on. + */ + @LocalServerPort + private int port; + @Test public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { - int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); + int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); assertEquals(HttpStatus.OK.value(), statusCode); } } diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java index fe71f44ddf..44a02c0c80 100644 --- a/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java +++ b/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java @@ -1,30 +1,36 @@ package com.baeldung.boot.autoconfig; -import static org.junit.Assert.assertEquals; +import com.baeldung.boot.Application; import io.restassured.RestAssured; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.boot.Application; +import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class AutoConfigIntegrationTest { + /** + * Encapsulates the random port the test server is listening on. + */ + @LocalServerPort + private int port; + @Test public void givenNoAuthentication_whenAccessHome_thenUnauthorized() { - int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); + int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); assertEquals(HttpStatus.UNAUTHORIZED.value(), statusCode); } @Test public void givenAuthentication_whenAccessHome_thenOK() { - int statusCode = RestAssured.given().auth().basic("john", "123").get("http://localhost:8080/").statusCode(); + int statusCode = RestAssured.given().auth().basic("john", "123").get("http://localhost:" + port).statusCode(); assertEquals(HttpStatus.OK.value(), statusCode); } } diff --git a/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java index 7a1eb4adbe..f8bd61e5c7 100644 --- a/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java +++ b/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java @@ -1,7 +1,5 @@ package com.baeldung.testloglevel; -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -13,9 +11,14 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.rule.OutputCapture; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS; + +@DirtiesContext(classMode = AFTER_CLASS) @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestLogLevelApplication.class) @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) diff --git a/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java index af3bafdc2e..ffe9d400ed 100644 --- a/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java +++ b/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java @@ -1,7 +1,5 @@ package com.baeldung.testloglevel; -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -13,9 +11,14 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.rule.OutputCapture; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS; + +@DirtiesContext(classMode = AFTER_CLASS) @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestLogLevelApplication.class) @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) diff --git a/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java index 5609ce6c01..6e80f50c00 100644 --- a/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java +++ b/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java @@ -11,12 +11,15 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.rule.OutputCapture; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS; @RunWith(SpringRunner.class) +@DirtiesContext(classMode = AFTER_CLASS) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestLogLevelApplication.class) @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) @ActiveProfiles("logging-test") diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml index 10cd49cc04..0f62c031cf 100644 --- a/spring-cloud/spring-cloud-gateway/pom.xml +++ b/spring-cloud/spring-cloud-gateway/pom.xml @@ -68,6 +68,10 @@ spring-boot-starter-test test + + org.springframework.boot + spring-boot-devtools + diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplication.java new file mode 100644 index 0000000000..e209b6cdf0 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.springcloudgateway.custompredicates; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; + +@SpringBootApplication +public class CustomPredicatesApplication { + + public static void main(String[] args) { + new SpringApplicationBuilder(CustomPredicatesApplication.class) + .profiles("customroutes") + .run(args); + } + +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/config/CustomPredicatesConfig.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/config/CustomPredicatesConfig.java new file mode 100644 index 0000000000..0e88b29bcf --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/config/CustomPredicatesConfig.java @@ -0,0 +1,38 @@ +package com.baeldung.springcloudgateway.custompredicates.config; + +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.springcloudgateway.custompredicates.factories.GoldenCustomerRoutePredicateFactory; +import com.baeldung.springcloudgateway.custompredicates.factories.GoldenCustomerRoutePredicateFactory.Config; +import com.baeldung.springcloudgateway.custompredicates.service.GoldenCustomerService; + +@Configuration +public class CustomPredicatesConfig { + + + @Bean + public GoldenCustomerRoutePredicateFactory goldenCustomer(GoldenCustomerService goldenCustomerService) { + return new GoldenCustomerRoutePredicateFactory(goldenCustomerService); + } + + + //@Bean + public RouteLocator routes(RouteLocatorBuilder builder, GoldenCustomerRoutePredicateFactory gf ) { + + return builder.routes() + .route("dsl_golden_route", r -> r.path("/dsl_api/**") + .filters(f -> f.stripPrefix(1)) + .uri("https://httpbin.org") + .predicate(gf.apply(new Config(true, "customerId")))) + .route("dsl_common_route", r -> r.path("/dsl_api/**") + .filters(f -> f.stripPrefix(1)) + .uri("https://httpbin.org") + .predicate(gf.apply(new Config(false, "customerId")))) + .build(); + } + +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/factories/GoldenCustomerRoutePredicateFactory.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/factories/GoldenCustomerRoutePredicateFactory.java new file mode 100644 index 0000000000..cb5c3a0b50 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/factories/GoldenCustomerRoutePredicateFactory.java @@ -0,0 +1,102 @@ +/** + * + */ +package com.baeldung.springcloudgateway.custompredicates.factories; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; + +import javax.validation.constraints.NotEmpty; + +import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory; +import org.springframework.http.HttpCookie; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.server.ServerWebExchange; + +import com.baeldung.springcloudgateway.custompredicates.service.GoldenCustomerService; + +/** + * @author Philippe + * + */ +public class GoldenCustomerRoutePredicateFactory extends AbstractRoutePredicateFactory { + + private final GoldenCustomerService goldenCustomerService; + + public GoldenCustomerRoutePredicateFactory(GoldenCustomerService goldenCustomerService ) { + super(Config.class); + this.goldenCustomerService = goldenCustomerService; + } + + + @Override + public List shortcutFieldOrder() { + return Arrays.asList("isGolden","customerIdCookie"); + } + + + @Override + public Predicate apply(Config config) { + + return (ServerWebExchange t) -> { + List cookies = t.getRequest() + .getCookies() + .get(config.getCustomerIdCookie()); + + boolean isGolden; + if ( cookies == null || cookies.isEmpty()) { + isGolden = false; + } + else { + String customerId = cookies.get(0).getValue(); + isGolden = goldenCustomerService.isGoldenCustomer(customerId); + } + + return config.isGolden()?isGolden:!isGolden; + }; + } + + + @Validated + public static class Config { + boolean isGolden = true; + + @NotEmpty + String customerIdCookie = "customerId"; + + + public Config() {} + + public Config( boolean isGolden, String customerIdCookie) { + this.isGolden = isGolden; + this.customerIdCookie = customerIdCookie; + } + + public boolean isGolden() { + return isGolden; + } + + public void setGolden(boolean value) { + this.isGolden = value; + } + + /** + * @return the customerIdCookie + */ + public String getCustomerIdCookie() { + return customerIdCookie; + } + + /** + * @param customerIdCookie the customerIdCookie to set + */ + public void setCustomerIdCookie(String customerIdCookie) { + this.customerIdCookie = customerIdCookie; + } + + + + } + +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/service/GoldenCustomerService.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/service/GoldenCustomerService.java new file mode 100644 index 0000000000..82bf2e6ae9 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/service/GoldenCustomerService.java @@ -0,0 +1,26 @@ +/** + * + */ +package com.baeldung.springcloudgateway.custompredicates.service; + +import org.springframework.stereotype.Component; + +/** + * @author Philippe + * + */ +@Component +public class GoldenCustomerService { + + public boolean isGoldenCustomer(String customerId) { + + // TODO: Add some AI logic to check is this customer deserves a "golden" status ;^) + if ( "baeldung".equalsIgnoreCase(customerId)) { + return true; + } + else { + return false; + } + } + +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application-customroutes.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application-customroutes.yml new file mode 100644 index 0000000000..859aa60bda --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application-customroutes.yml @@ -0,0 +1,26 @@ +spring: + cloud: + gateway: + routes: + - id: golden_route + uri: https://httpbin.org + predicates: + - Path=/api/** + - GoldenCustomer=true + filters: + - StripPrefix=1 + - AddRequestHeader=GoldenCustomer,true + - id: common_route + uri: https://httpbin.org + predicates: + - Path=/api/** + - name: GoldenCustomer + args: + golden: false + customerIdCookie: customerId + filters: + - StripPrefix=1 + - AddRequestHeader=GoldenCustomer,false + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/gatewayapp/CustomFiltersLiveTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/gatewayapp/CustomFiltersLiveTest.java index a4bb3f8068..f49f8c68b6 100644 --- a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/gatewayapp/CustomFiltersLiveTest.java +++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/gatewayapp/CustomFiltersLiveTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; import org.assertj.core.api.Condition; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; @@ -27,6 +28,7 @@ public class CustomFiltersLiveTest { @LocalServerPort String port; + @Autowired private WebTestClient client; @BeforeEach diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplicationLiveTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplicationLiveTest.java new file mode 100644 index 0000000000..d9988ceb5e --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/custompredicates/CustomPredicatesApplicationLiveTest.java @@ -0,0 +1,67 @@ +package com.baeldung.springcloudgateway.custompredicates; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +import java.net.URI; + +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; +import org.junit.Before; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; + +/** + * This test requires + */ +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("customroutes") +public class CustomPredicatesApplicationLiveTest { + + @LocalServerPort + String serverPort; + + @Autowired + private TestRestTemplate restTemplate; + + @Test + void givenNormalCustomer_whenCallHeadersApi_thenResponseForNormalCustomer() throws JSONException { + + String url = "http://localhost:" + serverPort + "/api/headers"; + ResponseEntity response = restTemplate.getForEntity(url, String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + JSONObject json = new JSONObject(response.getBody()); + JSONObject headers = json.getJSONObject("headers"); + assertThat(headers.getString("Goldencustomer")).isEqualTo("false"); + + } + + @Test + void givenGoldenCustomer_whenCallHeadersApi_thenResponseForGoldenCustomer() throws JSONException { + + String url = "http://localhost:" + serverPort + "/api/headers"; + RequestEntity request = RequestEntity + .get(URI.create(url)) + .header("Cookie", "customerId=baeldung") + .build(); + + ResponseEntity response = restTemplate.exchange(request, String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + JSONObject json = new JSONObject(response.getBody()); + JSONObject headers = json.getJSONObject("headers"); + assertThat(headers.getString("Goldencustomer")).isEqualTo("true"); + + } + +} diff --git a/spring-exceptions/README.md b/spring-exceptions/README.md index f8c7553f05..2136402d49 100644 --- a/spring-exceptions/README.md +++ b/spring-exceptions/README.md @@ -1,4 +1,4 @@ -## Spring `Exception`s +## Spring Exceptions This module contains articles about Spring `Exception`s diff --git a/spring-jinq/pom.xml b/spring-jinq/pom.xml index 991401c4a1..29fc3605d7 100644 --- a/spring-jinq/pom.xml +++ b/spring-jinq/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-boot-1 0.0.1-SNAPSHOT + ../parent-boot-1 diff --git a/spring-roo/pom.xml b/spring-roo/pom.xml index 456642b1f0..448574ed19 100644 --- a/spring-roo/pom.xml +++ b/spring-roo/pom.xml @@ -413,7 +413,7 @@ spring-roo-repository Spring Roo Repository - http://repo.spring.io/spring-roo + https://repo.spring.io/spring-roo diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml new file mode 100644 index 0000000000..168fab85c0 --- /dev/null +++ b/spring-security-modules/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + spring-security-modules + 0.0.1-SNAPSHOT + spring-security-modules + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + spring-security-acl + spring-security-angular/server + spring-security-cache-control + spring-security-core + spring-security-cors + spring-security-kerberos + spring-security-mvc + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth + spring-security-mvc-jsonview + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc-socket + spring-security-oidc + + + spring-security-rest + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-sso + spring-security-stormpath + spring-security-thymeleaf + spring-security-x509 + + + diff --git a/spring-security-modules/spring-security-cors/pom.xml b/spring-security-modules/spring-security-cors/pom.xml index 91e8f5adb6..2acb99368f 100644 --- a/spring-security-modules/spring-security-cors/pom.xml +++ b/spring-security-modules/spring-security-cors/pom.xml @@ -3,15 +3,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-security-cors - 0.0.1-SNAPSHOT spring-security-cors jar Spring Security CORS com.baeldung - parent-modules - 1.0.0-SNAPSHOT + spring-security-modules + 0.0.1-SNAPSHOT diff --git a/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerTest.java b/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerUnitTest.java similarity index 97% rename from spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerTest.java rename to spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerUnitTest.java index a471eb922f..7567573040 100644 --- a/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerTest.java +++ b/spring-security-modules/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerUnitTest.java @@ -18,7 +18,7 @@ import com.baeldung.springbootsecuritycors.basicauth.SpringBootSecurityApplicati @RunWith(SpringRunner.class) @SpringBootTest(classes = { SpringBootSecurityApplication.class }) -public class ResourceControllerTest { +public class ResourceControllerUnitTest { private MockMvc mockMvc; diff --git a/spring-security-sso/spring-security-sso-auth-server/README.md b/spring-security-sso/spring-security-sso-auth-server/README.md deleted file mode 100644 index 845fb50a93..0000000000 --- a/spring-security-sso/spring-security-sso-auth-server/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles - -- [Simple Single Sign-On with Spring Security OAuth2](https://www.baeldung.com/sso-spring-security-oauth2) diff --git a/spring-security-sso/spring-security-sso-ui-2/README.md b/spring-security-sso/spring-security-sso-ui-2/README.md deleted file mode 100644 index aed217bdf0..0000000000 --- a/spring-security-sso/spring-security-sso-ui-2/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Simple Single Sign-On with Spring Security OAuth2](https://www.baeldung.com/sso-spring-security-oauth2) diff --git a/spring-security-sso/spring-security-sso-ui/README.md b/spring-security-sso/spring-security-sso-ui/README.md deleted file mode 100644 index 845fb50a93..0000000000 --- a/spring-security-sso/spring-security-sso-ui/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles - -- [Simple Single Sign-On with Spring Security OAuth2](https://www.baeldung.com/sso-spring-security-oauth2) diff --git a/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationHooks.java b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationHooks.java new file mode 100644 index 0000000000..8de55e4611 --- /dev/null +++ b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationHooks.java @@ -0,0 +1,48 @@ +package com.baeldung.cucumberhooks.books; + +import io.cucumber.core.api.Scenario; +import io.cucumber.java.After; +import io.cucumber.java.AfterStep; +import io.cucumber.java.Before; +import io.cucumber.java.BeforeStep; +import io.cucumber.java8.En; + +public class BookStoreWithHooksIntegrationHooks implements En { + + public BookStoreWithHooksIntegrationHooks() { + Before(1, () -> startBrowser()); + } + + @Before(order=2, value="@Screenshots") + public void beforeScenario(Scenario scenario) { + takeScreenshot(); + } + + @After + public void afterScenario(Scenario scenario) { + takeScreenshot(); + } + + @BeforeStep + public void beforeStep(Scenario scenario) { + takeScreenshot(); + } + + @AfterStep + public void afterStep(Scenario scenario) { + takeScreenshot(); + closeBrowser(); + } + + public void takeScreenshot() { + //code to take and save screenshot + } + + public void startBrowser() { + //code to open browser + } + + public void closeBrowser() { + //code to close browser + } +} diff --git a/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationTest.java b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationTest.java index 4db8157c21..79e43bad27 100644 --- a/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationTest.java +++ b/testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberhooks/books/BookStoreWithHooksIntegrationTest.java @@ -1,11 +1,5 @@ package com.baeldung.cucumberhooks.books; -import io.cucumber.core.api.Scenario; -import io.cucumber.java.After; -import io.cucumber.java.AfterStep; -import io.cucumber.java.Before; -import io.cucumber.java.BeforeStep; -import io.cucumber.java8.En; import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; import org.junit.runner.RunWith; @@ -14,42 +8,6 @@ import org.junit.runner.RunWith; @CucumberOptions(features = "classpath:features/book-store-with-hooks.feature", glue = "com.baeldung.cucumberhooks.books" ) -public class BookStoreWithHooksIntegrationTest implements En { +public class BookStoreWithHooksIntegrationTest { - public BookStoreWithHooksIntegrationTest() { - Before(1, () -> startBrowser()); - } - - @Before(order=2, value="@Screenshots") - public void beforeScenario(Scenario scenario) { - takeScreenshot(); - } - - @After - public void afterScenario(Scenario scenario) { - takeScreenshot(); - } - - @BeforeStep - public void beforeStep(Scenario scenario) { - takeScreenshot(); - } - - @AfterStep - public void afterStep(Scenario scenario) { - takeScreenshot(); - closeBrowser(); - } - - public void takeScreenshot() { - //code to take and save screenshot - } - - public void startBrowser() { - //code to open browser - } - - public void closeBrowser() { - //code to close browser - } } diff --git a/wildfly/pom.xml b/wildfly/pom.xml index e81b609206..cdffe8b996 100644 --- a/wildfly/pom.xml +++ b/wildfly/pom.xml @@ -9,9 +9,10 @@ war - org.springframework.boot - spring-boot-starter-parent - 2.1.6.RELEASE + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2