Merge branch 'master' into master

This commit is contained in:
Loredana Crusoveanu 2024-04-27 14:05:55 +03:00 committed by GitHub
commit 2731096e4d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
162 changed files with 4745 additions and 504 deletions

View File

@ -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;
}

View File

@ -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;
}

View File

@ -13,4 +13,12 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
</dependencies>
</project>

View File

@ -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<Integer> expected = Arrays.stream(intArray).boxed().collect(Collectors.toList());
List<Integer> 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<Integer> expected = Arrays.stream(intArray).boxed().collect(Collectors.toList());
List<Integer> actual = new ArrayList<>();
for (int[] numbers : initialArray) {
List<Integer> 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<Arguments> 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
}
)
);
}
}

View File

@ -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<Integer> 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<Integer> 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<Arguments> 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<Arguments> 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)
);
}
}

View File

@ -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)

View File

@ -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)

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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)

View File

@ -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);
}
}
}

View File

@ -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;
}
}
}
}

View File

@ -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();
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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)

View File

@ -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)

View File

@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
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">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-lang-7</artifactId>
<packaging>jar</packaging>
<name>core-java-lang-7</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.junit-pioneer</groupId>
<artifactId>junit-pioneer</artifactId>
<version>${junit.pioneer.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>${testcontaienr.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${testcontaienr.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor -->
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
<path>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</path>
</annotationProcessorPaths>
<source>14</source>
<target>14</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<junit.pioneer.version>2.2.0</junit.pioneer.version>
<testcontaienr.version>1.19.3</testcontaienr.version>
<mapstruct.version>1.6.0.Beta1</mapstruct.version>
<jmh.version>1.37</jmh.version>
</properties>
</project>

View File

@ -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<MyClass> objects = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
objects.add(new MyClass("value" + i));
}
Set<Integer> hashCodes = new HashSet<>();
for (MyClass obj : objects) {
hashCodes.add(obj.hashCode());
}
assertEquals(objects.size(), hashCodes.size(), 10);
}
}

View File

@ -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;
}
}

View File

@ -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<BigDecimal> decimalList) {
Set<BigDecimal> decimalSet = new HashSet<>(decimalList);
assertThat(decimalSet).hasSameElementsAs(decimalList);
}
@ParameterizedTest
@MethodSource("decimalProvider")
void givenListOfDecimals_WhenAddingToSortedSet_ThenUsingCompareTo(List<BigDecimal> decimalList,
List<BigDecimal> expectedDecimalList) {
Set<BigDecimal> 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<Arguments> 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<Arguments> 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<Arguments> 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"))));
}
}

View File

@ -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<Arguments> 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<Arguments> 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")
);
}
}

View File

@ -6,7 +6,6 @@
- [Check if a String Contains a Number Value in Java](https://www.baeldung.com/java-string-number-presence)
- [Strings Maximum Length in Java](https://www.baeldung.com/java-strings-maximum-length)
- [Javas 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)

View File

@ -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)

View File

@ -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);
}
}

View File

@ -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<Character, Integer> 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<Character, Integer> charCount = new HashMap<>();
for (char c : str.toCharArray()) {
charCount.merge(c,
1,
Integer::sum);
}
assertEquals(3, charCount.get('a').intValue());
}
}

View File

@ -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 {

View File

@ -144,6 +144,7 @@
<module>core-java-lang-4</module>
<module>core-java-lang-5</module>
<module>core-java-lang-6</module>
<module>core-java-lang-7</module>
<module>core-java-lang-math</module>
<module>core-java-lang-math-2</module>
<module>core-java-lang-math-4</module>

View File

@ -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

View File

@ -0,0 +1,5 @@
# Ignore Gradle project-specific cache directory
.gradle
# Ignore Gradle build output directory
build

View File

@ -0,0 +1 @@
## Relevant Articles

View File

@ -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()
}

View File

@ -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" }

View File

@ -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

View File

@ -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" "$@"

View File

@ -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

View File

@ -0,0 +1,2 @@
rootProject.name = 'gradle-avro'

View File

@ -0,0 +1,19 @@
{
"type": "record",
"name": "User",
"namespace": "avro",
"fields": [
{
"name": "firstName",
"type": "string"
},
{
"name": "lastName",
"type": "string"
},
{
"name": "phoneNumber",
"type": "string"
}
]
}

View File

@ -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"
}
]
}

View File

@ -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());
}
}

View File

@ -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.");
}
}
}

View File

@ -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");
}
}

View File

@ -17,7 +17,7 @@
<module>k8s-admission-controller</module>
<module>kubernetes-spring</module>
<module>k8s-java-heap-dump</module>
<module>k8s-operator</module>
<!-- <module>k8s-operator</module>--> <!-- Migrated to heavy profile -->
</modules>
</project>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>maven-reactor</artifactId>
<version>1.0-SNAPSHOT</version>
<name>maven-reactor</name>
<packaging>pom</packaging>
<name>maven-reactor</name>
<description>Sample multi-module project to explain maven reactor</description>
<parent>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>maven-repositories</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>maven-repositories</name>
<packaging>pom</packaging>
<name>maven-repositories</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>parent-project</artifactId>
<version>1.0-SNAPSHOT</version>
<name>parent-project</name>
<packaging>pom</packaging>
<name>parent-project</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -4,8 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>webapp</artifactId>
<name>webapp</name>
<packaging>war</packaging>
<name>webapp</name>
<parent>
<artifactId>parent-project</artifactId>

View File

@ -4,9 +4,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>maven-simple</artifactId>
<name>maven-simple</name>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>maven-simple</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>maven-surefire-plugin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>maven-surefire-plugin</name>
<packaging>jar</packaging>
<name>maven-surefire-plugin</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -6,8 +6,8 @@
<groupId>com.baeldung</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>maven-war-plugin</name>
<packaging>war</packaging>
<name>maven-war-plugin</name>
<build>
<plugins>

View File

@ -6,8 +6,8 @@
<groupId>com.baeldung.multimodulemavenproject</groupId>
<artifactId>multimodulemavenproject</artifactId>
<version>1.0</version>
<name>multimodulemavenproject</name>
<packaging>pom</packaging>
<name>multimodulemavenproject</name>
<!--
No <parent> tag since we want the compiler plugin defined

View File

@ -6,11 +6,13 @@
<artifactId>business</artifactId>
<version>1.0-SNAPSHOT</version>
<name>business</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>resume-from</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.baeldung</groupId>

View File

@ -1,11 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>lib</artifactId>
<version>1.0-SNAPSHOT</version>
<name>lib</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>resume-from</artifactId>

View File

@ -6,8 +6,8 @@
<groupId>com.baeldung</groupId>
<artifactId>resume-from</artifactId>
<version>1.0-SNAPSHOT</version>
<name>resume-from</name>
<packaging>pom</packaging>
<name>resume-from</name>
<modules>
<module>business</module>

View File

@ -25,6 +25,7 @@
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>versions-maven-plugin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>versions-maven-plugin</name>
<packaging>pom</packaging>
<name>versions-maven-plugin</name>
<parent>
<artifactId>maven-modules</artifactId>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung.apache.camel</groupId>
<artifactId>apache-camel</artifactId>
<name>apache-camel</name>
<packaging>jar</packaging>
<name>apache-camel</name>
<url>http://maven.apache.org</url>
<parent>

View File

@ -4,8 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>messaging-modules</artifactId>
<name>messaging-modules</name>
<packaging>pom</packaging>
<name>messaging-modules</name>
<parent>
<artifactId>parent-boot-3</artifactId>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung.apache.camel</groupId>
<artifactId>spring-apache-camel</artifactId>
<name>spring-apache-camel</name>
<packaging>jar</packaging>
<name>spring-apache-camel</name>
<url>http://maven.apache.org</url>
<parent>

View File

@ -4,8 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-jms</artifactId>
<name>spring-jms</name>
<packaging>war</packaging>
<name>spring-jms</name>
<description>Introduction to Spring JMS</description>
<parent>

View File

@ -1,7 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.orkes.demo</groupId>
<artifactId>event-driven-microservice</artifactId>
<version>0.1</version>
<name>event-driven-microservice</name>
<description>Demo Project for Orkes Conductor on Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
@ -10,39 +16,26 @@
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>io.orkes.demo</groupId>
<artifactId>event-driven-microservice</artifactId>
<version>0.1</version>
<name>event-driven-microservice</name>
<description>Demo Project for Orkes Conductor on Spring Boot</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.orkes.conductor</groupId>
<artifactId>orkes-conductor-client</artifactId>
<version>${conductor.client.version}</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>${springdoc-openapi-webmvc-ui.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.helidon</groupId>
<artifactId>helidon</artifactId>
<name>helidon</name>
<packaging>pom</packaging>
<name>helidon</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -6,8 +6,8 @@
<groupId>com.baeldung.micronaut</groupId>
<artifactId>micronaut</artifactId>
<version>0.1</version>
<name>micronaut</name>
<packaging>${packaging}</packaging>
<name>micronaut</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>microprofile</artifactId>
<version>1.0-SNAPSHOT</version>
<name>microprofile</name>
<packaging>war</packaging>
<name>microprofile</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -4,8 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>microservices-modules</artifactId>
<name>microservices-modules</name>
<packaging>pom</packaging>
<name>microservices-modules</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>rest-express</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>rest-express</name>
<packaging>jar</packaging>
<name>rest-express</name>
<description>A Basic, MongoDB-backed Service Suite</description>
<url>https://github.com/RestExpress/RestExpress-Scaffold</url>
<!--

View File

@ -6,8 +6,8 @@
<groupId>com.mycompany</groupId>
<artifactId>muleesb</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>muleesb</name>
<packaging>mule</packaging>
<name>muleesb</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -22,7 +22,6 @@
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
</dependency>
</dependencies>

View File

@ -7,11 +7,9 @@ import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.jdbi.dao.CarMakerDao;
import com.baeldung.boot.jdbi.dao.CarModelDao;
@ -21,10 +19,9 @@ import com.baeldung.boot.jdbi.service.CarMakerService;
import lombok.extern.slf4j.Slf4j;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringBootJdbiApplication.class, JdbiConfiguration.class})
@Slf4j
public class SpringBootJdbiApplicationIntegrationTest {
class SpringBootJdbiApplicationIntegrationTest {
@Autowired
@ -37,7 +34,7 @@ public class SpringBootJdbiApplicationIntegrationTest {
private CarMakerService carMakerService;
@Test
public void givenNewCarMaker_whenInsertNewCarMaker_thenSuccess() {
void givenNewCarMaker_whenInsertNewCarMaker_thenSuccess() {
assertNotNull(carMakerDao);
@ -51,7 +48,7 @@ public class SpringBootJdbiApplicationIntegrationTest {
}
@Test
public void givenNewCarMakers_whenInsertNewCarMakers_thenSuccess() {
void givenNewCarMakers_whenInsertNewCarMakers_thenSuccess() {
assertNotNull(carMakerDao);
@ -74,7 +71,7 @@ public class SpringBootJdbiApplicationIntegrationTest {
@Test
public void givenExistingCarMaker_whenFindById_thenReturnExistingCarMaker() {
void givenExistingCarMaker_whenFindById_thenReturnExistingCarMaker() {
CarMaker maker = carMakerDao.findById(1L);
assertThat(maker).isNotNull();
@ -83,7 +80,7 @@ public class SpringBootJdbiApplicationIntegrationTest {
}
@Test
public void givenExistingCarMaker_whenBulkInsertFails_thenRollback() {
void givenExistingCarMaker_whenBulkInsertFails_thenRollback() {
CarMaker maker = carMakerDao.findById(1L);
CarModel m1 = CarModel.builder()

View File

@ -4,23 +4,20 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringOraclePoolingApplication.class})
@ActiveProfiles({"oracle-pooling-basic", "c3p0"})
public class SpringOraclePoolingApplicationC3P0LiveTest {
class SpringOraclePoolingApplicationC3P0LiveTest {
@Autowired
private DataSource dataSource;
@Test
public void givenC3p0Configuration_thenBuildsComboPooledDataSource() {
void givenC3p0Configuration_thenBuildsComboPooledDataSource() {
assertTrue(dataSource instanceof com.mchange.v2.c3p0.ComboPooledDataSource);
}

View File

@ -4,23 +4,20 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringOraclePoolingApplication.class})
@ActiveProfiles("oracle-pooling-basic")
public class SpringOraclePoolingApplicationHikariCPLiveTest {
class SpringOraclePoolingApplicationHikariCPLiveTest {
@Autowired
private DataSource dataSource;
@Test
public void givenHikariCPConfiguration_thenBuildsHikariCP() {
void givenHikariCPConfiguration_thenBuildsHikariCP() {
assertTrue(dataSource instanceof com.zaxxer.hikari.HikariDataSource);
}

View File

@ -4,23 +4,20 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringOraclePoolingApplication.class})
@ActiveProfiles({"oracle-pooling-basic", "oracle"})
public class SpringOraclePoolingApplicationOracleLiveTest {
class SpringOraclePoolingApplicationOracleLiveTest {
@Autowired
private DataSource dataSource;
@Test
public void givenOracleConfiguration_thenBuildsOracleDataSource() {
void givenOracleConfiguration_thenBuildsOracleDataSource() {
assertTrue(dataSource instanceof oracle.jdbc.pool.OracleDataSource);
}

View File

@ -4,15 +4,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringOraclePoolingApplication.class})
@ActiveProfiles({"oracle-pooling-basic"})
@TestPropertySource(properties = "spring.datasource.type=oracle.ucp.jdbc.PoolDataSource")

View File

@ -1,13 +1,8 @@
package com.baeldung.springboothsqldb.application.tests;
import com.baeldung.springboothsqldb.application.entities.Customer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.nio.charset.Charset;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
@ -17,23 +12,27 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
import com.baeldung.springboothsqldb.application.entities.Customer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
@SpringBootTest
@AutoConfigureMockMvc
public class CustomerControllerIntegrationTest {
class CustomerControllerIntegrationTest {
private static MediaType MEDIA_TYPE_JSON;
@Autowired
private MockMvc mockMvc;
@Before
public void setUpJsonMediaType() {
@BeforeEach
void setUpJsonMediaType() {
MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype());
}
@Test
public void whenPostHttpRequesttoCustomers_thenStatusOK() throws Exception {
void whenPostHttpRequesttoCustomers_thenStatusOK() throws Exception {
Customer customer = new Customer("John", "john@domain.com");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
@ -50,7 +49,7 @@ public class CustomerControllerIntegrationTest {
}
@Test
public void whenGetHttpRequesttoCustomers_thenStatusOK() throws Exception {
void whenGetHttpRequesttoCustomers_thenStatusOK() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/customers"))

View File

@ -1,20 +1,17 @@
package com.baeldung.states;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import jakarta.persistence.EntityManagerFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(SpringRunner.class)
@SpringBootTest
class UserEntityIntegrationTest {
@Autowired

View File

@ -1,27 +1,25 @@
package com.baeldung.tomcatconnectionpool.test.application;
import static org.assertj.core.api.Assertions.assertThat;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.tomcatconnectionpool.application.SpringBootConsoleApplication;
import static org.assertj.core.api.Assertions.*;
import org.springframework.boot.test.context.SpringBootTest;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringBootConsoleApplication.class})
@TestPropertySource(properties = "spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource")
public class SpringBootTomcatConnectionPoolIntegrationTest {
class SpringBootTomcatConnectionPoolIntegrationTest {
@Autowired
private DataSource dataSource;
@Test
public void givenTomcatConnectionPoolInstance_whenCheckedPoolClassName_thenCorrect() {
void givenTomcatConnectionPoolInstance_whenCheckedPoolClassName_thenCorrect() {
assertThat(dataSource.getClass().getName()).isEqualTo("org.apache.tomcat.jdbc.pool.DataSource");
}
}

View File

@ -8,5 +8,5 @@
- [Differences Between Spring Data JPA findFirst() and findTop()](https://www.baeldung.com/spring-data-jpa-findfirst-vs-findtop)
- [Difference Between findBy and findAllBy in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-find-by-vs-find-all-by)
- [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures)
- [Generate Database Schema with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-generate-db-schema)
- More articles: [[<-- prev]](../spring-data-jpa-repo)

View File

@ -58,10 +58,6 @@
<version>${querydsl.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-ant</artifactId>
</dependency>
</dependencies>
<build>

View File

@ -9,5 +9,4 @@ This module contains articles about Spring Data JPA.
- [Difference Between findBy and findOneBy in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-findby-vs-findoneby)
- [How to Get Last Record in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-last-record)
- [Refresh and Fetch an Entity After Save in JPA](https://www.baeldung.com/spring-data-jpa-refresh-fetch-entity-after-save)
- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting)
- More articles: [[<-- prev]](../spring-data-jpa-repo-2)

View File

@ -32,11 +32,6 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<properties>
<start-class>com.baeldung.spring.data.jpa.naturalid.Application</start-class>

View File

@ -3,7 +3,6 @@
This module contains articles about repositories in Spring Data JPA
### Relevant Articles:
- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
- [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries)
- [Spring Data CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save)
- [Spring Data JPA Adding a Method in All Repositories](https://www.baeldung.com/spring-data-jpa-method-in-all-repositories)

View File

@ -1,7 +0,0 @@
package com.baeldung.simple.service;
import com.baeldung.simple.entity.Foo;
public interface IFooService {
Foo create(Foo foo);
}

View File

@ -8,6 +8,7 @@ This module contains articles about Spring Data JPA that are also part of an Ebo
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.
### Relevant Articles
- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
- [Customizing the Result of JPA Queries with Aggregation Functions](https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions)
- [CrudRepository, JpaRepository, and PagingAndSortingRepository in Spring Data](https://www.baeldung.com/spring-data-repositories)
- [New CRUD Repository Interfaces in Spring Data 3](https://www.baeldung.com/spring-data-3-crud-repository-interfaces)
@ -15,3 +16,5 @@ Since this is a module tied to an e-book, it should **not** be moved or used to
- [Spring Data JPA @Query](https://www.baeldung.com/spring-data-jpa-query)
- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections)
- [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation)
- [Generate Database Schema with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-generate-db-schema)
- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting)

View File

@ -43,11 +43,21 @@
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>${jakarta.xml.bind.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-ant</artifactId>
<version>${hibernate.version}</version>
</dependency>
</dependencies>
<properties>

Some files were not shown because too many files have changed in this diff Show More