Merge branch 'eugenp:master' into master

This commit is contained in:
Wynn Teo 2024-04-15 08:12:34 +08:00 committed by GitHub
commit 2fcd34c0a9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
224 changed files with 3946 additions and 594 deletions

View File

@ -1,23 +1,22 @@
package com.baeldung.algorithms.mergeintervals;
import static java.lang.Integer.max;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class MergeOverlappingIntervals {
public List<Interval> doMerge(List<Interval> intervals) {
// Sort the intervals based on start time
intervals.sort((one, two) -> one.start - two.start);
// Create somewhere to put the merged list, start it off with the earliest starting interval
intervals.sort(Comparator.comparingInt(interval -> interval.start));
ArrayList<Interval> merged = new ArrayList<>();
merged.add(intervals.get(0));
// Loop over each interval and merge if start time is before the end time of the
// previous interval
intervals.forEach(interval -> {
if (merged.get(merged.size() - 1).end > interval.start) {
merged.get(merged.size() - 1).setEnd(interval.end);
Interval lastMerged = merged.get(merged.size() - 1);
if (interval.start <= lastMerged.end){
lastMerged.setEnd(max(interval.end, lastMerged.end));
} else {
merged.add(interval);
}
@ -25,5 +24,4 @@ public class MergeOverlappingIntervals {
return merged;
}
}
}

View File

@ -1,30 +1,38 @@
package com.baeldung.algorithms.mergeintervals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class MergeIntervalsUnitTest {
private ArrayList<Interval> intervals = new ArrayList<>(Arrays.asList(
new Interval(2, 5),
new Interval(13, 20),
new Interval(11, 15),
new Interval(1, 3)
private List<Interval> intervals = new ArrayList<>(Arrays.asList(
// @formatter:off
new Interval(3, 5),
new Interval(13, 20),
new Interval(11, 15),
new Interval(15, 16),
new Interval(1, 3),
new Interval(4, 5),
new Interval(16, 17)
// @formatter:on
));
private ArrayList<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
new Interval(1, 5),
new Interval(11, 20)
private List<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
// @formatter:off
new Interval(1, 5),
new Interval(11, 20)
// @formatter:on
));
@Test
void givenIntervals_whenMerging_thenReturnMergedIntervals() {
MergeOverlappingIntervals merger = new MergeOverlappingIntervals();
ArrayList<Interval> result = (ArrayList<Interval>) merger.doMerge(intervals);
assertArrayEquals(intervalsMerged.toArray(), result.toArray());
List<Interval> result = merger.doMerge(intervals);
assertEquals(intervalsMerged, result);
}
}
}

View File

@ -40,6 +40,16 @@
<artifactId>fastexcel-reader</artifactId>
<version>${fastexcel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
<build>
@ -64,6 +74,7 @@
<jexcel.version>1.0.9</jexcel.version>
<fastexcel.version>0.17.0</fastexcel.version>
<maven.resources.plugin.version>3.3.1</maven.resources.plugin.version>
<log4j.version>2.23.1</log4j.version>
</properties>
</project>

View File

@ -71,7 +71,7 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-core.version}</version>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -112,7 +112,6 @@
<feign-core.version>11.2</feign-core.version>
<guice.version>5.1.0</guice.version>
<system-stubs-junit4.version>2.0.2</system-stubs-junit4.version>
<mockito-core.version>4.1.0</mockito-core.version>
<assertj-core.version>3.19.0</assertj-core.version>
<junit-jupiter.version>5.8.1</junit-jupiter.version>
</properties>

View File

@ -0,0 +1,4 @@
package com.baeldung;
public class Unrelated {
}

View File

@ -1,7 +1,7 @@
package com.baeldung;
import static org.junit.Assert.assertTrue;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Set;
@ -14,22 +14,22 @@ public class OuterUnitTest {
@Test
public void whenGetNestHostFromOuter_thenGetNestHost() {
is(Outer.class.getNestHost().getName()).equals(NEST_HOST_NAME);
assertEquals(NEST_HOST_NAME, Outer.class.getNestHost().getName());
}
@Test
public void whenGetNestHostFromInner_thenGetNestHost() {
is(Outer.Inner.class.getNestHost().getName()).equals(NEST_HOST_NAME);
assertEquals(NEST_HOST_NAME, Outer.Inner.class.getNestHost().getName());
}
@Test
public void whenCheckNestmatesForNestedClasses_thenGetTrue() {
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(true);
assertTrue(Outer.Inner.class.isNestmateOf(Outer.class));
}
@Test
public void whenCheckNestmatesForUnrelatedClasses_thenGetFalse() {
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(false);
assertFalse(Outer.Inner.class.isNestmateOf(Unrelated.class));
}
@Test

View File

@ -1,3 +1,4 @@
## Relevant Articles
- [Deprecate Finalization in Java 18](https://www.baeldung.com/java-18-deprecate-finalization)
- [Simple Web Server in Java 18](https://www.baeldung.com/simple-web-server-java-18)
- [Internet Address Resolution SPI in Java](https://www.baeldung.com/java-service-provider-interface)

View File

@ -3,3 +3,4 @@
- [Find the Equilibrium Indexes of an Array in Java](https://www.baeldung.com/java-equilibrium-index-array)
- [Moves Zeros to the End of an Array in Java](https://www.baeldung.com/java-array-sort-move-zeros-end)
- [Finding the Majority Element of an Array in Java](https://www.baeldung.com/java-array-find-majority-element)
- [Set Matrix Elements to Zero in Java](https://www.baeldung.com/java-set-matrix-elements-to-zero)

View File

@ -0,0 +1,147 @@
package com.baeldung.matrixtozero;
import java.util.*;
public class SetMatrixToZero{
static void setZeroesByNaiveApproach(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
int [][] result = new int[row][col];
for(int i = 0; i<row; i++){
for(int j = 0; j < col; j++){
result[i][j] = matrix[i][j];
}
}
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(matrix[i][j] == 0){
for(int k = 0; k < col; k++){
result[i][k] = 0;
}
for(int k = 0; k < row; k++){
result[k][j] = 0;
}
}
}
}
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
matrix[i][j] = result[i][j];
}
}
}
static void setZeroesByTimeOptimizedApproach(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
Set<Integer> rowSet = new HashSet<>();
Set<Integer> colSet = new HashSet<>();
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if (matrix[i][j] == 0){
rowSet.add(i);
colSet.add(j);
}
}
}
for(int row: rowSet){
for(int j = 0; j < cols; j++){
matrix[row][j] = 0;
}
}
for(int col: colSet) {
for(int i = 0; i < rows; i++){
matrix[i][col] = 0;
}
}
}
static boolean hasZeroInFirstRow(int[][] matrix, int cols) {
for (int j = 0; j < cols; j++) {
if (matrix[0][j] == 0) {
return true;
}
}
return false;
}
static boolean hasZeroInFirstCol(int[][] matrix, int rows) {
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) {
return true;
}
}
return false;
}
static void markZeroesInMatrix(int[][] matrix, int rows, int cols) {
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
}
static void setZeroesInRows(int[][] matrix, int rows, int cols) {
for (int i = 1; i < rows; i++) {
if (matrix[i][0] == 0) {
for (int j = 1; j < cols; j++) {
matrix[i][j] = 0;
}
}
}
}
static void setZeroesInCols(int[][] matrix, int rows, int cols) {
for (int j = 1; j < cols; j++) {
if (matrix[0][j] == 0) {
for (int i = 1; i < rows; i++) {
matrix[i][j] = 0;
}
}
}
}
static void setZeroesInFirstRow(int[][] matrix, int cols) {
for (int j = 0; j < cols; j++) {
matrix[0][j] = 0;
}
}
static void setZeroesInFirstCol(int[][] matrix, int rows) {
for (int i = 0; i < rows; i++) {
matrix[i][0] = 0;
}
}
static void setZeroesByOptimalApproach(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
boolean firstRowZero = hasZeroInFirstRow(matrix, cols);
boolean firstColZero = hasZeroInFirstCol(matrix, rows);
markZeroesInMatrix(matrix, rows, cols);
setZeroesInRows(matrix, rows, cols);
setZeroesInCols(matrix, rows, cols);
if (firstRowZero) {
setZeroesInFirstRow(matrix, cols);
}
if (firstColZero) {
setZeroesInFirstCol(matrix, rows);
}
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.matrixtozero;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
public class SetMatrixToZeroUnitTest{
@Test
void givenMatrix_whenUsingSetZeroesByNaiveApproach_thenSetZeroes() {
int[][] matrix = {
{1, 2, 3},
{4, 0, 6},
{7, 8, 9}
};
int[][] expected = {
{1, 0, 3},
{0, 0, 0},
{7, 0, 9}
};
SetMatrixToZero.setZeroesByNaiveApproach(matrix);
assertArrayEquals(expected, matrix);
}
@Test
void givenMatrix_whenUsingSetZeroesByTimeOptimizedApproach_thenSetZeroes() {
int[][] matrix = {
{1, 2, 3},
{4, 0, 6},
{7, 8, 9}
};
int[][] expected = {
{1, 0, 3},
{0, 0, 0},
{7, 0, 9}
};
SetMatrixToZero.setZeroesByTimeOptimizedApproach(matrix);
assertArrayEquals(expected, matrix);
}
@Test
void givenMatrix_whenUsingSetZeroesByOptimalApproach_thenSetZeroes() {
int[][] matrix = {
{1, 2, 3},
{4, 0, 6},
{7, 8, 9}
};
int[][] expected = {
{1, 0, 3},
{0, 0, 0},
{7, 0, 9}
};
SetMatrixToZero.setZeroesByOptimalApproach(matrix);
assertArrayEquals(expected, matrix);
}
}

View File

@ -13,4 +13,5 @@
- [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)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)

View File

@ -3,3 +3,5 @@
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-5)

View File

@ -0,0 +1,64 @@
package com.baeldung.iteratorvsforeach;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
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;
class IteratorVsForeachUnitTest {
private static Stream<Arguments> listProvider() {
return Stream.of(Arguments.of(List.of("String1", "String2", "unwanted"), List.of("String1", "String2")));
}
@Test
public void givenEmptyCollection_whenUsingForEach_thenNoElementsAreIterated() {
List<String> names = Collections.emptyList();
StringBuilder stringBuilder = new StringBuilder();
names.forEach(stringBuilder::append);
assertEquals("", stringBuilder.toString());
}
@ParameterizedTest
@MethodSource("listProvider")
public void givenCollectionWithElements_whenRemovingElementDuringForEachIteration_thenElementIsRemoved(List<String> input, List<String> expected) {
List<String> mutableList = new ArrayList<>(input);
// Separate collection for items to be removed
List<String> toRemove = new ArrayList<>();
// Using forEach to identify items to remove
input.forEach(item -> {
if (item.equals("unwanted")) {
toRemove.add(item);
}
});
// Removing the identified items from the original list
mutableList.removeAll(toRemove);
assertIterableEquals(expected, mutableList);
}
@ParameterizedTest
@MethodSource("listProvider")
public void givenCollectionWithElements_whenRemovingElementDuringIteratorIteration_thenElementIsRemoved(List<String> input, List<String> expected) {
List<String> mutableList = new ArrayList<>(input);
Iterator<String> it = mutableList.iterator();
while (it.hasNext()) {
String item = it.next();
if (item.equals("unwanted")) {
it.remove(); // Safely remove item
}
}
assertIterableEquals(expected, mutableList);
}
}

View File

@ -11,5 +11,6 @@ This module contains articles about core Java input and output (IO)
- [Read and Write Files in Java Using Separate Threads](https://www.baeldung.com/java-read-write-files-different-threads)
- [Convert an OutputStream to a Byte Array in Java](https://www.baeldung.com/java-outputstream-byte-array)
- [Reading a .gz File Line by Line Using GZIPInputStream](https://www.baeldung.com/java-gzipinputstream-read-gz-file-line-by-line)
- [Opening HTML File Using Java](https://www.baeldung.com/java-open-html-file)
- [[<-- Prev]](/core-java-modules/core-java-io-4)

View File

@ -0,0 +1,113 @@
package com.baeldung.printwriterwritevsprint;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
public class WriteVsPrintUnitTest {
Object outputFromPrintWriter;
Object outputFromPrintWriter() {
try (BufferedReader br = new BufferedReader(new FileReader("output.txt"))){
outputFromPrintWriter = br.readLine();
} catch (IOException e){
e.printStackTrace();
Assertions.fail();
}
return outputFromPrintWriter;
}
@Test
void whenUsingWriteInt_thenASCIICharacterIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.write(48);
printWriter.close();
assertEquals("0", outputFromPrintWriter());
}
@Test
void whenUsingWriteCharArrayFromOffset_thenCharArrayIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.write(new char[]{'A','/','&','4','E'}, 1, 4 );
printWriter.close();
assertEquals("/&4E", outputFromPrintWriter());
}
@Test
void whenUsingWriteStringFromOffset_thenLengthOfStringIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.write("StringExample", 6, 7 );
printWriter.close();
assertEquals("Example", outputFromPrintWriter());
}
@Test
void whenUsingPrintBoolean_thenStringValueIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.print(true);
printWriter.close();
assertEquals("true", outputFromPrintWriter());
}
@Test
void whenUsingPrintChar_thenCharIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.print('A');
printWriter.close();
assertEquals("A", outputFromPrintWriter());
}
@Test
void whenUsingPrintInt_thenValueOfIntIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.print(420);
printWriter.close();
assertEquals("420", outputFromPrintWriter());
}
@Test
void whenUsingPrintString_thenStringIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.print("RandomString");
printWriter.close();
assertEquals("RandomString", outputFromPrintWriter());
}
@Test
void whenUsingPrintObject_thenObjectToStringIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
Map example = new HashMap();
printWriter.print(example);
printWriter.close();
assertEquals(example.toString(), outputFromPrintWriter());
}
}

View File

@ -20,28 +20,6 @@
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<!-- this is all you need to write tests with JUnit Jupiter -->
<dependency>
<groupId>org.junit.jupiter</groupId>
@ -63,18 +41,6 @@
<version>${junit-jupiter-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>

View File

@ -260,7 +260,6 @@
<!-- util -->
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<mockito.version>4.6.1</mockito.version>
<!-- maven plugins -->
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>

View File

@ -10,3 +10,4 @@ This module contains articles about Object Oriented Programming (OOP) in Java
- [Law of Demeter in Java](https://www.baeldung.com/java-demeter-law)
- [Java Interface Naming Conventions](https://www.baeldung.com/java-interface-naming-conventions)
- [Difference Between Information Hiding and Encapsulation](https://www.baeldung.com/java-information-hiding-vs-encapsulation)
- [Statements Before super() in Java](https://www.baeldung.com/java-statements-before-super-constructor)

View File

@ -0,0 +1,44 @@
package com.baeldung.printnullvalues;
import java.util.Objects;
import java.util.Optional;
public class Employee {
private String name;
private int age;
private String department;
public Employee(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}
public String toStringUsingNullCheck() {
return "Name: " + (name != null ? name : "Unknown") +
", Age: " + age +
", Department: " + (department != null ? department : "Unknown");
}
public String toStringUsingOptional() {
return "Name: " + Optional.ofNullable(name).orElse("Unknown") +
", Age: " + age +
", Department: " + Optional.ofNullable(department).orElse("Unknown");
}
private String getDefaultIfNull(String value, String defaultValue) {
return value != null ? value : defaultValue;
}
public String toStringUsingCustomHelper() {
return "Name: " + getDefaultIfNull(name, "Unknown") +
", Age: " + age +
", Department: " + getDefaultIfNull(department, "Unknown");
}
public String toStringUsingObjects() {
return "Name: " + Objects.toString(name, "Unknown") +
", Age: " + age +
", Department: " + Objects.toString(department, "Unknown");
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.printnullvalues;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PrintingNullValuesUnitTest {
Employee employee = new Employee(null, 30, null);
String expected = "Name: Unknown, Age: 30, Department: Unknown";
@Test
public void givenNullValues_whenToStringUsingNullCheck_thenCorrectStringReturned() {
assertEquals(expected, employee.toStringUsingNullCheck());
}
@Test
public void givenNullValues_whenToStringUsingOptional_thenCorrectStringReturned() {
assertEquals(expected, employee.toStringUsingOptional());
}
@Test
public void givenNullValues_whenToStringUsingCustomHelper_thenCorrectStringReturned() {
assertEquals(expected, employee.toStringUsingCustomHelper());
}
@Test
public void givenNullValues_whenToStringUsingObjects_thenCorrectStringReturned() {
assertEquals(expected, employee.toStringUsingObjects());
}
}

View File

@ -0,0 +1,2 @@
## Relevant Articles:
- [[<-- Prev]](/core-java-modules/core-java-networking-4)

View File

@ -0,0 +1,59 @@
<?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-networking-5</artifactId>
<packaging>jar</packaging>
<name>core-java-networking-5</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>${commons-validator.version}</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${javax.ws.rs-api.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>${jersey-common.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-web.version}</version>
</dependency>
</dependencies>
<properties>
<commons-validator.version>1.7</commons-validator.version>
<jsoup.version>1.17.2</jsoup.version>
<httpclient.version>4.5.2</httpclient.version>
<javax.ws.rs-api.version>2.1.1</javax.ws.rs-api.version>
<jersey-common.version>2.22.2</jersey-common.version>
<spring-web.version>6.0.6</spring-web.version>
</properties>
</project>

View File

@ -0,0 +1,57 @@
package com.baeldung.redirectedurl;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import static org.junit.Assert.assertEquals;
public class RedirectedUrlUnitTest {
String canonicalUrl = "http://www.baeldung.com/";
String expectedRedirectedUrl = "https://www.baeldung.com/";
@Test
public void givenOriginalUrl_whenFindRedirectUrlUsingHttpURLConnection_thenCorrectRedirectedUrlReturned() throws IOException {
URL url = new URL(canonicalUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
int status = connection.getResponseCode();
String redirectedUrl = null;
if (status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_MOVED_TEMP) {
redirectedUrl = connection.getHeaderField("Location");
}
connection.disconnect();
assertEquals(expectedRedirectedUrl, redirectedUrl);
}
@Test
public void givenOriginalUrl_whenFindRedirectUrlUsingHttpClient_thenCorrectRedirectedUrlReturned() throws IOException {
RequestConfig config = RequestConfig.custom()
.setRedirectsEnabled(false)
.build();
try (CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(config)
.build()) {
HttpGet httpGet = new HttpGet(canonicalUrl);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
int statusCode = response.getStatusLine().getStatusCode();
String redirectedUrl = null;
if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
org.apache.http.Header[] headers = response.getHeaders("Location");
if (headers.length > 0) {
redirectedUrl = headers[0].getValue();
}
}
assertEquals(expectedRedirectedUrl, redirectedUrl);
}
}
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.complexnumbers;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public record ComplexNumber(double real, double imaginary) {
public static ComplexNumber fromString(String complexNumberStr) {
Pattern pattern = Pattern.compile("(-?\\d*\\.?\\d+)?(?:([+-]?\\d*\\.?\\d+)i)?");
Matcher matcher = pattern.matcher(complexNumberStr.replaceAll("\\s", ""));
if (matcher.matches()) {
// Extract real and imaginary parts
String realPartStr = matcher.group(1);
String imaginaryPartStr = matcher.group(2);
// Parse real part (if present)
double real = (realPartStr != null) ? Double.parseDouble(realPartStr) : 0;
// Parse imaginary part (if present)
double imaginary = (imaginaryPartStr != null) ? Double.parseDouble(imaginaryPartStr) : 0;
return new ComplexNumber(real, imaginary);
} else {
throw new IllegalArgumentException("Invalid complex number format(" + complexNumberStr + "), supported format is `a+bi`");
}
}
public String toString() {
return real + "+" + imaginary + "i";
}
public ComplexNumber add(ComplexNumber that) {
return new ComplexNumber(real + that.real, imaginary + that.imaginary);
}
public ComplexNumber multiply(ComplexNumber that) {
double newReal = this.real * that.real - this.imaginary * that.imaginary;
double newImaginary = this.real * that.imaginary + this.imaginary * that.real;
return new ComplexNumber(newReal, newImaginary);
}
public ComplexNumber subtract(ComplexNumber that) {
return new ComplexNumber(real - that.real, imaginary - that.imaginary);
}
public ComplexNumber divide(ComplexNumber that) {
if(that.real == 0 && that.imaginary == 0 ){
throw new ArithmeticException("Division by 0 is not allowed!");
}
double c2d2 = Math.pow(that.real, 2) + Math.pow(that.imaginary, 2);
double newReal = (this.real * that.real + this.imaginary * that.imaginary) / c2d2;
double newImaginary = (this.imaginary * that.real - this.real * that.imaginary) / c2d2;
return new ComplexNumber(newReal, newImaginary);
}
}

View File

@ -0,0 +1,103 @@
package com.baeldung.complexnumbers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class ComplexNumberOperationsUnitTest {
@ParameterizedTest(name = "Multiplying {0} and {1}")
@CsvSource({
"3+2i, 1+7i, -11+23i",
"2, 4, 8",
"2, 4i, 8i",
"1+1i, 1+1i, 0+2i",
" 3+2i, 1 + 7i, -11 + 23i ",
"0+5i, 3+0i, 0+15i",
"0+0i, -2+0i, 0+0i",
"-3+2i, 1-7i, 11+23i",
"2+4i, 0, 0"
})
public void givenTwoComplexNumbers_multiplyAndGetResult(String complexStr1, String complexStr2, String expectedStr) {
ComplexNumber complex1 = ComplexNumber.fromString(complexStr1);
ComplexNumber complex2 = ComplexNumber.fromString(complexStr2);
ComplexNumber expected = ComplexNumber.fromString(expectedStr);
ComplexNumber product = complex1.multiply(complex2);
Assertions.assertTrue(isSame(product, expected));
}
@ParameterizedTest(name = "Adding {0} and {1}")
@CsvSource({
"3+2i, 1+7i, 4+9i",
"2, 4, 6",
"2, 4i, 2+4i",
"1+1i, 1+1i, 2+2i",
" 3+2i, 1 + 7i, 4 + 9i ",
"0+5i, 3+0i, 3+5i",
"0+0i, -2+0i, -2+0i",
"-3+2i, 1-7i, -2-5i",
"2+4i, 0, 2+4i"
})
public void givenTwoComplexNumbers_addThemAndGetResult(String complexStr1, String complexStr2, String expectedStr) {
ComplexNumber complex1 = ComplexNumber.fromString(complexStr1);
ComplexNumber complex2 = ComplexNumber.fromString(complexStr2);
ComplexNumber expected = ComplexNumber.fromString(expectedStr);
ComplexNumber sum = complex1.add(complex2);
Assertions.assertTrue(isSame(sum, expected));
}
@ParameterizedTest(name = "Subtracting {0} and {1}")
@CsvSource({
"3+2i, 1+7i, 2-5i",
"2, 4, -2",
"2, 4i, 2-4i",
"1+1i, 1+1i, 0",
" 3+ 2i, 1+ 7i, 2-5i",
"0+5i, 3+0i, -3+5i",
"0+0i, -2+0i, 2+0i",
"-3+2i, 1-7i, -4+9i",
"2+4i, 0, 2+4i"
})
public void givenTwoComplexNumbers_subtractAndGetResult(String complexStr1, String complexStr2, String expectedStr) {
ComplexNumber complex1 = ComplexNumber.fromString(complexStr1);
ComplexNumber complex2 = ComplexNumber.fromString(complexStr2);
ComplexNumber expected = ComplexNumber.fromString(expectedStr);
ComplexNumber sum = complex1.subtract(complex2);
Assertions.assertTrue(isSame(sum, expected));
}
@ParameterizedTest(name = "Dividing {0} and {1}")
@CsvSource({
"3+2i, 1+7i, 0.34-0.38i",
"2, 4, 0.5",
"2, 4i, 0-0.5i",
"1+1i, 1+1i, 1",
"3 + 2i, 1 + 7i, 0.34-0.38i",
"0+5i, 3+0i, 0+1.6666666666666667i",
"0+0i, -2+0i, 0+0i",
"-3+2i, 1-7i, -0.34-0.38i",
"2+4i, 1, 2+4i"
})
public void givenTwoComplexNumbers_divideThemAndGetResult(String complexStr1, String complexStr2, String expectedStr) {
ComplexNumber complex1 = ComplexNumber.fromString(complexStr1);
ComplexNumber complex2 = ComplexNumber.fromString(complexStr2);
ComplexNumber expected = ComplexNumber.fromString(expectedStr);
ComplexNumber sum = complex1.divide(complex2);
Assertions.assertTrue(isSame(sum, expected));
}
@Test
public void givenAComplexNumberAsZero_handleDivideByZeroScenario() {
ComplexNumber complex1 = new ComplexNumber(1, 1);
ComplexNumber zero = new ComplexNumber(0, 0);
Exception exception = Assertions.assertThrows(ArithmeticException.class, () -> {
complex1.divide(zero);
});
Assertions.assertEquals(exception.getMessage(), "Division by 0 is not allowed!");
}
public boolean isSame(ComplexNumber result, ComplexNumber expected) {
return result.real() == expected.real() && result.imaginary() == expected.imaginary();
}
}

View File

@ -5,73 +5,70 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SymmetricSubstringMaxLengthUnitTest {
String input = "<><??>>";
String input = "abba";
int expected = 4;
@Test
public void givenString_whenUsingSymmetricSubstringExpansion_thenFindLongestSymmetricSubstring() {
int start = 0;
int mid = 0;
int last_gt = 0;
int end = 0;
int best = 0;
static int findLongestSymmetricSubstringUsingSymmetricApproach(String str) {
int maxLength = 1;
while (start < input.length()) {
int current = Math.min(mid - start, end - mid);
if (best < current) {
best = current;
}
if (end - mid == current && end < input.length()) {
if (input.charAt(end) == '?') {
end++;
} else if (input.charAt(end) == '>') {
end++;
last_gt = end;
} else {
end++;
mid = end;
start = Math.max(start, last_gt);
for (int i = 0; i < str.length(); i++) {
for (int j = i; j < str.length(); j++) {
int flag = 1;
for (int k = 0; k < (j - i + 1) / 2; k++) {
if (str.charAt(i + k) != str.charAt(j - k)) {
flag = 0;
break;
}
}
if (flag != 0 && (j - i + 1) > maxLength) {
maxLength = j - i + 1;
}
} else if (mid < input.length() && input.charAt(mid) == '?') {
mid++;
} else if (start < mid) {
start++;
} else {
start = Math.max(start, last_gt);
mid++;
end = Math.max(mid, end);
}
}
int result = 2 * best;
assertEquals(expected, result);
return maxLength;
}
@Test
public void givenString_whenUsingBruteForce_thenFindLongestSymmetricSubstring() {
int max = 0;
for (int i = 0; i < input.length(); i++) {
for (int j = i + 1; j <= input.length(); j++) {
String t = input.substring(i, j);
if (t.length() % 2 == 0) {
int k = 0, l = t.length() - 1;
boolean isSym = true;
while (k < l && isSym) {
if (!(t.charAt(k) == '<' || t.charAt(k) == '?') && (t.charAt(l) == '>' || t.charAt(l) == '?')) {
isSym = false;
}
k++;
l--;
}
if (isSym) {
max = Math.max(max, t.length());
}
assertEquals(expected, findLongestSymmetricSubstringUsingBruteForce(input).length());
}
@Test
public void givenString_whenUsingSymmetricSubstring_thenFindLongestSymmetricSubstring() {
assertEquals(expected, findLongestSymmetricSubstringUsingSymmetricApproach(input));
}
private String findLongestSymmetricSubstringUsingBruteForce(String str) {
if (str == null || str.length() == 0) {
return "";
}
int maxLength = 0;
String longestPalindrome = "";
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j <= str.length(); j++) {
String substring = str.substring(i, j);
if (isPalindrome(substring) && substring.length() > maxLength) {
maxLength = substring.length();
longestPalindrome = substring;
}
}
}
assertEquals(expected, max);
return longestPalindrome;
}
private boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}

View File

@ -165,6 +165,7 @@
<module>core-java-networking</module>
<module>core-java-networking-2</module>
<module>core-java-networking-4</module>
<module>core-java-networking-5</module>
<module>core-java-nio</module>
<module>core-java-nio-2</module>
<module>core-java-numbers</module>

View File

@ -20,7 +20,7 @@
<!-- Boot version compatible with spqr-boot-starter -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.6.4</version>
<version>2.6.15</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -34,4 +34,11 @@
<module>graphql-spqr-boot-starter</module>
</modules>
<properties>
<org.slf4j.version>1.7.32</org.slf4j.version>
<logback.version>1.2.7</logback.version>
<!-- Can't update to the recent mockito version, without updating the spring boot version-->
<mockito.version>4.4.0</mockito.version>
</properties>
</project>

View File

@ -0,0 +1,41 @@
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 {
// Method 1: Using BufferedImage Constructor
public BufferedImage convertUsingConstructor(Image image) throws IllegalArgumentException {
int width = image.getWidth(null);
int height = image.getHeight(null);
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Image dimensions are invalid");
}
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
bufferedImage.getGraphics().drawImage(image, 0, 0, null);
return bufferedImage;
}
// Method 2: Casting Image to BufferedImage
public BufferedImage convertUsingCasting(Image image) throws ClassCastException {
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());
}
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.image.resize.imagetobufferedimage;
import com.baeldung.imageprocessing.imagetobufferedimage.ImageToBufferedImage;
import org.junit.Test;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class ImageToBufferedImageUnitTest {
Image image = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
public ImageToBufferedImageUnitTest() throws IOException {
}
@Test
public void whenConvertUsingConstructorWithValidDimensions_thenImageGeneratedWithoutError() {
ImageToBufferedImage converter = new ImageToBufferedImage();
BufferedImage bufferedImage = converter.convertUsingConstructor(image);
assertNotNull(bufferedImage);
assertEquals(image.getWidth(null), bufferedImage.getWidth());
assertEquals(image.getHeight(null), bufferedImage.getHeight());
}
@Test(expected = IllegalArgumentException.class)
public void whenConvertUsingConstructorWithInvalidDimensions_thenImageGeneratedWithError() {
ImageToBufferedImage converter = new ImageToBufferedImage();
converter.convertUsingConstructor(new BufferedImage(-100, -100, BufferedImage.TYPE_INT_ARGB));
}
@Test
public void whenConvertUsingCastingWithCompatibleImageType_thenImageGeneratedWithoutError() {
ImageToBufferedImage converter = new ImageToBufferedImage();
BufferedImage bufferedImage = converter.convertUsingCasting(image);
assertNotNull(bufferedImage);
assertEquals(image.getWidth(null), bufferedImage.getWidth());
assertEquals(image.getHeight(null), bufferedImage.getHeight());
}
@Test(expected = ClassCastException.class)
public void whenConvertUsingCastingWithIncompatibleImageType_thenImageGeneratedWithError() {
ImageToBufferedImage converter = new ImageToBufferedImage();
// PNG format is not directly supported by BufferedImage
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

@ -60,7 +60,7 @@
<properties>
<h2.version>2.1.214</h2.version>
<json-path.version>5.4.0</json-path.version>
<spring-boot.version>2.5.0</spring-boot.version>
<spring-boot.version>3.1.5</spring-boot.version>
</properties>
</project>

View File

@ -1,9 +1,9 @@
package com.baeldung.jackson.jsonignorevstransient;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.Transient;
import java.io.Serializable;
@Entity

View File

@ -31,9 +31,9 @@
<jhipster.server.version>1.1.0</jhipster.server.version>
<jjwt.version>0.12.3</jjwt.version>
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
<liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
<liquibase-hibernate5.version>4.27.0</liquibase-hibernate5.version>
<liquibase-slf4j.version>2.0.0</liquibase-slf4j.version>
<liquibase.version>3.6.2</liquibase.version>
<liquibase.version>4.27.0</liquibase.version>
<logstash-logback-encoder.version>4.8</logstash-logback-encoder.version>
<m2e.apt.activation>jdt_apt</m2e.apt.activation>
<mapstruct.version>1.1.0.Final</mapstruct.version>

View File

@ -1,10 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">
<property name="now" value="now()" dbms="h2"/>
<property name="now" value="now()" dbms="mysql"/>

View File

@ -1,10 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">
<property name="now" value="now()" dbms="h2"/>
@ -36,6 +32,6 @@
<!-- jhipster-needle-liquibase-add-column - JHipster will add columns here, do not remove-->
</createTable>
</changeSet>
</databaseChangeLog>

View File

@ -1,9 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">
<include file="classpath:config/liquibase/changelog/00000000000000_initial_schema.xml" relativeToChangelogFile="false"/>
<include file="classpath:config/liquibase/changelog/20170503041524_added_entity_Car.xml" relativeToChangelogFile="false"/>
<!-- jhipster-needle-liquibase-add-changelog - JHipster will add liquibase changelogs here -->

View File

@ -85,7 +85,7 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>${mockito.version}</version>
<version>${mockito-inline.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -120,6 +120,7 @@
<reactive.stream.version>1.0.3</reactive.stream.version>
<reactor.version>3.6.0</reactor.version>
<jmockit.version>1.49</jmockit.version>
<mockito-inline.version>5.2.0</mockito-inline.version>
</properties>
</project>

View File

@ -49,11 +49,23 @@
<properties>
<jool.version>0.9.12</jool.version>
<parallel-collectors.version>2.6.0</parallel-collectors.version>
<parallel-collectors.version>3.0.0</parallel-collectors.version>
<vavr.version>0.9.0</vavr.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version>
<streamex.version>0.8.1</streamex.version>
<protonpack.version>1.15</protonpack.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>21</source>
<target>21</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,73 @@
package com.baeldung.parallel_collectors;
import com.pivovarit.collectors.ParallelCollectors;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class ParallelCollectorsVirtualThreadsManualTest {
private static final Logger log = LoggerFactory.getLogger(ParallelCollectorsVirtualThreadsManualTest.class);
// increase the number of parallel processes to find the max number of threads on your machine
@Test
public void givenParallelism_whenUsingOSThreads_thenShouldRunOutOfThreads() {
int parallelProcesses = 50_000;
var e = Executors.newFixedThreadPool(parallelProcesses);
var result = timed(() -> Stream.iterate(0, i -> i + 1).limit(parallelProcesses)
.collect(ParallelCollectors.parallel(i -> fetchById(i), toList(), e, parallelProcesses))
.join());
log.info("{}", result);
}
@Test
public void givenParallelism_whenUsingVThreads_thenShouldProcessInParallel() {
int parallelProcesses = 1000_000;
var result = timed(() -> Stream.iterate(0, i -> i + 1).limit(parallelProcesses)
.collect(ParallelCollectors.parallel(i -> fetchById(i), toList()))
.join());
log.info("{}", result);
}
@Test
public void givenParallelismAndPCollectors2_whenUsingVThreads_thenShouldProcessInParallel() {
int parallelProcesses = 1000_000;
var result = timed(() -> Stream.iterate(0, i -> i + 1).limit(parallelProcesses)
.collect(ParallelCollectors.parallel(i -> fetchById(i), toList(), Executors.newVirtualThreadPerTaskExecutor(), Integer.MAX_VALUE))
.join());
log.info("{}", result);
}
private static String fetchById(int id) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignore shamelessly
}
return "user-" + id;
}
private static <T> T timed(Supplier<T> supplier) {
var before = Instant.now();
T result = supplier.get();
var after = Instant.now();
log.info("Execution time: {} ms", Duration.between(before, after).toMillis());
return result;
}
}

View File

@ -78,40 +78,20 @@
</dependency>
</dependencies>
<profiles>
<profile>
<id>integration-lite-first</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<logback.configurationFile>${project.basedir}/src/test/resources/logback-test.xml</logback.configurationFile>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>integration-lite-second</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<logback.configurationFile>${project.basedir}/src/test/resources/logback-test.xml</logback.configurationFile>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<logback.configurationFile>${project.basedir}/src/test/resources/logback-test.xml</logback.configurationFile>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<json.version>20240303</json.version>

View File

@ -12,3 +12,5 @@ This module contains articles about MapStruct.
- [Use Mapper in Another Mapper with Mapstruct and Java](https://www.baeldung.com/java-mapstruct-nested-mapping)
- [Throw Exception for Unexpected Input for Enum With MapStruct](https://www.baeldung.com/java-mapstruct-enum-unexpected-input-exception)
- [How to Use Conditional Mapping With MapStruct](https://www.baeldung.com/java-mapstruct-bean-types-conditional)
- [Mapping Enum With MapStruct](https://www.baeldung.com/java-mapstruct-enum)

View File

@ -44,7 +44,7 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-core.version}</version>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -83,7 +83,6 @@
<activemq.version>5.14.1</activemq.version>
<spring-boot-test.version>1.5.10.RELEASE</spring-boot-test.version>
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
<mockito-core.version>4.6.1</mockito-core.version>
<activemq-junit.version>5.16.5</activemq-junit.version>
<testcontainers.version>1.17.3</testcontainers.version>
<junit-jupiter.version>5.10.1</junit-jupiter.version>

View File

@ -34,7 +34,7 @@
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>${spring.webmvc.version}</version>
<version>${springdoc-openapi-webmvc-ui.version}</version>
</dependency>
<dependency>
@ -71,6 +71,7 @@
<java.version>17</java.version>
<conductor.client.version>2.0.8</conductor.client.version>
<spring.webmvc.version>2.1.0</spring.webmvc.version>
<springdoc-openapi-webmvc-ui.version>2.5.0</springdoc-openapi-webmvc-ui.version>
</properties>
</project>

View File

@ -107,6 +107,8 @@
<spring-boot.version>2.7.11</spring-boot.version>
<aspectj.version>1.9.20.1</aspectj.version>
<mysql-connector-java.version>8.2.0</mysql-connector-java.version>
<org.slf4j.version>1.7.32</org.slf4j.version>
<logback.version>1.2.7</logback.version>
</properties>
</project>

View File

@ -47,12 +47,12 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -232,8 +232,6 @@
<spring-boot.version>3.1.5</spring-boot.version>
<junit-jupiter.version>5.8.2</junit-jupiter.version>
<native-build-tools-plugin.version>0.9.17</native-build-tools-plugin.version>
<logback.version>1.4.4</logback.version>
<slf4j.version>2.0.3</slf4j.version>
</properties>
</project>

View File

@ -15,13 +15,75 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<spring.version>5.3.28</spring.version>

View File

@ -72,6 +72,8 @@
<spring-integration-test.version>5.5.14</spring-integration-test.version>
<camel-core.version>3.20.4</camel-core.version>
<camel-test-junit5.version>3.14.0</camel-test-junit5.version>
<org.slf4j.version>1.7.32</org.slf4j.version>
<logback.version>1.2.7</logback.version>
</properties>
</project>

View File

@ -16,9 +16,18 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>${mockito.version}</version>
<version>${mockito-inline.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
</dependency>
</dependencies>
</project>
<properties>
<mockito-inline.version>5.2.0</mockito-inline.version>
</properties>
</project>

View File

@ -0,0 +1,29 @@
package com.baeldung.builder.implementation;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
public class GenericBuilder<T> {
private final Supplier<T> supplier;
private GenericBuilder(Supplier<T> supplier) {
this.supplier = supplier;
}
public static <T> GenericBuilder<T> of(Supplier<T> supplier) {
return new GenericBuilder<>(supplier);
}
public <P> GenericBuilder<T> with(BiConsumer<T, P> consumer, P value) {
return new GenericBuilder<>(() -> {
T object = supplier.get();
consumer.accept(object, value);
return object;
});
}
public T build() {
return supplier.get();
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.builder.implementation;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Builder
@Getter
@Setter
public class LombokPost {
private String title;
private String text;
private String category;
}

View File

@ -0,0 +1,74 @@
package com.baeldung.builder.implementation;
public class Post {
private String title;
private String text;
private String category;
Post(Builder builder) {
this.title = builder.title;
this.text = builder.text;
this.category = builder.category;
}
Post() {}
public String getTitle() {
return title;
}
public String getText() {
return text;
}
public String getCategory() {
return category;
}
public void setTitle(String title) {
this.title = title;
}
public void setText(String text) {
this.text = text;
}
public void setCategory(String category) {
this.category = category;
}
@Override
public String toString() {
return "Post{" + "title='" + title + '\'' + ", text='" + text + '\'' + ", category='" + category + '\'' + '}';
}
public static class Builder {
private String title;
private String text;
private String category;
public Builder() {}
public Builder title(String title) {
this.title = title;
return this;
}
public Builder text(String text) {
this.text = text;
return this;
}
public Builder category(String category) {
this.category = category;
return this;
}
public Post build() {
return new Post(this);
}
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.builder.implementation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class BuilderImplementationUnitTest {
@Test
void givenClassicBuilder_whenBuild_thenReturnObject() {
Post post = new Post.Builder()
.title("Java Builder Pattern")
.text("Explaining how to implement the Builder Pattern in Java")
.category("Programming")
.build();
assertEquals("Java Builder Pattern", post.getTitle());
assertEquals("Explaining how to implement the Builder Pattern in Java", post.getText());
assertEquals("Programming", post.getCategory());
}
@Test
void givenGenericBuilder_whenBuild_thenReturnObject() {
Post post = GenericBuilder.of(Post::new)
.with(Post::setTitle, "Java Builder Pattern")
.with(Post::setText, "Explaining how to implement the Builder Pattern in Java")
.with(Post::setCategory, "Programming")
.build();
assertEquals("Java Builder Pattern", post.getTitle());
assertEquals("Explaining how to implement the Builder Pattern in Java", post.getText());
assertEquals("Programming", post.getCategory());
}
@Test
void givenLombokBuilder_whenBuild_thenReturnObject() {
LombokPost post = LombokPost.builder()
.title("Java Builder Pattern")
.text("Explaining how to implement the Builder Pattern in Java")
.category("Programming")
.build();
assertEquals("Java Builder Pattern", post.getTitle());
assertEquals("Explaining how to implement the Builder Pattern in Java", post.getText());
assertEquals("Programming", post.getCategory());
}
}

View File

@ -3,7 +3,6 @@
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>
<groupId>com.baeldung</groupId>
<artifactId>monkey-patching</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>monkey-patching</name>
@ -19,12 +18,12 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.0</version>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.7.0</version>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -45,5 +44,7 @@
<properties>
<spring-boot.version>2.7.0</spring-boot.version>
<org.slf4j.version>1.7.32</org.slf4j.version>
<logback.version>1.2.7</logback.version>
</properties>
</project>

View File

@ -0,0 +1,42 @@
<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>
<groupId>org.baeldung</groupId>
<artifactId>duckdb</artifactId>
<name>duckdb</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>9</source>
<target>9</target>
</configuration>
</plugin>
</plugins>
</build>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>persistence-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<duckdb.version>0.10.0</duckdb.version>
</properties>
<dependencies>
<dependency>
<groupId>org.duckdb</groupId>
<artifactId>duckdb_jdbc</artifactId>
<version>${duckdb.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,198 @@
package com.baeldung;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
class DuckDbAccessIntegrationTest {
private Connection conn = null;
private Statement stmt = null;
@BeforeAll
static void setupOnce() throws Exception {
Class.forName("org.duckdb.DuckDBDriver");
}
@BeforeEach
void setup() throws SQLException {
conn = DriverManager.getConnection("jdbc:duckdb:");
stmt = conn.createStatement();
}
@Test
void whenQueryCurrentDate_thenReturnToday() throws SQLException {
ResultSet rs = stmt.executeQuery("SELECT current_date");
Date currentDate = rs.next() ? rs.getDate(1) : null;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date expectedDate = calendar.getTime();
assertThat(currentDate).isEqualTo(expectedDate);
}
@Test
void whenReadCsv_thenReturnHeaderAndData() throws SQLException {
String filePath = getResourceAbsolutePath("/customer.csv");
String query = String.format("SELECT * FROM read_csv('%s')", filePath);
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData metadata = rs.getMetaData();
List<String> actualHeaderNames = new ArrayList<>();
for (int n=1; n<=metadata.getColumnCount(); n++) {
actualHeaderNames.add(metadata.getColumnLabel(n));
}
// Then
List<String> expectedHeaderNames = List.of("CustomerId", "FirstName", "LastName", "Gender");
assertThat(actualHeaderNames).isEqualTo(expectedHeaderNames);
int rowCount = 0;
while (rs.next()) {
rowCount++;
}
assertThat(rowCount).isEqualTo(10);
}
@Test
void whenImportByCsv_thenReturnCorrectRowCount() throws SQLException {
// When
String filePath = getResourceAbsolutePath("/customer.csv");
String query = String.format("CREATE TABLE customer AS SELECT * FROM read_csv('%s')", filePath);
stmt.executeUpdate(query);
// Then
assertThat(getTableRowCount(conn, "customer")).isEqualTo(10);
}
@Test
void whenImportByJson_thenReturnCorrectRowCount() throws SQLException {
// When
String filePath = getResourceAbsolutePath("/product.json");
String query = String.format("CREATE TABLE product AS SELECT * FROM read_json('%s')", filePath);
stmt.executeUpdate(query);
// Then
assertThat(getTableRowCount(conn, "product")).isEqualTo(3);
}
@Test
void whenImportByInsert_thenReturnCorrectRowCount() throws SQLException {
// When
stmt.executeUpdate("CREATE TABLE purchase(customerId BIGINT, productId BIGINT)");
String query = "INSERT INTO purchase(customerId, productId) VALUES (?,?)";
try (PreparedStatement pStmt = conn.prepareStatement(query)) {
pStmt.setInt(1, 101);
pStmt.setInt(2, 1);
pStmt.addBatch();
pStmt.setInt(1, 101);
pStmt.setInt(2, 2);
pStmt.addBatch();
pStmt.setInt(1, 102);
pStmt.setInt(2, 2);
pStmt.addBatch();
pStmt.executeBatch();
}
// Then
assertThat(getTableRowCount(conn, "purchase")).isEqualTo(3);
}
@Test
void whenQueryWithJoin_thenReturnCorrectCount() throws SQLException {
String customerFilePath = getResourceAbsolutePath("/customer.csv");
String productFilePath = getResourceAbsolutePath("/product.json");
whenImportByInsert_thenReturnCorrectRowCount();
String query = String.format("SELECT C.firstName, C.lastName, P.productName " +
"FROM read_csv('%s') AS C, read_json('%s') AS P, purchase S " +
"WHERE S.customerId = C.customerId " +
"AND S.productId = P.productId ",
customerFilePath, productFilePath);
int count = 0;
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
count++;
}
assertThat(count).isEqualTo(3);
}
@Test
void whenExportData_thenFileIsCreated() throws IOException, SQLException {
createPurchaseView(conn);
File tempFile = File.createTempFile("temp", "");
String exportFilePath = tempFile.getAbsolutePath();
String query = String.format("COPY purchase_view TO '%s'", exportFilePath);
stmt.executeUpdate(query);
assertThat(tempFile.length()).isGreaterThan(0);
tempFile.delete();
}
@AfterEach
void tearDown() throws SQLException {
stmt.close();
conn.close();
}
private String getResourceAbsolutePath(String name) {
return this.getClass().getResource(name).getPath().replaceFirst("/", "");
}
private int getTableRowCount(Connection conn, String tableName) throws SQLException {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery(String.format("SELECT COUNT(*) FROM %s", tableName));
return (rs.next()) ? rs.getInt(1) : 0;
}
}
private void createPurchaseView(Connection conn) throws SQLException {
whenImportByCsv_thenReturnCorrectRowCount();
whenImportByJson_thenReturnCorrectRowCount();
whenImportByInsert_thenReturnCorrectRowCount();
String query = "CREATE VIEW purchase_view AS " +
"SELECT P.productName, COUNT(*) AS purchaseCount " +
"FROM customer C, product P, purchase S " +
"WHERE S.customerId = C.customerId " +
"AND S.productId = P.productId " +
"GROUP BY P.productName " +
"ORDER BY COUNT(*) DESC ";
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate(query);
}
}
}

View File

@ -0,0 +1,11 @@
CustomerId,FirstName,LastName,Gender
101,John,Smith,Male
102,Sarah,Jones,Female
103,Michael,Johnson,Male
104,Emily,Davis,Female
105,David,Brown,Male
106,Emma,Williams,Female
107,Alexander,Miller,Male
108,Samantha,Anderson,Female
109,Matthew,Taylor,Male
110,Olivia,Thompson,Female
1 CustomerId FirstName LastName Gender
2 101 John Smith Male
3 102 Sarah Jones Female
4 103 Michael Johnson Male
5 104 Emily Davis Female
6 105 David Brown Male
7 106 Emma Williams Female
8 107 Alexander Miller Male
9 108 Samantha Anderson Female
10 109 Matthew Taylor Male
11 110 Olivia Thompson Female

View File

@ -0,0 +1,17 @@
[
{
"productId": 1,
"productName":"EZ Curl Bar",
"category": "Sports Equipment"
},
{
"productId": 2,
"productName": "7' Barbell",
"category": "Sports Equipment"
},
{
"productId": 3,
"productName": "Single Mouthguard - Black",
"category": "Sports Equipment"
}
]

View File

@ -0,0 +1,6 @@
## Hibernate Annotations
This module contains articles about Annotations used in Hibernate.
### Relevant Articles:
- [@Subselect Annotation in Hibernate](https://www.baeldung.com/hibernate-subselect)

View File

@ -0,0 +1,109 @@
<?xml version="1.0"?>
<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>hibernate-annotations-2</artifactId>
<version>0.1-SNAPSHOT</version>
<name>hibernate-annotations-2</name>
<packaging>jar</packaging>
<description>Hibernate annotations module, part 2</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>persistence-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${org.springframework.data.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-core.version}</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-testing</artifactId>
<version>${hibernate-core.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-spatial</artifactId>
<version>${hibernate-core.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>${tomcat-dbcp.version}</version>
</dependency>
<!-- validation -->
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.hypersistence</groupId>
<artifactId>hypersistence-utils-hibernate-60</artifactId>
<version>${hypersistance-utils-hibernate-60.version}</version>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>${liquibase-core.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
</dependencies>
<properties>
<!-- Spring -->
<org.springframework.version>6.0.6</org.springframework.version>
<org.springframework.data.version>3.0.3</org.springframework.data.version>
<hibernate-core.version>6.4.2.Final</hibernate-core.version>
<maven.deploy.skip>true</maven.deploy.skip>
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
<hypersistance-utils-hibernate-60.version>3.3.1</hypersistance-utils-hibernate-60.version>
<lombok.version>1.18.30</lombok.version>
<liquibase-core.version>4.24.0</liquibase-core.version>
</properties>
</project>

View File

@ -0,0 +1,50 @@
package com.baeldung.hibernate;
import com.baeldung.hibernate.subselect.RuntimeConfiguration;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
public class HibernateAnnotationUtil {
private static final SessionFactory SESSION_FACTORY = buildSessionFactory();
/**
* Utility class
*/
private HibernateAnnotationUtil() {
}
public static SessionFactory getSessionFactory() {
return SESSION_FACTORY;
}
private static SessionFactory buildSessionFactory() {
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(dbSettings())
.build();
Metadata metadata = new MetadataSources(serviceRegistry)
.addAnnotatedClass(RuntimeConfiguration.class)
.buildMetadata();
return metadata.buildSessionFactory();
}
private static Map<String, Object> dbSettings() {
Map<String, Object> dbSettings = new HashMap<>();
dbSettings.put(Environment.URL, "jdbc:h2:mem:spring_hibernate_one_to_many");
dbSettings.put(Environment.USER, "sa");
dbSettings.put(Environment.PASS, "");
dbSettings.put(Environment.DRIVER, "org.h2.Driver");
dbSettings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
dbSettings.put(Environment.SHOW_SQL, "true");
dbSettings.put(Environment.HBM2DDL_AUTO, "create");
return dbSettings;
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.hibernate;
import com.google.common.base.Preconditions;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
public class PersistenceConfig {
@Autowired
private Environment env;
@Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource dataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", "false");
return hibernateProperties;
}
}

View File

@ -0,0 +1,15 @@
# jdbc.X
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.eventGeneratedId=sa
jdbc.user=sa
jdbc.pass=
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory

View File

@ -0,0 +1,18 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.hibernate.PersistenceConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -1,6 +1,6 @@
package com.baeldung.hibernate.subselect;
import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil;
import com.baeldung.hibernate.HibernateAnnotationUtil;
import jakarta.persistence.criteria.Root;
import liquibase.Contexts;
import liquibase.LabelExpression;

View File

@ -4,7 +4,6 @@ import com.baeldung.hibernate.oneToMany.model.Cart;
import com.baeldung.hibernate.oneToMany.model.CartOIO;
import com.baeldung.hibernate.oneToMany.model.Item;
import com.baeldung.hibernate.oneToMany.model.ItemOIO;
import com.baeldung.hibernate.subselect.RuntimeConfiguration;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
@ -39,7 +38,6 @@ public class HibernateAnnotationUtil {
.addAnnotatedClass(CartOIO.class)
.addAnnotatedClass(Item.class)
.addAnnotatedClass(ItemOIO.class)
.addAnnotatedClass(RuntimeConfiguration.class)
.buildMetadata();
return metadata.buildSessionFactory();

View File

@ -20,7 +20,7 @@ import com.baeldung.jooq.jointables.public_.tables.Book;
import com.baeldung.jooq.jointables.public_.tables.Bookauthor;
import com.baeldung.jooq.jointables.public_.tables.Store;
public class JoinTablesIntegrationTest {
public class JoinTablesLiveTest {
static DSLContext context;

View File

@ -24,6 +24,7 @@
<module>core-java-persistence-2</module>
<module>core-java-persistence-3</module>
<module>couchbase</module>
<module>duckdb</module>
<module>elasticsearch</module>
<module>flyway</module>
<module>flyway-repair</module>
@ -68,6 +69,7 @@
<module>spring-boot-persistence-mongodb</module>
<module>spring-boot-persistence-mongodb-2</module>
<module>spring-boot-persistence-mongodb-3</module>
<module>spring-boot-persistence-mongodb-4</module>
<module>spring-data-arangodb</module>
<!--<module>spring-data-cassandra</module>--> <!-- failing after upgrading to jdk17. JDK 17 compatibility in progress CASSANDRA-16895 -->
<module>spring-data-cassandra-test</module>

View File

@ -60,6 +60,11 @@
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.tx.version}</version>
</dependency>
</dependencies>
<build>
@ -84,6 +89,7 @@
<modelmapper.version>3.2.0</modelmapper.version>
<commons-codec.version>1.16.1</commons-codec.version>
<lombok.version>1.18.30</lombok.version>
<spring.tx.version>6.1.4</spring.tx.version>
</properties>
</project>

View File

@ -0,0 +1,23 @@
package com.baeldung.transactionalandasync;
import jakarta.persistence.*;
import lombok.*;
import java.math.BigDecimal;
@Entity
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(of = {"id"})
@Table(name = "account")
@Data
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "balance")
private BigDecimal balance;
}

View File

@ -0,0 +1,6 @@
package com.baeldung.transactionalandasync;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AccountRepository extends JpaRepository<Account, Long> {
}

View File

@ -0,0 +1,41 @@
package com.baeldung.transactionalandasync;
import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
@AllArgsConstructor
@Transactional
public class AccountService {
private final AccountRepository accountRepository;
@Async
public void transferAsync(Long depositorId, Long favoredId, BigDecimal amount) {
transfer(depositorId, favoredId, amount);
printReceipt();
}
@Transactional
public void transfer(Long depositorId, Long favoredId, BigDecimal amount) {
Account depositorAccount = accountRepository.findById(depositorId)
.orElseThrow(IllegalArgumentException::new);
Account favoredAccount = accountRepository.findById(favoredId)
.orElseThrow(IllegalArgumentException::new);
depositorAccount.setBalance(depositorAccount.getBalance().subtract(amount));
favoredAccount.setBalance(favoredAccount.getBalance().add(amount));
accountRepository.save(depositorAccount);
accountRepository.save(favoredAccount);
}
public void printReceipt() {
// logic to print the receipt
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.transactionalandasync;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BankAccountApplication {
public static void main(String[] args) {
SpringApplication.run(BankAccountApplication.class, args);
}
}

View File

@ -0,0 +1,5 @@
# Relevant Articles
- [ZonedDateTime with Spring Data MongoDB](https://www.baeldung.com/spring-data-mongodb-zoneddatetime)
- [A Guide to @DBRef in MongoDB](https://www.baeldung.com/spring-mongodb-dbref-annotation)
- More articles: [[<--prev]](../spring-boot-persistence-mongodb-3)

View File

@ -0,0 +1,34 @@
<?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>spring-boot-persistence-mongodb-4</artifactId>
<name>spring-boot-persistence-mongodb-4</name>
<description>This is simple boot application for Spring boot persistence mongodb test</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MongoDB -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,5 +1,6 @@
package com.baeldung.mongodb.dbref;
import com.baeldung.mongodb.dbref.repository.PersonRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -7,8 +8,6 @@ import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import com.baeldung.mongodb.dbref.repository.PersonRepository;
@Component
public class DbRefTester implements ApplicationRunner {

View File

@ -1,11 +1,11 @@
package com.baeldung.mongodb.dbref.model;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List;
@Document(collection = "Person")
public class Person {

View File

@ -1,8 +1,7 @@
package com.baeldung.mongodb.dbref.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.baeldung.mongodb.dbref.model.Person;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface PersonRepository extends MongoRepository<Person, String> {

View File

@ -1,15 +1,14 @@
package com.baeldung.zoneddatetime.config;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.zoneddatetime.converter.ZonedDateTimeReadConverter;
import com.baeldung.zoneddatetime.converter.ZonedDateTimeWriteConverter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.baeldung.zoneddatetime.converter.ZonedDateTimeReadConverter;
import com.baeldung.zoneddatetime.converter.ZonedDateTimeWriteConverter;
import java.util.ArrayList;
import java.util.List;
@EnableMongoRepositories(basePackages = { "com.baeldung" })
public class MongoConfig extends AbstractMongoClientConfiguration {

View File

@ -1,7 +1,6 @@
package com.baeldung.zoneddatetime.repository;
import com.baeldung.zoneddatetime.model.Action;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.baeldung.zoneddatetime.model.Action;
public interface ActionRepository extends MongoRepository<Action, String> { }

View File

@ -0,0 +1 @@
spring.application.name=spring-boot-persistence-mongodb-4

View File

@ -1,11 +1,11 @@
package com.baeldung.mongodb.dbref;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.mongodb.dbref.model.Person;
import com.baeldung.mongodb.dbref.model.Pet;
import com.baeldung.mongodb.dbref.repository.PersonRepository;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBObject;
import com.mongodb.DBRef;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -14,12 +14,11 @@ import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.mongodb.dbref.model.Person;
import com.baeldung.mongodb.dbref.model.Pet;
import com.baeldung.mongodb.dbref.repository.PersonRepository;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBObject;
import com.mongodb.DBRef;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest

View File

@ -1,5 +1,8 @@
package com.baeldung.zoneddatetime;
import com.baeldung.zoneddatetime.config.MongoConfig;
import com.baeldung.zoneddatetime.model.Action;
import com.baeldung.zoneddatetime.repository.ActionRepository;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@ -10,10 +13,6 @@ import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.zoneddatetime.config.MongoConfig;
import com.baeldung.zoneddatetime.model.Action;
import com.baeldung.zoneddatetime.repository.ActionRepository;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

View File

@ -0,0 +1 @@
spring.mongodb.embedded.version=4.4.9

View File

@ -4,8 +4,6 @@
- [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb)
- [Upload and Retrieve Files Using MongoDB and Spring Boot](https://www.baeldung.com/spring-boot-mongodb-upload-file)
- [GridFS in Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-gridfs)
- [ZonedDateTime with Spring Data MongoDB](https://www.baeldung.com/spring-data-mongodb-zoneddatetime)
- [A Guide to @DBRef in MongoDB](https://www.baeldung.com/spring-mongodb-dbref-annotation)
- [Import Data to MongoDB From JSON File Using Java](https://www.baeldung.com/java-import-json-mongodb)
- [Spring Data MongoDB Configure Connection](https://www.baeldung.com/spring-data-mongodb-connection)
- More articles: [[next-->]](../spring-boot-persistence-mongodb-2)

View File

@ -70,7 +70,6 @@
</dependencies>
<properties>
<mockito.version>2.23.0</mockito.version>
<validation-api.version>2.0.1.Final</validation-api.version>
<mysql-connector-java.version>8.2.0</mysql-connector-java.version>
<start-class>com.baeldung.boot.Application</start-class>

View File

@ -136,6 +136,12 @@
<type>so</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.14.13</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -5,8 +5,6 @@ import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringContextTest {

View File

@ -0,0 +1,24 @@
package com.baeldung.spring.data.jpa.getnextseq;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
@Entity
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "mySeqGen")
@SequenceGenerator(name = "mySeqGen", sequenceName = "my_sequence_name", allocationSize = 1)
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.spring.data.jpa.getnextseq;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyEntityApplication {
public static void main(String[] args) {
SpringApplication.run(MyEntityApplication.class);
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.spring.data.jpa.getnextseq;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {
@Query(value = "SELECT NEXTVAL('my_sequence_name')", nativeQuery = true)
Long getNextSequenceValue();
}

View File

@ -0,0 +1,22 @@
package com.baeldung.spring.data.jpa.getnextseq;
import java.math.BigInteger;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
@Service
public class MyEntityService {
@PersistenceContext
private EntityManager entityManager;
public Long getNextSequenceValue(String sequenceName) {
BigInteger nextValue = (BigInteger) entityManager.createNativeQuery("SELECT NEXTVAL(:sequenceName)")
.setParameter("sequenceName", sequenceName)
.getSingleResult();
return nextValue.longValue();
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.spring.data.jpa.getnextseq;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
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.jdbc.Sql;
@SpringBootTest
@ActiveProfiles("test")
@Sql(scripts = "/testsequence.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
public class MyEntityRepositoryIntegrationTest {
@Autowired
private MyEntityRepository myEntityRepository;
@Autowired
private MyEntityService myEntityService;
@Test
void whenUsingSequenceGenerator_thenNextValueReturned() {
MyEntity entity = new MyEntity();
myEntityRepository.save(entity);
long generatedId = entity.getId();
assertNotNull(generatedId);
assertEquals(1L, generatedId);
}
@Test
void whenUsingCustomQuery_thenNextValueReturned() {
long generatedId = myEntityRepository.getNextSequenceValue();
assertNotNull(generatedId);
assertEquals(1L, generatedId);
}
@Test
void whenUsingEntityManager_thenNextValueReturned() {
long generatedId = myEntityService.getNextSequenceValue("my_sequence_name");
assertNotNull(generatedId);
assertEquals(1L, generatedId);
}
}

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