diff --git a/algorithms-modules/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream.java b/algorithms-modules/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream.java index 9d3b699956..d3fde8a827 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream.java +++ b/algorithms-modules/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream.java @@ -29,13 +29,13 @@ public class MedianOfIntegerStream { } double getMedian() { - int median; + double median; if (minHeap.size() < maxHeap.size()) { median = maxHeap.peek(); } else if (minHeap.size() > maxHeap.size()) { median = minHeap.peek(); } else { - median = (minHeap.peek() + maxHeap.peek()) / 2; + median = (minHeap.peek() + maxHeap.peek()) / 2.0; } return median; } diff --git a/algorithms-modules/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream2.java b/algorithms-modules/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream2.java index 8aa7e6f6af..a28709c2d6 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream2.java +++ b/algorithms-modules/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStream2.java @@ -25,11 +25,11 @@ public class MedianOfIntegerStream2 { } double getMedian() { - int median; + double median; if (minHeap.size() > maxHeap.size()) { median = minHeap.peek(); } else { - median = (minHeap.peek() + maxHeap.peek()) / 2; + median = (minHeap.peek() + maxHeap.peek()) / 2.0; } return median; } diff --git a/core-java-modules/core-java-arrays-operations-basic-2/pom.xml b/core-java-modules/core-java-arrays-operations-basic-2/pom.xml index 354da6d7ff..27ebc9166b 100644 --- a/core-java-modules/core-java-arrays-operations-basic-2/pom.xml +++ b/core-java-modules/core-java-arrays-operations-basic-2/pom.xml @@ -13,4 +13,12 @@ 0.0.1-SNAPSHOT + + + org.apache.commons + commons-lang3 + 3.14.0 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-operations-basic-2/src/test/java/com/baeldung/array/flatarray/FlatArrayUnitTest.java b/core-java-modules/core-java-arrays-operations-basic-2/src/test/java/com/baeldung/array/flatarray/FlatArrayUnitTest.java new file mode 100644 index 0000000000..5d67c68a37 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-basic-2/src/test/java/com/baeldung/array/flatarray/FlatArrayUnitTest.java @@ -0,0 +1,130 @@ +package com.baeldung.array.flatarray; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class FlatArrayUnitTest { + + @ParameterizedTest + @MethodSource("arrayProvider") + void giveTwoDimensionalArray_whenFlatWithStream_thenGetCorrectResult(int[][] initialArray, + int[] expected) { + int[] actual = Arrays.stream(initialArray).flatMapToInt(Arrays::stream).toArray(); + assertThat(actual).containsExactly(expected); + } + + @ParameterizedTest + @MethodSource("arrayProvider") + void giveTwoDimensionalArray_whenFlatWithForLoopAndAdditionalList_thenGetCorrectResult(int[][] initialArray, + int[] intArray) { + List expected = Arrays.stream(intArray).boxed().collect(Collectors.toList()); + List actual = new ArrayList<>(); + for (int[] numbers : initialArray) { + for (int number : numbers) { + actual.add(number); + } + } + assertThat(actual).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("arrayProvider") + void giveTwoDimensionalArray_whenFlatWithForLoopAndLists_thenGetCorrectResult(int[][] initialArray, + int[] intArray) { + List expected = Arrays.stream(intArray).boxed().collect(Collectors.toList()); + List actual = new ArrayList<>(); + for (int[] numbers : initialArray) { + List listOfNumbers = Arrays.stream(numbers).boxed().collect(Collectors.toList()); + actual.addAll(listOfNumbers); + } + assertThat(actual).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("arrayProvider") + void giveTwoDimensionalArray_whenFlatWithArrayCopy_thenGetCorrectResult(int[][] initialArray, + int[] expected) { + int[] actual = new int[]{}; + int position = 0; + for (int[] numbers : initialArray) { + if (actual.length < position + numbers.length) { + int[] newArray = new int[actual.length + numbers.length]; + System.arraycopy(actual, 0, newArray, 0, actual.length); + actual = newArray; + } + System.arraycopy(numbers, 0, actual, position, numbers.length); + position += numbers.length; + } + assertThat(actual).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("arrayProvider") + void giveTwoDimensionalArray_whenFlatWithArrayCopyAndTotalNumberOfElements_thenGetCorrectResult(int[][] initialArray, + int[] expected) { + int totalNumberOfElements = 0; + for (int[] numbers : initialArray) { + totalNumberOfElements += numbers.length; + } + int[] actual = new int[totalNumberOfElements]; + int position = 0; + for (int[] numbers : initialArray) { + System.arraycopy(numbers, 0, actual, position, numbers.length); + position += numbers.length; + } + assertThat(actual).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("arrayProvider") + void giveTwoDimensionalArray_whenFlatWithForLoopAndTotalNumberOfElements_thenGetCorrectResult(int[][] initialArray, + int[] expected) { + int totalNumberOfElements = 0; + for (int[] numbers : initialArray) { + totalNumberOfElements += numbers.length; + } + int[] actual = new int[totalNumberOfElements]; + int position = 0; + for (int[] numbers : initialArray) { + for (int number : numbers) { + actual[position] = number; + ++position; + } + } + assertThat(actual).isEqualTo(expected); + } + + + static Stream arrayProvider() { + return Stream.of( + Arguments.of( + new int[][]{ + {805, 902, 259, 162, 775}, + {278, 216, 0, 72, 663}, + {185, 390, 537, 909, 918}, + {150, 782, 282, 482, 401}, + {244, 685, 643, 364, 307}, + {483, 939, 750, 190, 424}, + {44, 160, 290, 963, 881} + }, + new int[]{ + 805, 902, 259, 162, 775, + 278, 216, 0, 72, 663, + 185, 390, 537, 909, 918, + 150, 782, 282, 482, 401, + 244, 685, 643, 364, 307, + 483, 939, 750, 190, 424, + 44, 160, 290, 963, 881 + } + ) + ); + } +} diff --git a/core-java-modules/core-java-arrays-operations-basic-2/src/test/java/com/baeldung/array/smallestindex/SmallestElementIndexUnitTest.java b/core-java-modules/core-java-arrays-operations-basic-2/src/test/java/com/baeldung/array/smallestindex/SmallestElementIndexUnitTest.java new file mode 100644 index 0000000000..9f8299b9e5 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-basic-2/src/test/java/com/baeldung/array/smallestindex/SmallestElementIndexUnitTest.java @@ -0,0 +1,132 @@ +package com.baeldung.array.smallestindex; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import org.apache.commons.lang3.ArrayUtils; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class SmallestElementIndexUnitTest { + + @ParameterizedTest + @MethodSource("primitiveProvider") + void givenArray_whenUsingForLoop_thenGetCorrectResult(int[] array, int expectedIndex) { + int minValue = Integer.MAX_VALUE; + int minIndex = -1; + for (int i = 0; i < array.length; i++) { + if (array[i] < minValue) { + minValue = array[i]; + minIndex = i; + } + } + assertThat(minIndex).isEqualTo(expectedIndex); + } + + @ParameterizedTest + @MethodSource("primitiveProvider") + void givenArray_whenUsingForLoopAndLookForIndex_thenGetCorrectResult(int[] array, int expectedIndex) { + int minValue = Integer.MAX_VALUE; + for (int number : array) { + if (number < minValue) { + minValue = number; + } + } + int minIndex = -1; + for (int i = 0; i < array.length; i++) { + if (array[i] == minValue) { + minIndex = i; + break; + } + } + assertThat(minIndex).isEqualTo(expectedIndex); + } + + @ParameterizedTest + @MethodSource("primitiveProvider") + void givenArray_whenUsingIntStreamAndLookForIndex_thenGetCorrectResult(int[] array, int expectedIndex) { + int minValue = Arrays.stream(array).min().orElse(Integer.MAX_VALUE); + int minIndex = -1; + for (int i = 0; i < array.length; i++) { + if (array[i] == minValue) { + minIndex = i; + break; + } + } + assertThat(minIndex).isEqualTo(expectedIndex); + } + + @ParameterizedTest + @MethodSource("primitiveProvider") + void givenArray_whenUsingIntStreamAndLookForIndexWithIntStream_thenGetCorrectResult(int[] array, int expectedIndex) { + int minValue = Arrays.stream(array).min().orElse(Integer.MAX_VALUE); + int minIndex = IntStream.range(0, array.length) + .filter(index -> array[index] == minValue) + .findFirst().orElse(-1); + assertThat(minIndex).isEqualTo(expectedIndex); + } + + @ParameterizedTest + @MethodSource("primitiveProvider") + void givenArray_whenUsingIntStreamAndLookForIndexWithArrayUtils_thenGetCorrectResult(int[] array, int expectedIndex) { + int minValue = Arrays.stream(array).min().orElse(Integer.MAX_VALUE); + int minIndex = ArrayUtils.indexOf(array, minValue); + assertThat(minIndex).isEqualTo(expectedIndex); + } + + @ParameterizedTest + @MethodSource("referenceTypesProvider") + void givenArray_whenUsingReduce_thenGetCorrectResult(Integer[] array, int expectedIndex) { + int minValue = Arrays.stream(array).reduce(Integer.MAX_VALUE, Integer::min); + int minIndex = ArrayUtils.indexOf(array, minValue); + assertThat(minIndex).isEqualTo(expectedIndex); + } + + @ParameterizedTest + @MethodSource("referenceTypesProvider") + void givenArray_whenUsingReduceAndList_thenGetCorrectResult(Integer[] array, int expectedIndex) { + List list = Arrays.asList(array); + int minValue = list.stream().reduce(Integer.MAX_VALUE, Integer::min); + int index = list.indexOf(minValue); + assertThat(index).isEqualTo(expectedIndex); + } + + @ParameterizedTest + @MethodSource("primitiveProvider") + void givenArray_whenUsingReduceWithRange_thenGetCorrectResult(int[] array, int expectedIndex) { + int index = IntStream.range(0, array.length) + .reduce((a, b) -> array[a] <= array[b] ? a : b) + .orElse(-1); + assertThat(index).isEqualTo(expectedIndex); + } + + @ParameterizedTest + @MethodSource("primitiveProvider") + void givenArray_whenUsingPrimitiveStreams_thenGetCorrectResult(int[] array, int expectedIndex) { + List list = Arrays.stream(array).boxed().collect(Collectors.toList()); + int minValue = Arrays.stream(array).min().orElse(Integer.MAX_VALUE); + int index = list.indexOf(minValue); + assertThat(index).isEqualTo(expectedIndex); + } + + static Stream primitiveProvider() { + return Stream.of( + Arguments.of(new int[]{585, 190, 201, 82, 332}, 3), + Arguments.of(new int[]{1, 1, 1}, 0), + Arguments.of(new int[]{}, -1) + ); + } + + static Stream referenceTypesProvider() { + return Stream.of( + Arguments.of(new Integer[]{585, 190, 201, 82, 332}, 3), + Arguments.of(new Integer[]{1, 1, 1}, 0), + Arguments.of(new Integer[]{}, -1) + ); + } +} diff --git a/core-java-modules/core-java-collections-5/README.md b/core-java-modules/core-java-collections-5/README.md index e1ad221a31..1608b96775 100644 --- a/core-java-modules/core-java-collections-5/README.md +++ b/core-java-modules/core-java-collections-5/README.md @@ -7,10 +7,8 @@ - [Creating Custom Iterator in Java](https://www.baeldung.com/java-creating-custom-iterator) - [Difference Between Arrays.sort() and Collections.sort()](https://www.baeldung.com/java-arrays-collections-sort-methods) - [Skipping the First Iteration in Java](https://www.baeldung.com/java-skip-first-iteration) -- [Remove Elements From a Queue Using Loop](https://www.baeldung.com/java-remove-elements-queue) - [Intro to Vector Class in Java](https://www.baeldung.com/java-vector-guide) - [Time Complexity of Java Collections Sort in Java](https://www.baeldung.com/java-time-complexity-collections-sort) -- [Check if List Contains at Least One Enum](https://www.baeldung.com/java-list-check-enum-presence) - [Comparison of for Loops and Iterators](https://www.baeldung.com/java-for-loops-vs-iterators) - [PriorityQueue iterator() Method in Java](https://www.baeldung.com/java-priorityqueue-iterator) - [Immutable vs Unmodifiable Collection in Java](https://www.baeldung.com/java-collection-immutable-unmodifiable-differences) diff --git a/core-java-modules/core-java-collections-6/README.md b/core-java-modules/core-java-collections-6/README.md index 399e34a4d5..062e3e5409 100644 --- a/core-java-modules/core-java-collections-6/README.md +++ b/core-java-modules/core-java-collections-6/README.md @@ -5,4 +5,7 @@ ### Relevant Articles: - [Iterator vs forEach() in Java](https://www.baeldung.com/java-iterator-vs-foreach) - [Adding Elements to a Collection During Iteration](https://www.baeldung.com/java-add-elements-collection) +- [Remove Elements From a Queue Using Loop](https://www.baeldung.com/java-remove-elements-queue) +- [Check if List Contains at Least One Enum](https://www.baeldung.com/java-list-check-enum-presence) + - More articles: [[<-- prev]](/core-java-modules/core-java-collections-5) diff --git a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/checkiflistcontainsenum/CheckIfListContainsEnumUnitTest.java b/core-java-modules/core-java-collections-6/src/test/java/com/baeldung/checkiflistcontainsenum/CheckIfListContainsEnumUnitTest.java similarity index 96% rename from core-java-modules/core-java-collections-5/src/test/java/com/baeldung/checkiflistcontainsenum/CheckIfListContainsEnumUnitTest.java rename to core-java-modules/core-java-collections-6/src/test/java/com/baeldung/checkiflistcontainsenum/CheckIfListContainsEnumUnitTest.java index 0b9fd356e2..2d87d0ca47 100644 --- a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/checkiflistcontainsenum/CheckIfListContainsEnumUnitTest.java +++ b/core-java-modules/core-java-collections-6/src/test/java/com/baeldung/checkiflistcontainsenum/CheckIfListContainsEnumUnitTest.java @@ -1,57 +1,57 @@ -package com.baeldung.checkiflistcontainsenum; - -import org.junit.Assert; -import org.junit.Test; - -import java.util.*; - -public class CheckIfListContainsEnumUnitTest { - private final List> data = new ArrayList<>(); - - public CheckIfListContainsEnumUnitTest() { - Map map = new HashMap<>(); - map.put("Name", "John"); - map.put("Age", 25); - map.put("Position", Position.DEVELOPER); - - data.add(map); - } - - @Test - public void givenDataList_whenUsingLoop_thenCheckIfListContainsEnum() { - boolean containsEnumValue = false; - - for (Map entry : data) { - Object positionValue = entry.get("Position"); - if (Arrays.asList(Position.values()).contains(positionValue)) { - containsEnumValue = true; - break; - } - } - - Assert.assertTrue(containsEnumValue); - } - - @Test - public void givenDataList_whenUsingStream_thenCheckIfListContainsEnum() { - boolean containsEnumValue = data.stream() - .map(entry -> entry.get("Position")) - .anyMatch(position -> Arrays.asList(Position.values()).contains(position)); - - Assert.assertTrue(containsEnumValue); - } - - @Test - public void givenDataList_whenUsingDisjointMethod_thenCheckIfListContainsEnum() { - List positionValues = data.stream() - .map(entry -> (Position) entry.get("Position")) - .toList(); - - boolean containsEnumValue = !Collections.disjoint(Arrays.asList(Position.values()), positionValues); - Assert.assertTrue(containsEnumValue); - } - - public enum Position { - DEVELOPER, MANAGER, ANALYST - } -} +package com.baeldung.checkiflistcontainsenum; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.*; + +public class CheckIfListContainsEnumUnitTest { + private final List> data = new ArrayList<>(); + + public CheckIfListContainsEnumUnitTest() { + Map map = new HashMap<>(); + map.put("Name", "John"); + map.put("Age", 25); + map.put("Position", Position.DEVELOPER); + + data.add(map); + } + + @Test + public void givenDataList_whenUsingLoop_thenCheckIfListContainsEnum() { + boolean containsEnumValue = false; + + for (Map entry : data) { + Object positionValue = entry.get("Position"); + if (Arrays.asList(Position.values()).contains(positionValue)) { + containsEnumValue = true; + break; + } + } + + Assert.assertTrue(containsEnumValue); + } + + @Test + public void givenDataList_whenUsingStream_thenCheckIfListContainsEnum() { + boolean containsEnumValue = data.stream() + .map(entry -> entry.get("Position")) + .anyMatch(position -> Arrays.asList(Position.values()).contains(position)); + + Assert.assertTrue(containsEnumValue); + } + + @Test + public void givenDataList_whenUsingDisjointMethod_thenCheckIfListContainsEnum() { + List positionValues = data.stream() + .map(entry -> (Position) entry.get("Position")) + .toList(); + + boolean containsEnumValue = !Collections.disjoint(Arrays.asList(Position.values()), positionValues); + Assert.assertTrue(containsEnumValue); + } + + public enum Position { + DEVELOPER, MANAGER, ANALYST + } +} diff --git a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java b/core-java-modules/core-java-collections-6/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java similarity index 96% rename from core-java-modules/core-java-collections-5/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java rename to core-java-modules/core-java-collections-6/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java index 38fdc58099..b574853d50 100644 --- a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java +++ b/core-java-modules/core-java-collections-6/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java @@ -1,60 +1,60 @@ -package com.baeldung.removequeueelements; - -import org.junit.Test; - -import java.util.LinkedList; -import java.util.Queue; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class RemoveQueueElementsUnitTest { - @Test - public void givenQueueWithEvenAndOddNumbers_whenRemovingEvenNumbers_thenOddNumbersRemain() { - Queue queue = new LinkedList<>(); - Queue oddElementsQueue = new LinkedList<>(); - queue.add(1); - queue.add(2); - queue.add(3); - queue.add(4); - queue.add(5); - - while (queue.peek() != null) { - int element = queue.remove(); - if (element % 2 != 0) { - oddElementsQueue.add(element); - } - } - - assertEquals(3, oddElementsQueue.size()); - assertTrue(oddElementsQueue.contains(1)); - assertTrue(oddElementsQueue.contains(3)); - assertTrue(oddElementsQueue.contains(5)); - } - - @Test - public void givenStringQueue_whenRemovingStringsThatStartWithA_thenStringElementsRemain() { - Queue queue = new LinkedList<>(); - Queue stringElementsQueue = new LinkedList<>(); - queue.add("Apple"); - queue.add("Banana"); - queue.add("Orange"); - queue.add("Grape"); - queue.add("Mango"); - - - while (queue.peek() != null) { - String element = queue.remove(); - if (!element.startsWith("A")) { - stringElementsQueue.add(element); - } - } - - assertEquals(4, stringElementsQueue.size()); - assertTrue(stringElementsQueue.contains("Banana")); - assertTrue(stringElementsQueue.contains("Orange")); - assertTrue(stringElementsQueue.contains("Grape")); - assertTrue(stringElementsQueue.contains("Mango")); - } - -} +package com.baeldung.removequeueelements; + +import org.junit.Test; + +import java.util.LinkedList; +import java.util.Queue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class RemoveQueueElementsUnitTest { + @Test + public void givenQueueWithEvenAndOddNumbers_whenRemovingEvenNumbers_thenOddNumbersRemain() { + Queue queue = new LinkedList<>(); + Queue oddElementsQueue = new LinkedList<>(); + queue.add(1); + queue.add(2); + queue.add(3); + queue.add(4); + queue.add(5); + + while (queue.peek() != null) { + int element = queue.remove(); + if (element % 2 != 0) { + oddElementsQueue.add(element); + } + } + + assertEquals(3, oddElementsQueue.size()); + assertTrue(oddElementsQueue.contains(1)); + assertTrue(oddElementsQueue.contains(3)); + assertTrue(oddElementsQueue.contains(5)); + } + + @Test + public void givenStringQueue_whenRemovingStringsThatStartWithA_thenStringElementsRemain() { + Queue queue = new LinkedList<>(); + Queue stringElementsQueue = new LinkedList<>(); + queue.add("Apple"); + queue.add("Banana"); + queue.add("Orange"); + queue.add("Grape"); + queue.add("Mango"); + + + while (queue.peek() != null) { + String element = queue.remove(); + if (!element.startsWith("A")) { + stringElementsQueue.add(element); + } + } + + assertEquals(4, stringElementsQueue.size()); + assertTrue(stringElementsQueue.contains("Banana")); + assertTrue(stringElementsQueue.contains("Orange")); + assertTrue(stringElementsQueue.contains("Grape")); + assertTrue(stringElementsQueue.contains("Mango")); + } + +} diff --git a/core-java-modules/core-java-datetime-conversion-2/src/main/java/com/baeldung/convertdateandzoneddatetime/DateAndZonedDateTimeConverter.java b/core-java-modules/core-java-datetime-conversion-2/src/main/java/com/baeldung/convertdateandzoneddatetime/DateAndZonedDateTimeConverter.java new file mode 100644 index 0000000000..e33d200856 --- /dev/null +++ b/core-java-modules/core-java-datetime-conversion-2/src/main/java/com/baeldung/convertdateandzoneddatetime/DateAndZonedDateTimeConverter.java @@ -0,0 +1,17 @@ +package com.baeldung.convertdateandzoneddatetime; + +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; + +public class DateAndZonedDateTimeConverter { + + public static Date convertToDate(ZonedDateTime zonedDateTime) { + return Date.from(zonedDateTime.toInstant()); + } + + public static ZonedDateTime convertToZonedDateTime(Date date, ZoneId zone) { + return date.toInstant().atZone(zone); + } + +} diff --git a/core-java-modules/core-java-datetime-conversion-2/src/test/java/com/baeldung/convertdateandzoneddatetime/DateAndZonedDateTimeConverterUnitTest.java b/core-java-modules/core-java-datetime-conversion-2/src/test/java/com/baeldung/convertdateandzoneddatetime/DateAndZonedDateTimeConverterUnitTest.java new file mode 100644 index 0000000000..3c1a9c9426 --- /dev/null +++ b/core-java-modules/core-java-datetime-conversion-2/src/test/java/com/baeldung/convertdateandzoneddatetime/DateAndZonedDateTimeConverterUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.convertdateandzoneddatetime; + +import org.junit.jupiter.api.Test; + +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class DateAndZonedDateTimeConverterUnitTest { + + @Test + public void givenZonedDateTime_whenConvertToDate_thenCorrect() { + ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("UTC")); + Date date = DateAndZonedDateTimeConverter.convertToDate(zdt); + assertEquals(Date.from(zdt.toInstant()), date); + } + + @Test + public void givenDate_whenConvertToZonedDateTime_thenCorrect() { + Date date = new Date(); + ZoneId zoneId = ZoneId.of("UTC"); + ZonedDateTime zdt = DateAndZonedDateTimeConverter.convertToZonedDateTime(date, zoneId); + assertEquals(date.toInstant().atZone(zoneId), zdt); + } + +} diff --git a/core-java-modules/core-java-exceptions-4/README.md b/core-java-modules/core-java-exceptions-4/README.md index dc76b90fc7..f95e6991f0 100644 --- a/core-java-modules/core-java-exceptions-4/README.md +++ b/core-java-modules/core-java-exceptions-4/README.md @@ -10,4 +10,5 @@ This module contains articles about core java exceptions - [Get the Current Stack Trace in Java](https://www.baeldung.com/java-get-current-stack-trace) - [Errors and Exceptions in Java](https://www.baeldung.com/java-errors-vs-exceptions) - [Fix the IllegalArgumentException: No enum const class](https://www.baeldung.com/java-fix-no-enum-const-class) +- [How to Fix EOFException in Java](https://www.baeldung.com/java-fix-eofexception) - [[<-- Prev]](../core-java-exceptions-3) diff --git a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/eof/EOFExceptionDemo.java b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/eof/EOFExceptionDemo.java new file mode 100644 index 0000000000..9e1d687022 --- /dev/null +++ b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/eof/EOFExceptionDemo.java @@ -0,0 +1,16 @@ +package com.baeldung.exception.eof; + +import java.io.DataInputStream; +import java.io.InputStream; +import java.io.ByteArrayInputStream; + +public class EOFExceptionDemo { + public static void readInput() throws Exception { + InputStream is = new ByteArrayInputStream("123".getBytes()); + DataInputStream in = new DataInputStream(is); + while (true) { + char value = (char)in.readByte(); + System.out.println("Input value: " + value); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/eof/EOFExceptionDemo2.java b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/eof/EOFExceptionDemo2.java new file mode 100644 index 0000000000..837bd4583f --- /dev/null +++ b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/eof/EOFExceptionDemo2.java @@ -0,0 +1,22 @@ +package com.baeldung.exception.eof; + +import java.io.DataInputStream; +import java.io.InputStream; +import java.io.ByteArrayInputStream; +import java.io.EOFException; + +public class EOFExceptionDemo2 { + public static void readInput() throws Exception { + InputStream is = new ByteArrayInputStream("123".getBytes()); + DataInputStream in = new DataInputStream(is); + while (true) { + try { + char value = (char)in.readByte(); + System.out.println("Input value: " + value); + } catch (EOFException e) { + System.out.println("End of file"); + break; + } + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/eof/EOFExceptionDemo3.java b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/eof/EOFExceptionDemo3.java new file mode 100644 index 0000000000..ade729c096 --- /dev/null +++ b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/eof/EOFExceptionDemo3.java @@ -0,0 +1,19 @@ +package com.baeldung.exception.eof; + +import java.io.DataInputStream; +import java.io.InputStream; +import java.util.Scanner; +import java.io.ByteArrayInputStream; + +public class EOFExceptionDemo3 { + public static void readInput() { + InputStream is = new ByteArrayInputStream("1 2 3".getBytes()); + Scanner sc = new Scanner(is); + while (sc.hasNextInt()) { + int value = sc.nextInt(); + System.out.println("Input value: " + value); + } + System.out.println("End of file"); + sc.close(); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/eof/EOFExceptionDemo2UnitTest.java b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/eof/EOFExceptionDemo2UnitTest.java new file mode 100644 index 0000000000..b3969c01cb --- /dev/null +++ b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/eof/EOFExceptionDemo2UnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.exception.eof; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.AfterEach; +import java.io.PrintStream; +import java.io.ByteArrayOutputStream; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class EOFExceptionDemo2UnitTest { + + private final PrintStream standardOut = System.out; + private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); + + @BeforeEach + public void setUp() { + System.setOut(new PrintStream(outputStreamCaptor)); + } + + @AfterEach + public void tearDown() { + System.setOut(standardOut); + } + + @Test + void readInput()throws Exception { + EOFExceptionDemo2.readInput(); + String expectedOuput = "Input value: 1"; + expectedOuput += "\n" + "Input value: 2"; + expectedOuput += "\n" + "Input value: 3"; + expectedOuput += "\n" + "End of file"; + assertEquals(expectedOuput, outputStreamCaptor.toString() + .trim()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/eof/EOFExceptionDemo3UnitTest.java b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/eof/EOFExceptionDemo3UnitTest.java new file mode 100644 index 0000000000..313bd3159d --- /dev/null +++ b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/eof/EOFExceptionDemo3UnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.exception.eof; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.AfterEach; +import java.io.PrintStream; +import java.io.ByteArrayOutputStream; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class EOFExceptionDemo3UnitTest { + + private final PrintStream standardOut = System.out; + private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); + + @BeforeEach + public void setUp() { + System.setOut(new PrintStream(outputStreamCaptor)); + } + + @AfterEach + public void tearDown() { + System.setOut(standardOut); + } + + @Test + void readInput() { + EOFExceptionDemo3.readInput(); + String expectedOuput = "Input value: 1"; + expectedOuput += "\n" + "Input value: 2"; + expectedOuput += "\n" + "Input value: 3"; + expectedOuput += "\n" + "End of file"; + assertEquals(expectedOuput, outputStreamCaptor.toString() + .trim()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/eof/EOFExceptionDemoUnitTest.java b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/eof/EOFExceptionDemoUnitTest.java new file mode 100644 index 0000000000..41275523e1 --- /dev/null +++ b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/eof/EOFExceptionDemoUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.exception.eof; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.AfterEach; +import java.io.EOFException; +import java.io.PrintStream; +import java.io.ByteArrayOutputStream; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class EOFExceptionDemoUnitTest { + + private final PrintStream standardOut = System.out; + private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); + + @BeforeEach + public void setUp() { + System.setOut(new PrintStream(outputStreamCaptor)); + } + + @AfterEach + public void tearDown() { + System.setOut(standardOut); + } + + @Test + void readInput_throwsEOFException() { + assertThrows(EOFException.class, () -> EOFExceptionDemo.readInput()); + String expectedOuput = "Input value: 1"; + expectedOuput += "\n" + "Input value: 2"; + expectedOuput += "\n" + "Input value: 3"; + assertEquals(expectedOuput, outputStreamCaptor.toString() + .trim()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-6/README.md b/core-java-modules/core-java-lang-6/README.md index 5319dd15f7..de5b0d09c5 100644 --- a/core-java-modules/core-java-lang-6/README.md +++ b/core-java-modules/core-java-lang-6/README.md @@ -6,11 +6,9 @@ This module contains articles about core features in the Java language - [Convert One Enum to Another Enum in Java](https://www.baeldung.com/java-convert-enums) - [What Is the Maximum Depth of the Java Call Stack?](https://www.baeldung.com/java-call-stack-max-depth) -- [Get a Random Element From a Set in Java](https://www.baeldung.com/java-set-draw-sample) - [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code) - [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects) - [Return First Non-null Value in Java](https://www.baeldung.com/java-first-non-null) -- [Compress and Uncompress Byte Array Using Deflater/Inflater](https://www.baeldung.com/java-compress-uncompress-byte-array) - [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables) - [What Is the Error: “Non-static method cannot be referenced from a static context”?](https://www.baeldung.com/java-non-static-method-cannot-be-referenced-from-a-static-context) - [Recursively Sum the Integers in an Array](https://www.baeldung.com/java-recursive-sum-integer-array) diff --git a/core-java-modules/core-java-lang-6/Dockerfile b/core-java-modules/core-java-lang-7/Dockerfile similarity index 100% rename from core-java-modules/core-java-lang-6/Dockerfile rename to core-java-modules/core-java-lang-7/Dockerfile diff --git a/core-java-modules/core-java-lang-7/README.md b/core-java-modules/core-java-lang-7/README.md new file mode 100644 index 0000000000..467485668f --- /dev/null +++ b/core-java-modules/core-java-lang-7/README.md @@ -0,0 +1,11 @@ +## Core Java Lang (Part 7) + +This module contains articles about core features in the Java language + +### Relevant Articles: + +- [Set an Environment Variable at Runtime in Java](https://www.baeldung.com/java-set-environment-variable-runtime) +- [Get a Random Element From a Set in Java](https://www.baeldung.com/java-set-draw-sample) +- [Compress and Uncompress Byte Array Using Deflater/Inflater](https://www.baeldung.com/java-compress-uncompress-byte-array) + +[[<-- Prev]](/core-java-modules/core-java-lang-6) diff --git a/core-java-modules/core-java-lang-6/docker-pom.xml b/core-java-modules/core-java-lang-7/docker-pom.xml similarity index 100% rename from core-java-modules/core-java-lang-6/docker-pom.xml rename to core-java-modules/core-java-lang-7/docker-pom.xml diff --git a/core-java-modules/core-java-lang-7/pom.xml b/core-java-modules/core-java-lang-7/pom.xml new file mode 100644 index 0000000000..886b01c475 --- /dev/null +++ b/core-java-modules/core-java-lang-7/pom.xml @@ -0,0 +1,70 @@ + + + 4.0.0 + core-java-lang-7 + jar + core-java-lang-7 + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + org.junit-pioneer + junit-pioneer + ${junit.pioneer.version} + test + + + org.testcontainers + testcontainers + ${testcontaienr.version} + test + + + org.testcontainers + junit-jupiter + ${testcontaienr.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + + org.mapstruct + mapstruct-processor + ${mapstruct.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + 14 + 14 + + + + + + + 2.2.0 + 1.19.3 + 1.6.0.Beta1 + 1.37 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java b/core-java-modules/core-java-lang-7/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java similarity index 100% rename from core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java rename to core-java-modules/core-java-lang-7/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/randominset/RandomInSetUtil.java b/core-java-modules/core-java-lang-7/src/main/java/com/baeldung/randominset/RandomInSetUtil.java similarity index 100% rename from core-java-modules/core-java-lang-6/src/main/java/com/baeldung/randominset/RandomInSetUtil.java rename to core-java-modules/core-java-lang-7/src/main/java/com/baeldung/randominset/RandomInSetUtil.java diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/compressbytes/CompressByteArrayUnitTest.java b/core-java-modules/core-java-lang-7/src/test/java/com/baeldung/compressbytes/CompressByteArrayUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-6/src/test/java/com/baeldung/compressbytes/CompressByteArrayUnitTest.java rename to core-java-modules/core-java-lang-7/src/test/java/com/baeldung/compressbytes/CompressByteArrayUnitTest.java diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/setenvironment/SettingChildProcessEnvironmentVariableUnitTest.java b/core-java-modules/core-java-lang-7/src/test/java/com/baeldung/setenvironment/SettingChildProcessEnvironmentVariableUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-6/src/test/java/com/baeldung/setenvironment/SettingChildProcessEnvironmentVariableUnitTest.java rename to core-java-modules/core-java-lang-7/src/test/java/com/baeldung/setenvironment/SettingChildProcessEnvironmentVariableUnitTest.java diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/setenvironment/SettingDockerEnvironmentVariableUnitTest.java b/core-java-modules/core-java-lang-7/src/test/java/com/baeldung/setenvironment/SettingDockerEnvironmentVariableUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-6/src/test/java/com/baeldung/setenvironment/SettingDockerEnvironmentVariableUnitTest.java rename to core-java-modules/core-java-lang-7/src/test/java/com/baeldung/setenvironment/SettingDockerEnvironmentVariableUnitTest.java diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/setenvironment/SettingSameProcessEnvironmentVariableUnitTest.java b/core-java-modules/core-java-lang-7/src/test/java/com/baeldung/setenvironment/SettingSameProcessEnvironmentVariableUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-6/src/test/java/com/baeldung/setenvironment/SettingSameProcessEnvironmentVariableUnitTest.java rename to core-java-modules/core-java-lang-7/src/test/java/com/baeldung/setenvironment/SettingSameProcessEnvironmentVariableUnitTest.java diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/setenvironment/SettingTestcontainerVariableUnitTest.java b/core-java-modules/core-java-lang-7/src/test/java/com/baeldung/setenvironment/SettingTestcontainerVariableUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-6/src/test/java/com/baeldung/setenvironment/SettingTestcontainerVariableUnitTest.java rename to core-java-modules/core-java-lang-7/src/test/java/com/baeldung/setenvironment/SettingTestcontainerVariableUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/testhashcode/HahCodeUnitTest.java b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/testhashcode/HahCodeUnitTest.java new file mode 100644 index 0000000000..6b38d9487e --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/testhashcode/HahCodeUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.testhashcode; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertEquals; + +public class HahCodeUnitTest { + @Test + public void givenObject_whenTestingHashCodeConsistency_thenConsistentHashCodeReturned() { + MyClass obj = new MyClass("value"); + int hashCode1 = obj.hashCode(); + int hashCode2 = obj.hashCode(); + assertEquals(hashCode1, hashCode2); + } + + @Test + public void givenTwoEqualObjects_whenTestingHashCodeEquality_thenEqualHashCodesReturned() { + MyClass obj1 = new MyClass("value"); + MyClass obj2 = new MyClass("value"); + assertEquals(obj1.hashCode(), obj2.hashCode()); + } + + @Test + public void givenMultipleObjects_whenTestingHashCodeDistribution_thenEvenDistributionOfHashCodes() { + List objects = new ArrayList<>(); + for (int i = 0; i < 1000; i++) { + objects.add(new MyClass("value" + i)); + } + + Set hashCodes = new HashSet<>(); + for (MyClass obj : objects) { + hashCodes.add(obj.hashCode()); + } + + assertEquals(objects.size(), hashCodes.size(), 10); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/testhashcode/MyClass.java b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/testhashcode/MyClass.java new file mode 100644 index 0000000000..52c42ed68c --- /dev/null +++ b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/testhashcode/MyClass.java @@ -0,0 +1,15 @@ +package com.baeldung.testhashcode; + +public class MyClass { + private String value; + + public MyClass(String value) { + this.value = value; + } + + @Override + public int hashCode() { + return value != null ? value.hashCode() : 0; + } + +} diff --git a/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/bigdecimalequalvscompare/BigDecimalEqualityUnitTest.java b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/bigdecimalequalvscompare/BigDecimalEqualityUnitTest.java new file mode 100644 index 0000000000..41deb388de --- /dev/null +++ b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/bigdecimalequalvscompare/BigDecimalEqualityUnitTest.java @@ -0,0 +1,121 @@ +package com.baeldung.bigdecimalequalvscompare; + +import static java.math.RoundingMode.HALF_UP; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; + +class BigDecimalEqualityUnitTest { + + @ParameterizedTest + @MethodSource("decimalCompareToProvider") + void givenBigDecimals_WhenCompare_ThenGetReasonableResult(BigDecimal fistDecimal, + BigDecimal secondDecimal, boolean areComparablySame) { + assertEquals(fistDecimal.compareTo(secondDecimal) == 0, areComparablySame); + } + + + @ParameterizedTest + @MethodSource("decimalEqualsProvider") + void givenBigDecimals_WhenCheckEquality_ThenConsiderPrecision(BigDecimal fistDecimal, + BigDecimal secondDecimal, boolean areEqual) { + assertEquals(fistDecimal.equals(secondDecimal), areEqual); + } + + @ParameterizedTest + @MethodSource("decimalEqualsProvider") + void givenBigDecimals_WhenCheckEqualityWithoutTrailingZeros_ThenTheSameAsCompareTo(BigDecimal fistDecimal, + BigDecimal secondDecimal) { + BigDecimal strippedFirstDecimal = fistDecimal.stripTrailingZeros(); + BigDecimal strippedSecondDecimal = secondDecimal.stripTrailingZeros(); + assertEquals(strippedFirstDecimal.equals(strippedSecondDecimal), + strippedFirstDecimal.compareTo(strippedSecondDecimal) == 0); + } + + @ParameterizedTest + @MethodSource("decimalProvider") + void givenListOfDecimals_WhenAddingToHashSet_ThenUsingEquals(List decimalList) { + Set decimalSet = new HashSet<>(decimalList); + assertThat(decimalSet).hasSameElementsAs(decimalList); + } + + @ParameterizedTest + @MethodSource("decimalProvider") + void givenListOfDecimals_WhenAddingToSortedSet_ThenUsingCompareTo(List decimalList, + List expectedDecimalList) { + Set decimalSet = new TreeSet<>(decimalList); + assertThat(decimalSet).hasSameElementsAs(expectedDecimalList); + } + + @ParameterizedTest + @CsvSource({ + "2.0, 2.00", + "4.0, 4.00" + }) + void givenNumbersWithDifferentPrecision_WhenPerformingTheSameOperation_TheResultsAreDifferent( + String firstNumber, String secondNumber) { + + BigDecimal firstResult = new BigDecimal(firstNumber).divide(BigDecimal.valueOf(3), HALF_UP); + BigDecimal secondResult = new BigDecimal(secondNumber).divide(BigDecimal.valueOf(3), HALF_UP); + assertThat(firstResult).isNotEqualTo(secondResult); + } + + static Stream decimalCompareToProvider() { + return Stream.of( + Arguments.of(new BigDecimal("0.1"), new BigDecimal("0.1"), true), + Arguments.of(new BigDecimal("1.1"), new BigDecimal("1.1"), true), + Arguments.of(new BigDecimal("1.10"), new BigDecimal("1.1"), true), + Arguments.of(new BigDecimal("0.100"), new BigDecimal("0.10000"), true), + Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1000"), true), + Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1001"), false), + Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1010"), false), + Arguments.of(new BigDecimal("0.2"), new BigDecimal("0.19999999"), false), + Arguments.of(new BigDecimal("1.0"), new BigDecimal("1.1"), false), + Arguments.of(new BigDecimal("0.01"), new BigDecimal("0.0099999"), false) + ); + } + + static Stream decimalEqualsProvider() { + return Stream.of( + Arguments.of(new BigDecimal("0.1"), new BigDecimal("0.1"), true), + Arguments.of(new BigDecimal("1.1"), new BigDecimal("1.1"), true), + Arguments.of(new BigDecimal("1.10"), new BigDecimal("1.1"), false), + Arguments.of(new BigDecimal("0.100"), new BigDecimal("0.10000"), false), + Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1000"), false), + Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1001"), false), + Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1010"), false), + Arguments.of(new BigDecimal("0.2"), new BigDecimal("0.19999999"), false), + Arguments.of(new BigDecimal("1.0"), new BigDecimal("1.1"), false), + Arguments.of(new BigDecimal("0.01"), new BigDecimal("0.0099999"), false) + ); + } + + static Stream decimalProvider() { + return Stream.of(Arguments.of(Arrays.asList( + new BigDecimal("1.1"), + new BigDecimal("1.10"), + new BigDecimal("1.100"), + new BigDecimal("0.10"), + new BigDecimal("0.100"), + new BigDecimal("0.1000"), + new BigDecimal("0.2"), + new BigDecimal("0.20"), + new BigDecimal("0.200")), + + Arrays.asList( + new BigDecimal("1.1"), + new BigDecimal("0.10"), + new BigDecimal("0.2")))); + } +} diff --git a/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/comparenumbers/ComparingNumbersOfDifferentClassesUnitTest.java b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/comparenumbers/ComparingNumbersOfDifferentClassesUnitTest.java new file mode 100644 index 0000000000..a196075f5a --- /dev/null +++ b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/comparenumbers/ComparingNumbersOfDifferentClassesUnitTest.java @@ -0,0 +1,158 @@ +package com.baeldung.comparenumbers; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +class ComparingNumbersOfDifferentClassesUnitTest { + + @ValueSource(strings = {"1", "2", "3", "4", "5"}) + @ParameterizedTest + void givenSameNumbersButDifferentPrimitives_WhenCheckEquality_ThenTheyEqual(String number) { + int integerNumber = Integer.parseInt(number); + long longNumber = Long.parseLong(number); + assertEquals(longNumber, integerNumber); + } + + @ValueSource(strings = {"1", "2", "3", "4", "5"}) + @ParameterizedTest + void givenSameNumbersButDifferentPrimitivesWithIntegerOverflow_WhenCheckEquality_ThenTheyNotEqual(String number) { + int integerNumber = Integer.MAX_VALUE + Integer.parseInt(number); + long longNumber = Integer.MAX_VALUE + Long.parseLong(number); + assertNotEquals(longNumber, integerNumber); + } + + @ValueSource(strings = {"1", "2", "3", "4", "5"}) + @ParameterizedTest + void givenSameNumbersButDifferentPrimitivesTypes_WhenCheckEquality_ThenTheyEqual(String number) { + int integerNumber = Integer.parseInt(number); + double doubleNumber = Double.parseDouble(number); + assertEquals(doubleNumber, integerNumber); + } + + @ValueSource(strings = {"1", "2", "3", "4", "5"}) + @ParameterizedTest + void givenDifferentNumbersButDifferentPrimitivesTypes_WhenCheckEquality_ThenTheyNotEqual(String number) { + int integerNumber = Integer.parseInt(number); + double doubleNumber = Double.parseDouble(number) + 0.0000000000001; + assertNotEquals(doubleNumber, integerNumber); + } + + @Test + void givenSameNumbersButDifferentPrimitivesWithLongOverflow_WhenCheckEquality_ThenTheyEqual() { + long longValue = BigInteger.valueOf(Long.MAX_VALUE) + .add(BigInteger.ONE) + .multiply(BigInteger.TWO).longValue(); + int integerValue = BigInteger.valueOf(Long.MAX_VALUE) + .add(BigInteger.ONE).intValue(); + assertThat(longValue).isEqualTo(integerValue); + } + @Test + void givenSameNumbersButDifferentPrimitivesWithDoubleOverflow_WhenCheckEquality_ThenTheyEqual() { + double firstDoubleValue = BigDecimal.valueOf(Double.MAX_VALUE).add(BigDecimal.valueOf(42)).doubleValue(); + double secondDoubleValue = BigDecimal.valueOf(Double.MAX_VALUE).doubleValue(); + assertEquals(firstDoubleValue, secondDoubleValue); + } + + @Test + void givenSameNumbersWithDoubleRoundingErrors_WhenCheckEquality_ThenTheyNotEqual() { + double doubleValue = 0.3 / 0.1; + int integerValue = 30 / 10; + assertNotEquals(doubleValue, integerValue); + } + + @ValueSource(strings = {"1", "2", "3", "4", "5"}) + @ParameterizedTest + void givenSameNumbersButDifferentWrappers_WhenCheckEquality_ThenTheyNotEqual(String number) { + Integer integerNumber = Integer.valueOf(number); + Long longNumber = Long.valueOf(number); + assertNotEquals(longNumber, integerNumber); + } + + @ValueSource(strings = {"1", "2", "3", "4", "5"}) + @ParameterizedTest + void givenSameNumbersButWrapperTypes_WhenCheckEquality_ThenTheyNotEqual(String number) { + Float floatNumber = Float.valueOf(number); + Integer integerNumber = Integer.valueOf(number); + assertNotEquals(floatNumber, integerNumber); + } + + @MethodSource("numbersWithDifferentScaleProvider") + @ParameterizedTest + void givenBigDecimalsWithDifferentScale_WhenCheckEquality_ThenTheyNotEqual(String firstNumber, + String secondNumber) { + BigDecimal firstBigDecimal = new BigDecimal(firstNumber); + BigDecimal secondBigDecimal = new BigDecimal(secondNumber); + + assertNotEquals(firstBigDecimal, secondBigDecimal); + } + + @MethodSource("numbersWithDifferentScaleProvider") + @ParameterizedTest + void givenBigDecimalsWithDifferentScale_WhenCompare_ThenTheyEqual(String firstNumber, + String secondNumber) { + BigDecimal firstBigDecimal = new BigDecimal(firstNumber); + BigDecimal secondBigDecimal = new BigDecimal(secondNumber); + + assertEquals(0, firstBigDecimal.compareTo(secondBigDecimal)); + } + + @MethodSource("numbersWithDifferentScaleProvider") + @ParameterizedTest + void givenBigDecimalsWithDifferentScale_WhenCompareWithAssertJ_ThenTheyEqual(String firstNumber, + String secondNumber) { + BigDecimal firstBigDecimal = new BigDecimal(firstNumber); + BigDecimal secondBigDecimal = new BigDecimal(secondNumber); + + assertThat(firstBigDecimal).isEqualByComparingTo(secondBigDecimal); + } + + + @MethodSource("numbersWithSameScaleProvider") + @ParameterizedTest + void givenBigDecimalsWithSameScale_WhenCheckEquality_ThenTheyEqual(String firstNumber, + String secondNumber) { + BigDecimal firstBigDecimal = new BigDecimal(firstNumber); + BigDecimal secondBigDecimal = new BigDecimal(secondNumber); + + assertEquals(firstBigDecimal, secondBigDecimal); + } + + @MethodSource("numbersWithSameScaleProvider") + @ParameterizedTest + void givenBigDecimalsWithSameScale_WhenCompare_ThenTheyEqual(String firstNumber, + String secondNumber) { + BigDecimal firstBigDecimal = new BigDecimal(firstNumber); + BigDecimal secondBigDecimal = new BigDecimal(secondNumber); + + assertEquals(0, firstBigDecimal.compareTo(secondBigDecimal)); + } + + + static Stream numbersWithDifferentScaleProvider() { + return Stream.of( + Arguments.of("0", "0.0"), Arguments.of("1", "1.0"), + Arguments.of("2", "2.0"), Arguments.of("3", "3.0"), + Arguments.of("4", "4.0"), Arguments.of("5", "5.0"), + Arguments.of("6", "6.0"), Arguments.of("7", "7.0") + ); + } + + static Stream numbersWithSameScaleProvider() { + return Stream.of( + Arguments.of("0", "0"), Arguments.of("1", "1"), + Arguments.of("2", "2"), Arguments.of("3", "3"), + Arguments.of("4", "4"), Arguments.of("5", "5"), + Arguments.of("6", "6"), Arguments.of("7", "7") + ); + } +} diff --git a/core-java-modules/core-java-string-operations-7/README.md b/core-java-modules/core-java-string-operations-7/README.md index 97249b1a8b..0ef528f162 100644 --- a/core-java-modules/core-java-string-operations-7/README.md +++ b/core-java-modules/core-java-string-operations-7/README.md @@ -6,7 +6,6 @@ - [Check if a String Contains a Number Value in Java](https://www.baeldung.com/java-string-number-presence) - [String’s Maximum Length in Java](https://www.baeldung.com/java-strings-maximum-length) - [Java’s String.length() and String.getBytes().length](https://www.baeldung.com/java-string-length-vs-getbytes-length) -- [Check If a Java StringBuilder Object Contains a Character](https://www.baeldung.com/java-check-stringbuilder-object-contains-character) - [Comparing One String With Multiple Values in One Expression in Java](https://www.baeldung.com/java-compare-string-multiple-values-one-expression) - [Regular Expression for Password Validation in Java](https://www.baeldung.com/java-regex-password-validation) - [Mask an Email Address and Phone Number in Java](https://www.baeldung.com/java-mask-email-address-phone-number) diff --git a/core-java-modules/core-java-string-operations-9/README.md b/core-java-modules/core-java-string-operations-9/README.md index aab4178988..a7e3f6de58 100644 --- a/core-java-modules/core-java-string-operations-9/README.md +++ b/core-java-modules/core-java-string-operations-9/README.md @@ -6,4 +6,5 @@ - [UTF-8 Validation in Java](https://www.baeldung.com/java-utf-8-validation) - [Simple Morse Code Translation in Java](https://www.baeldung.com/java-morse-code-english-translate) - [How to Determine if a String Contains Invalid Encoded Characters](https://www.baeldung.com/java-check-string-contains-invalid-encoded-characters) +- [Check If a Java StringBuilder Object Contains a Character](https://www.baeldung.com/java-check-stringbuilder-object-contains-character) - More articles: [[<-- prev]](../core-java-string-operations-8) diff --git a/core-java-modules/core-java-string-operations-9/src/test/java/com/baeldung/LastOccurrenceFinder/LastOccurrenceFinderUnitTest.java b/core-java-modules/core-java-string-operations-9/src/test/java/com/baeldung/LastOccurrenceFinder/LastOccurrenceFinderUnitTest.java new file mode 100644 index 0000000000..1c9fb327b7 --- /dev/null +++ b/core-java-modules/core-java-string-operations-9/src/test/java/com/baeldung/LastOccurrenceFinder/LastOccurrenceFinderUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.LastOccurrenceFinder; + +import org.junit.Test; + +import java.util.OptionalInt; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; + +public class LastOccurrenceFinderUnitTest { + String str = "Welcome to Baeldung"; + char target = 'e'; + int n = 2; + int expectedIndex = 6; + + @Test + public void givenStringAndCharAndN_whenFindingNthLastOccurrence_thenCorrectIndexReturned() { + int count = 0; + int index = -1; + for (int i = str.length() - 1; i >= 0; i--) { + if (str.charAt(i) == target) { + count++; + if (count == n) { + index = i; + break; + } + } + } + assertEquals(expectedIndex, index); + } + + @Test + public void givenStringAndCharAndN_whenFindingNthLastOccurrenceUsingStreams_thenCorrectIndexReturned() { + + OptionalInt result = IntStream.range(0, str.length()) + .map(i -> str.length() - 1 - i) + .filter(i -> str.charAt(i) == target) + .skip(n - 1) + .findFirst(); + int index = result.orElse(-1); + assertEquals(expectedIndex, index); + } +} diff --git a/core-java-modules/core-java-string-operations-9/src/test/java/com/baeldung/hashmapcharactercount/HashMapCharacterCountUnitTest.java b/core-java-modules/core-java-string-operations-9/src/test/java/com/baeldung/hashmapcharactercount/HashMapCharacterCountUnitTest.java new file mode 100644 index 0000000000..7f3e390c80 --- /dev/null +++ b/core-java-modules/core-java-string-operations-9/src/test/java/com/baeldung/hashmapcharactercount/HashMapCharacterCountUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.hashmapcharactercount; + +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static java.util.stream.Collectors.toMap; +import static org.junit.Assert.assertEquals; + +public class HashMapCharacterCountUnitTest { + String str = "abcaadcbcb"; + + @Test + public void givenString_whenUsingStreams_thenVerifyCounts() { + Map charCount = str.chars() + .boxed() + .collect(toMap( + k -> (char) k.intValue(), + v -> 1, + Integer::sum)); + + assertEquals(3, charCount.get('a').intValue()); + } + + @Test + public void givenString_whenUsingLooping_thenVerifyCounts() { + Map charCount = new HashMap<>(); + for (char c : str.toCharArray()) { + charCount.merge(c, + 1, + Integer::sum); + } + assertEquals(3, charCount.get('a').intValue()); + } + + +} diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/stringbuilderhaschar/CheckIfStringBuilderContainsCharUnitTest.java b/core-java-modules/core-java-string-operations-9/src/test/java/com/baeldung/stringbuilderhaschar/CheckIfStringBuilderContainsCharUnitTest.java similarity index 92% rename from core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/stringbuilderhaschar/CheckIfStringBuilderContainsCharUnitTest.java rename to core-java-modules/core-java-string-operations-9/src/test/java/com/baeldung/stringbuilderhaschar/CheckIfStringBuilderContainsCharUnitTest.java index 8d95b5533a..31740152e5 100644 --- a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/stringbuilderhaschar/CheckIfStringBuilderContainsCharUnitTest.java +++ b/core-java-modules/core-java-string-operations-9/src/test/java/com/baeldung/stringbuilderhaschar/CheckIfStringBuilderContainsCharUnitTest.java @@ -2,7 +2,7 @@ package com.baeldung.stringbuilderhaschar; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CheckIfStringBuilderContainsCharUnitTest { diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 665b0b931d..6b4edaf7f2 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -144,6 +144,7 @@ core-java-lang-4 core-java-lang-5 core-java-lang-6 + core-java-lang-7 core-java-lang-math core-java-lang-math-2 core-java-lang-math-4 diff --git a/gradle-modules/gradle-customization/gradle-avro/.gitattributes b/gradle-modules/gradle-customization/gradle-avro/.gitattributes new file mode 100644 index 0000000000..097f9f98d9 --- /dev/null +++ b/gradle-modules/gradle-customization/gradle-avro/.gitattributes @@ -0,0 +1,9 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + diff --git a/gradle-modules/gradle-customization/gradle-avro/.gitignore b/gradle-modules/gradle-customization/gradle-avro/.gitignore new file mode 100644 index 0000000000..1b6985c009 --- /dev/null +++ b/gradle-modules/gradle-customization/gradle-avro/.gitignore @@ -0,0 +1,5 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build diff --git a/gradle-modules/gradle-customization/gradle-avro/README.md b/gradle-modules/gradle-customization/gradle-avro/README.md new file mode 100644 index 0000000000..5616cce48b --- /dev/null +++ b/gradle-modules/gradle-customization/gradle-avro/README.md @@ -0,0 +1 @@ +## Relevant Articles diff --git a/gradle-modules/gradle-customization/gradle-avro/build.gradle b/gradle-modules/gradle-customization/gradle-avro/build.gradle new file mode 100644 index 0000000000..7a9565cb0c --- /dev/null +++ b/gradle-modules/gradle-customization/gradle-avro/build.gradle @@ -0,0 +1,63 @@ +buildscript { + dependencies { + classpath libs.avro.tools + } +} + +plugins { + id 'java' + alias libs.plugins.avro +} + +repositories { + mavenCentral() +} + +dependencies { + implementation libs.avro + // Use JUnit Jupiter for testing. + testImplementation libs.junit.jupiter + + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + +} + +import org.apache.avro.tool.SpecificCompilerTool + +sourceCompatibility = JavaVersion.VERSION_21 +targetCompatibility = JavaVersion.VERSION_21 + +def avroSchemasDir = "src/main/custom" +def avroCodeGenerationDir = "build/generated-main-avro-custom-java" + +// Add the generated Avro Java code to the Gradle source files. +sourceSets.main.java.srcDirs += [avroCodeGenerationDir] + +tasks.register('customAvroCodeGeneration') { + // Define the task inputs and outputs for the Gradle up-to-date checks. + inputs.dir(avroSchemasDir) + outputs.dir(avroCodeGenerationDir) + // The Avro code generation logs to the standard streams. Redirect the standard streams to the Gradle log. + logging.captureStandardOutput(LogLevel.INFO); + logging.captureStandardError(LogLevel.ERROR) + doLast { + // Run the Avro code generation. + new SpecificCompilerTool().run(System.in, System.out, System.err, List.of( + "-encoding", "UTF-8", + "-string", + "-fieldVisibility", "private", + "-noSetters", + "schema", "$projectDir/$avroSchemasDir".toString(), "$projectDir/$avroCodeGenerationDir".toString() + )) + } +} + +tasks.withType(JavaCompile).configureEach { + // Make Java compilation tasks depend on the Avro code generation task. + dependsOn('customAvroCodeGeneration') +} + +tasks.named('test') { + // Use JUnit Platform for unit tests. + useJUnitPlatform() +} diff --git a/gradle-modules/gradle-customization/gradle-avro/gradle/libs.versions.toml b/gradle-modules/gradle-customization/gradle-avro/gradle/libs.versions.toml new file mode 100644 index 0000000000..8a2b7df961 --- /dev/null +++ b/gradle-modules/gradle-customization/gradle-avro/gradle/libs.versions.toml @@ -0,0 +1,14 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format + +[versions] +junit-jupiter = "5.10.0" +avro = "1.11.0" + +[libraries] +junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit-jupiter" } +avro = {module = "org.apache.avro:avro", version.ref = "avro"} +avro-tools = {module = "org.apache.avro:avro-tools", version.ref = "avro"} + +[plugins] +avro = { id = "com.github.davidmc24.gradle.plugin.avro", version = "1.9.1" } diff --git a/gradle-modules/gradle-customization/gradle-avro/gradle/wrapper/gradle-wrapper.jar b/gradle-modules/gradle-customization/gradle-avro/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..d64cd49177 Binary files /dev/null and b/gradle-modules/gradle-customization/gradle-avro/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle-modules/gradle-customization/gradle-avro/gradle/wrapper/gradle-wrapper.properties b/gradle-modules/gradle-customization/gradle-avro/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..1af9e0930b --- /dev/null +++ b/gradle-modules/gradle-customization/gradle-avro/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradle-modules/gradle-customization/gradle-avro/gradlew b/gradle-modules/gradle-customization/gradle-avro/gradlew new file mode 100755 index 0000000000..1aa94a4269 --- /dev/null +++ b/gradle-modules/gradle-customization/gradle-avro/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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 +# +# https://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 POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# 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 ;; #( + MSYS* | 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# 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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradle-modules/gradle-customization/gradle-avro/gradlew.bat b/gradle-modules/gradle-customization/gradle-avro/gradlew.bat new file mode 100644 index 0000000000..93e3f59f13 --- /dev/null +++ b/gradle-modules/gradle-customization/gradle-avro/gradlew.bat @@ -0,0 +1,92 @@ +@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 https://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=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@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% equ 0 goto execute + +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 execute + +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 + +: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 %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/gradle-modules/gradle-customization/gradle-avro/settings.gradle b/gradle-modules/gradle-customization/gradle-avro/settings.gradle new file mode 100644 index 0000000000..640d0840ef --- /dev/null +++ b/gradle-modules/gradle-customization/gradle-avro/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'gradle-avro' + diff --git a/gradle-modules/gradle-customization/gradle-avro/src/main/avro/user.avsc b/gradle-modules/gradle-customization/gradle-avro/src/main/avro/user.avsc new file mode 100644 index 0000000000..7f9cde4d9e --- /dev/null +++ b/gradle-modules/gradle-customization/gradle-avro/src/main/avro/user.avsc @@ -0,0 +1,19 @@ +{ + "type": "record", + "name": "User", + "namespace": "avro", + "fields": [ + { + "name": "firstName", + "type": "string" + }, + { + "name": "lastName", + "type": "string" + }, + { + "name": "phoneNumber", + "type": "string" + } + ] +} diff --git a/gradle-modules/gradle-customization/gradle-avro/src/main/custom/pet.avsc b/gradle-modules/gradle-customization/gradle-avro/src/main/custom/pet.avsc new file mode 100644 index 0000000000..427093feb5 --- /dev/null +++ b/gradle-modules/gradle-customization/gradle-avro/src/main/custom/pet.avsc @@ -0,0 +1,23 @@ +{ + "type": "record", + "name": "Pet", + "namespace": "custom.avro", + "fields": [ + { + "name": "petId", + "type": "string" + }, + { + "name": "name", + "type": "string" + }, + { + "name": "species", + "type": "string" + }, + { + "name": "age", + "type": "int" + } + ] +} diff --git a/gradle-modules/gradle-customization/gradle-avro/src/test/java/com.baeldung.avro/AvroCodeGenerationUnitTest.java b/gradle-modules/gradle-customization/gradle-avro/src/test/java/com.baeldung.avro/AvroCodeGenerationUnitTest.java new file mode 100644 index 0000000000..f3d40a9f66 --- /dev/null +++ b/gradle-modules/gradle-customization/gradle-avro/src/test/java/com.baeldung.avro/AvroCodeGenerationUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.avro; + +import avro.User; +import custom.avro.Pet; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class AvroCodeGenerationUnitTest { + + @Test + void givenUserData_whenJavaClassGeneratedWithPlugin_thenDataShouldMatch() { + final String firstName = "John"; + final String lastName = "Doe"; + final String phoneNumber = "+380659443235"; + + User user = User.newBuilder() + .setFirstName(firstName) + .setLastName(lastName) + .setPhoneNumber(phoneNumber) + .build(); + + assertEquals(firstName, user.getFirstName()); + assertEquals(lastName, user.getLastName()); + assertEquals(phoneNumber, user.getPhoneNumber()); + } + + @Test + void givenUserData_whenJavaClassGeneratedWithTask_thenDataShouldMatch() { + final String petId = "123"; + final String name = "Fluffy"; + final String species = "Cat"; + final int age = 3; + + Pet pet = Pet.newBuilder() + .setPetId(petId) + .setName(name) + .setSpecies(species) + .setAge(age) + .build(); + + assertEquals(petId, pet.getPetId()); + assertEquals(name, pet.getName()); + assertEquals(species, pet.getSpecies()); + assertEquals(age, pet.getAge()); + } +} diff --git a/image-processing/src/main/java/com/baeldung/imageprocessing/imagetobufferedimage/ImageToBufferedImage.java b/image-processing/src/main/java/com/baeldung/imageprocessing/imagetobufferedimage/ImageToBufferedImage.java index f3a4491adf..2be8c0b1a4 100644 --- a/image-processing/src/main/java/com/baeldung/imageprocessing/imagetobufferedimage/ImageToBufferedImage.java +++ b/image-processing/src/main/java/com/baeldung/imageprocessing/imagetobufferedimage/ImageToBufferedImage.java @@ -1,10 +1,7 @@ package com.baeldung.imageprocessing.imagetobufferedimage; -import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; public class ImageToBufferedImage { @@ -25,17 +22,7 @@ public class ImageToBufferedImage { if (image instanceof BufferedImage) { return (BufferedImage) image; } else { - throw new ClassCastException("Image type is not compatible with BufferedImage"); - } - } - - // Method 3: Using ImageIO Class - public BufferedImage convertUsingImageIO(String filePath) throws IOException { - try { - File file = new File(filePath); - return ImageIO.read(file); - } catch (Exception e) { - throw new IOException("Error reading image file: " + e.getMessage()); + throw new ClassCastException("Image type is not compatible with BufferedImage."); } } } diff --git a/image-processing/src/test/java/com/baeldung/image/resize/imagetobufferedimage/ImageToBufferedImageIntegrationTest.java b/image-processing/src/test/java/com/baeldung/image/resize/imagetobufferedimage/ImageToBufferedImageIntegrationTest.java index a5dd11de06..137c709d5f 100644 --- a/image-processing/src/test/java/com/baeldung/image/resize/imagetobufferedimage/ImageToBufferedImageIntegrationTest.java +++ b/image-processing/src/test/java/com/baeldung/image/resize/imagetobufferedimage/ImageToBufferedImageIntegrationTest.java @@ -50,20 +50,5 @@ public class ImageToBufferedImageIntegrationTest { Image image = new ImageIcon("src/main/resources/images/baeldung.png").getImage(); converter.convertUsingCasting(image); } - - @Test - public void whenConvertUsingImageIOWithValidFile_thenImageGeneratedWithoutError() throws IOException { - ImageToBufferedImage converter = new ImageToBufferedImage(); - BufferedImage bufferedImage = converter.convertUsingImageIO("src/main/resources/images/sampleImage.jpg"); - assertNotNull(bufferedImage); - assertEquals(image.getWidth(null), bufferedImage.getWidth()); - assertEquals(image.getHeight(null), bufferedImage.getHeight()); - } - - @Test(expected = IOException.class) - public void whenConvertUsingImageIOWithInvalidFile_thenImageGeneratedWithError() throws IOException { - ImageToBufferedImage converter = new ImageToBufferedImage(); - converter.convertUsingImageIO("invalid_file.jpg"); - } } diff --git a/kubernetes-modules/pom.xml b/kubernetes-modules/pom.xml index 986e15b541..caa2dd4f44 100644 --- a/kubernetes-modules/pom.xml +++ b/kubernetes-modules/pom.xml @@ -17,7 +17,7 @@ k8s-admission-controller kubernetes-spring k8s-java-heap-dump - k8s-operator + diff --git a/maven-modules/maven-reactor/pom.xml b/maven-modules/maven-reactor/pom.xml index debbcda803..cf4adac16e 100644 --- a/maven-modules/maven-reactor/pom.xml +++ b/maven-modules/maven-reactor/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-reactor 1.0-SNAPSHOT - maven-reactor pom + maven-reactor Sample multi-module project to explain maven reactor diff --git a/maven-modules/maven-repositories/pom.xml b/maven-modules/maven-repositories/pom.xml index c9c7ba9a8b..78da14f876 100644 --- a/maven-modules/maven-repositories/pom.xml +++ b/maven-modules/maven-repositories/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-repositories 1.0.0-SNAPSHOT - maven-repositories pom + maven-repositories com.baeldung diff --git a/maven-modules/maven-simple/parent-project/pom.xml b/maven-modules/maven-simple/parent-project/pom.xml index 2f28eff49f..3374ed133a 100644 --- a/maven-modules/maven-simple/parent-project/pom.xml +++ b/maven-modules/maven-simple/parent-project/pom.xml @@ -5,8 +5,8 @@ 4.0.0 parent-project 1.0-SNAPSHOT - parent-project pom + parent-project com.baeldung diff --git a/maven-modules/maven-simple/parent-project/webapp/pom.xml b/maven-modules/maven-simple/parent-project/webapp/pom.xml index d0596a4503..b119c1c4c1 100644 --- a/maven-modules/maven-simple/parent-project/webapp/pom.xml +++ b/maven-modules/maven-simple/parent-project/webapp/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 webapp - webapp war + webapp parent-project diff --git a/maven-modules/maven-simple/pom.xml b/maven-modules/maven-simple/pom.xml index fe59259758..155c32bee3 100644 --- a/maven-modules/maven-simple/pom.xml +++ b/maven-modules/maven-simple/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 maven-simple - maven-simple 1.0.0-SNAPSHOT pom + maven-simple com.baeldung diff --git a/maven-modules/maven-surefire-plugin/pom.xml b/maven-modules/maven-surefire-plugin/pom.xml index 840ffab077..ce2e380aae 100644 --- a/maven-modules/maven-surefire-plugin/pom.xml +++ b/maven-modules/maven-surefire-plugin/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-surefire-plugin 0.0.1-SNAPSHOT - maven-surefire-plugin jar + maven-surefire-plugin com.baeldung diff --git a/maven-modules/maven-war-plugin/pom.xml b/maven-modules/maven-war-plugin/pom.xml index 04188b8995..df3889e47c 100644 --- a/maven-modules/maven-war-plugin/pom.xml +++ b/maven-modules/maven-war-plugin/pom.xml @@ -6,8 +6,8 @@ com.baeldung maven-war-plugin 0.0.1-SNAPSHOT - maven-war-plugin war + maven-war-plugin diff --git a/maven-modules/multimodulemavenproject/pom.xml b/maven-modules/multimodulemavenproject/pom.xml index 5a6eea7cf4..b2dfe1afa7 100644 --- a/maven-modules/multimodulemavenproject/pom.xml +++ b/maven-modules/multimodulemavenproject/pom.xml @@ -6,8 +6,8 @@ com.baeldung.multimodulemavenproject multimodulemavenproject 1.0 - multimodulemavenproject pom + multimodulemavenproject - io.orkes.demo - event-driven-microservice - 0.1 - - event-driven-microservice - Demo Project for Orkes Conductor on Spring Boot - - - org.springframework.boot spring-boot-starter-web - io.orkes.conductor orkes-conductor-client ${conductor.client.version} - org.springdoc springdoc-openapi-starter-webmvc-ui ${springdoc-openapi-webmvc-ui.version} - org.projectlombok lombok true - org.springframework.boot spring-boot-starter-test diff --git a/microservices-modules/helidon/pom.xml b/microservices-modules/helidon/pom.xml index ca2cafb7d3..894867c6a7 100644 --- a/microservices-modules/helidon/pom.xml +++ b/microservices-modules/helidon/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.helidon helidon - helidon pom + helidon com.baeldung diff --git a/microservices-modules/micronaut/pom.xml b/microservices-modules/micronaut/pom.xml index 641b23d5e6..c1c669f107 100644 --- a/microservices-modules/micronaut/pom.xml +++ b/microservices-modules/micronaut/pom.xml @@ -6,8 +6,8 @@ com.baeldung.micronaut micronaut 0.1 - micronaut ${packaging} + micronaut com.baeldung diff --git a/microservices-modules/microprofile/pom.xml b/microservices-modules/microprofile/pom.xml index b2ce768748..54a4bd5c09 100644 --- a/microservices-modules/microprofile/pom.xml +++ b/microservices-modules/microprofile/pom.xml @@ -5,8 +5,8 @@ 4.0.0 microprofile 1.0-SNAPSHOT - microprofile war + microprofile com.baeldung diff --git a/microservices-modules/pom.xml b/microservices-modules/pom.xml index 0f0baac488..40279454a0 100644 --- a/microservices-modules/pom.xml +++ b/microservices-modules/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 microservices-modules - microservices-modules pom + microservices-modules com.baeldung diff --git a/microservices-modules/rest-express/pom.xml b/microservices-modules/rest-express/pom.xml index be1c142a94..50b8802342 100644 --- a/microservices-modules/rest-express/pom.xml +++ b/microservices-modules/rest-express/pom.xml @@ -5,8 +5,8 @@ 4.0.0 rest-express 1.0.0-SNAPSHOT - rest-express jar + rest-express A Basic, MongoDB-backed Service Suite https://github.com/RestExpress/RestExpress-Scaffold