Merge branch 'eugenp:master' into master
This commit is contained in:
commit
2fcd34c0a9
@ -1,23 +1,22 @@
|
|||||||
package com.baeldung.algorithms.mergeintervals;
|
package com.baeldung.algorithms.mergeintervals;
|
||||||
|
|
||||||
|
import static java.lang.Integer.max;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class MergeOverlappingIntervals {
|
public class MergeOverlappingIntervals {
|
||||||
|
|
||||||
public List<Interval> doMerge(List<Interval> intervals) {
|
public List<Interval> doMerge(List<Interval> intervals) {
|
||||||
// Sort the intervals based on start time
|
intervals.sort(Comparator.comparingInt(interval -> interval.start));
|
||||||
intervals.sort((one, two) -> one.start - two.start);
|
|
||||||
|
|
||||||
// Create somewhere to put the merged list, start it off with the earliest starting interval
|
|
||||||
ArrayList<Interval> merged = new ArrayList<>();
|
ArrayList<Interval> merged = new ArrayList<>();
|
||||||
merged.add(intervals.get(0));
|
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 -> {
|
intervals.forEach(interval -> {
|
||||||
if (merged.get(merged.size() - 1).end > interval.start) {
|
Interval lastMerged = merged.get(merged.size() - 1);
|
||||||
merged.get(merged.size() - 1).setEnd(interval.end);
|
if (interval.start <= lastMerged.end){
|
||||||
|
lastMerged.setEnd(max(interval.end, lastMerged.end));
|
||||||
} else {
|
} else {
|
||||||
merged.add(interval);
|
merged.add(interval);
|
||||||
}
|
}
|
||||||
@ -25,5 +24,4 @@ public class MergeOverlappingIntervals {
|
|||||||
|
|
||||||
return merged;
|
return merged;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
|
@ -1,30 +1,38 @@
|
|||||||
package com.baeldung.algorithms.mergeintervals;
|
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.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
class MergeIntervalsUnitTest {
|
class MergeIntervalsUnitTest {
|
||||||
|
|
||||||
private ArrayList<Interval> intervals = new ArrayList<>(Arrays.asList(
|
private List<Interval> intervals = new ArrayList<>(Arrays.asList(
|
||||||
new Interval(2, 5),
|
// @formatter:off
|
||||||
new Interval(13, 20),
|
new Interval(3, 5),
|
||||||
new Interval(11, 15),
|
new Interval(13, 20),
|
||||||
new Interval(1, 3)
|
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(
|
private List<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
|
||||||
new Interval(1, 5),
|
// @formatter:off
|
||||||
new Interval(11, 20)
|
new Interval(1, 5),
|
||||||
|
new Interval(11, 20)
|
||||||
|
// @formatter:on
|
||||||
));
|
));
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenIntervals_whenMerging_thenReturnMergedIntervals() {
|
void givenIntervals_whenMerging_thenReturnMergedIntervals() {
|
||||||
MergeOverlappingIntervals merger = new MergeOverlappingIntervals();
|
MergeOverlappingIntervals merger = new MergeOverlappingIntervals();
|
||||||
ArrayList<Interval> result = (ArrayList<Interval>) merger.doMerge(intervals);
|
List<Interval> result = merger.doMerge(intervals);
|
||||||
assertArrayEquals(intervalsMerged.toArray(), result.toArray());
|
assertEquals(intervalsMerged, result);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -40,6 +40,16 @@
|
|||||||
<artifactId>fastexcel-reader</artifactId>
|
<artifactId>fastexcel-reader</artifactId>
|
||||||
<version>${fastexcel.version}</version>
|
<version>${fastexcel.version}</version>
|
||||||
</dependency>
|
</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>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -64,6 +74,7 @@
|
|||||||
<jexcel.version>1.0.9</jexcel.version>
|
<jexcel.version>1.0.9</jexcel.version>
|
||||||
<fastexcel.version>0.17.0</fastexcel.version>
|
<fastexcel.version>0.17.0</fastexcel.version>
|
||||||
<maven.resources.plugin.version>3.3.1</maven.resources.plugin.version>
|
<maven.resources.plugin.version>3.3.1</maven.resources.plugin.version>
|
||||||
|
<log4j.version>2.23.1</log4j.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -71,7 +71,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.mockito</groupId>
|
<groupId>org.mockito</groupId>
|
||||||
<artifactId>mockito-core</artifactId>
|
<artifactId>mockito-core</artifactId>
|
||||||
<version>${mockito-core.version}</version>
|
<version>${mockito.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -112,7 +112,6 @@
|
|||||||
<feign-core.version>11.2</feign-core.version>
|
<feign-core.version>11.2</feign-core.version>
|
||||||
<guice.version>5.1.0</guice.version>
|
<guice.version>5.1.0</guice.version>
|
||||||
<system-stubs-junit4.version>2.0.2</system-stubs-junit4.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>
|
<assertj-core.version>3.19.0</assertj-core.version>
|
||||||
<junit-jupiter.version>5.8.1</junit-jupiter.version>
|
<junit-jupiter.version>5.8.1</junit-jupiter.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
@ -0,0 +1,4 @@
|
|||||||
|
package com.baeldung;
|
||||||
|
|
||||||
|
public class Unrelated {
|
||||||
|
}
|
@ -1,7 +1,7 @@
|
|||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
import static org.hamcrest.CoreMatchers.is;
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
@ -14,22 +14,22 @@ public class OuterUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGetNestHostFromOuter_thenGetNestHost() {
|
public void whenGetNestHostFromOuter_thenGetNestHost() {
|
||||||
is(Outer.class.getNestHost().getName()).equals(NEST_HOST_NAME);
|
assertEquals(NEST_HOST_NAME, Outer.class.getNestHost().getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGetNestHostFromInner_thenGetNestHost() {
|
public void whenGetNestHostFromInner_thenGetNestHost() {
|
||||||
is(Outer.Inner.class.getNestHost().getName()).equals(NEST_HOST_NAME);
|
assertEquals(NEST_HOST_NAME, Outer.Inner.class.getNestHost().getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCheckNestmatesForNestedClasses_thenGetTrue() {
|
public void whenCheckNestmatesForNestedClasses_thenGetTrue() {
|
||||||
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(true);
|
assertTrue(Outer.Inner.class.isNestmateOf(Outer.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCheckNestmatesForUnrelatedClasses_thenGetFalse() {
|
public void whenCheckNestmatesForUnrelatedClasses_thenGetFalse() {
|
||||||
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(false);
|
assertFalse(Outer.Inner.class.isNestmateOf(Unrelated.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
## Relevant Articles
|
## Relevant Articles
|
||||||
- [Deprecate Finalization in Java 18](https://www.baeldung.com/java-18-deprecate-finalization)
|
- [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)
|
- [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)
|
||||||
|
@ -3,3 +3,4 @@
|
|||||||
- [Find the Equilibrium Indexes of an Array in Java](https://www.baeldung.com/java-equilibrium-index-array)
|
- [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)
|
- [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)
|
- [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)
|
||||||
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
@ -13,4 +13,5 @@
|
|||||||
- [Check if List Contains at Least One Enum](https://www.baeldung.com/java-list-check-enum-presence)
|
- [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)
|
- [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)
|
- [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)
|
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
|
||||||
|
@ -3,3 +3,5 @@
|
|||||||
## Core Java Collections Cookbooks and Examples
|
## Core Java Collections Cookbooks and Examples
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-5)
|
||||||
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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)
|
- [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)
|
- [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)
|
- [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)
|
- [[<-- Prev]](/core-java-modules/core-java-io-4)
|
||||||
|
|
||||||
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
@ -20,28 +20,6 @@
|
|||||||
<version>${lombok.version}</version>
|
<version>${lombok.version}</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</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 -->
|
<!-- this is all you need to write tests with JUnit Jupiter -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.junit.jupiter</groupId>
|
<groupId>org.junit.jupiter</groupId>
|
||||||
@ -63,18 +41,6 @@
|
|||||||
<version>${junit-jupiter-version}</version>
|
<version>${junit-jupiter-version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</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>
|
<dependency>
|
||||||
<groupId>org.testng</groupId>
|
<groupId>org.testng</groupId>
|
||||||
<artifactId>testng</artifactId>
|
<artifactId>testng</artifactId>
|
||||||
|
@ -260,7 +260,6 @@
|
|||||||
<!-- util -->
|
<!-- util -->
|
||||||
<unix4j.version>0.4</unix4j.version>
|
<unix4j.version>0.4</unix4j.version>
|
||||||
<grep4j.version>1.8.7</grep4j.version>
|
<grep4j.version>1.8.7</grep4j.version>
|
||||||
<mockito.version>4.6.1</mockito.version>
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<javamoney.moneta.version>1.1</javamoney.moneta.version>
|
<javamoney.moneta.version>1.1</javamoney.moneta.version>
|
||||||
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
|
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
|
||||||
|
@ -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)
|
- [Law of Demeter in Java](https://www.baeldung.com/java-demeter-law)
|
||||||
- [Java Interface Naming Conventions](https://www.baeldung.com/java-interface-naming-conventions)
|
- [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)
|
- [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)
|
||||||
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
2
core-java-modules/core-java-networking-5/README.md
Normal file
2
core-java-modules/core-java-networking-5/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
## Relevant Articles:
|
||||||
|
- [[<-- Prev]](/core-java-modules/core-java-networking-4)
|
59
core-java-modules/core-java-networking-5/pom.xml
Normal file
59
core-java-modules/core-java-networking-5/pom.xml
Normal 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>
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
@ -5,73 +5,70 @@ import org.junit.Test;
|
|||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
public class SymmetricSubstringMaxLengthUnitTest {
|
public class SymmetricSubstringMaxLengthUnitTest {
|
||||||
String input = "<><??>>";
|
String input = "abba";
|
||||||
int expected = 4;
|
int expected = 4;
|
||||||
|
|
||||||
@Test
|
static int findLongestSymmetricSubstringUsingSymmetricApproach(String str) {
|
||||||
public void givenString_whenUsingSymmetricSubstringExpansion_thenFindLongestSymmetricSubstring() {
|
int maxLength = 1;
|
||||||
int start = 0;
|
|
||||||
int mid = 0;
|
|
||||||
int last_gt = 0;
|
|
||||||
int end = 0;
|
|
||||||
int best = 0;
|
|
||||||
|
|
||||||
while (start < input.length()) {
|
for (int i = 0; i < str.length(); i++) {
|
||||||
int current = Math.min(mid - start, end - mid);
|
for (int j = i; j < str.length(); j++) {
|
||||||
if (best < current) {
|
int flag = 1;
|
||||||
best = current;
|
for (int k = 0; k < (j - i + 1) / 2; k++) {
|
||||||
}
|
if (str.charAt(i + k) != str.charAt(j - k)) {
|
||||||
|
flag = 0;
|
||||||
if (end - mid == current && end < input.length()) {
|
break;
|
||||||
if (input.charAt(end) == '?') {
|
}
|
||||||
end++;
|
}
|
||||||
} else if (input.charAt(end) == '>') {
|
if (flag != 0 && (j - i + 1) > maxLength) {
|
||||||
end++;
|
maxLength = j - i + 1;
|
||||||
last_gt = end;
|
|
||||||
} else {
|
|
||||||
end++;
|
|
||||||
mid = end;
|
|
||||||
start = Math.max(start, last_gt);
|
|
||||||
}
|
}
|
||||||
} 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;
|
return maxLength;
|
||||||
|
|
||||||
assertEquals(expected, result);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenUsingBruteForce_thenFindLongestSymmetricSubstring() {
|
public void givenString_whenUsingBruteForce_thenFindLongestSymmetricSubstring() {
|
||||||
int max = 0;
|
assertEquals(expected, findLongestSymmetricSubstringUsingBruteForce(input).length());
|
||||||
for (int i = 0; i < input.length(); i++) {
|
}
|
||||||
for (int j = i + 1; j <= input.length(); j++) {
|
|
||||||
String t = input.substring(i, j);
|
@Test
|
||||||
if (t.length() % 2 == 0) {
|
public void givenString_whenUsingSymmetricSubstring_thenFindLongestSymmetricSubstring() {
|
||||||
int k = 0, l = t.length() - 1;
|
assertEquals(expected, findLongestSymmetricSubstringUsingSymmetricApproach(input));
|
||||||
boolean isSym = true;
|
}
|
||||||
while (k < l && isSym) {
|
|
||||||
if (!(t.charAt(k) == '<' || t.charAt(k) == '?') && (t.charAt(l) == '>' || t.charAt(l) == '?')) {
|
private String findLongestSymmetricSubstringUsingBruteForce(String str) {
|
||||||
isSym = false;
|
if (str == null || str.length() == 0) {
|
||||||
}
|
return "";
|
||||||
k++;
|
}
|
||||||
l--;
|
|
||||||
}
|
int maxLength = 0;
|
||||||
if (isSym) {
|
String longestPalindrome = "";
|
||||||
max = Math.max(max, t.length());
|
|
||||||
}
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -165,6 +165,7 @@
|
|||||||
<module>core-java-networking</module>
|
<module>core-java-networking</module>
|
||||||
<module>core-java-networking-2</module>
|
<module>core-java-networking-2</module>
|
||||||
<module>core-java-networking-4</module>
|
<module>core-java-networking-4</module>
|
||||||
|
<module>core-java-networking-5</module>
|
||||||
<module>core-java-nio</module>
|
<module>core-java-nio</module>
|
||||||
<module>core-java-nio-2</module>
|
<module>core-java-nio-2</module>
|
||||||
<module>core-java-numbers</module>
|
<module>core-java-numbers</module>
|
||||||
|
@ -20,7 +20,7 @@
|
|||||||
<!-- Boot version compatible with spqr-boot-starter -->
|
<!-- Boot version compatible with spqr-boot-starter -->
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-dependencies</artifactId>
|
<artifactId>spring-boot-dependencies</artifactId>
|
||||||
<version>2.6.4</version>
|
<version>2.6.15</version>
|
||||||
<type>pom</type>
|
<type>pom</type>
|
||||||
<scope>import</scope>
|
<scope>import</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
@ -34,4 +34,11 @@
|
|||||||
<module>graphql-spqr-boot-starter</module>
|
<module>graphql-spqr-boot-starter</module>
|
||||||
</modules>
|
</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>
|
</project>
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -60,7 +60,7 @@
|
|||||||
<properties>
|
<properties>
|
||||||
<h2.version>2.1.214</h2.version>
|
<h2.version>2.1.214</h2.version>
|
||||||
<json-path.version>5.4.0</json-path.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>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -1,9 +1,9 @@
|
|||||||
package com.baeldung.jackson.jsonignorevstransient;
|
package com.baeldung.jackson.jsonignorevstransient;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import javax.persistence.Table;
|
import jakarta.persistence.Table;
|
||||||
import javax.persistence.Transient;
|
import jakarta.persistence.Transient;
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
|
@ -31,9 +31,9 @@
|
|||||||
<jhipster.server.version>1.1.0</jhipster.server.version>
|
<jhipster.server.version>1.1.0</jhipster.server.version>
|
||||||
<jjwt.version>0.12.3</jjwt.version>
|
<jjwt.version>0.12.3</jjwt.version>
|
||||||
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.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-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>
|
<logstash-logback-encoder.version>4.8</logstash-logback-encoder.version>
|
||||||
<m2e.apt.activation>jdt_apt</m2e.apt.activation>
|
<m2e.apt.activation>jdt_apt</m2e.apt.activation>
|
||||||
<mapstruct.version>1.1.0.Final</mapstruct.version>
|
<mapstruct.version>1.1.0.Final</mapstruct.version>
|
||||||
|
@ -1,10 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<databaseChangeLog
|
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
|
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">
|
||||||
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">
|
|
||||||
|
|
||||||
<property name="now" value="now()" dbms="h2"/>
|
<property name="now" value="now()" dbms="h2"/>
|
||||||
<property name="now" value="now()" dbms="mysql"/>
|
<property name="now" value="now()" dbms="mysql"/>
|
||||||
|
@ -1,10 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<databaseChangeLog
|
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
|
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">
|
||||||
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">
|
|
||||||
|
|
||||||
<property name="now" value="now()" dbms="h2"/>
|
<property name="now" value="now()" dbms="h2"/>
|
||||||
|
|
||||||
@ -36,6 +32,6 @@
|
|||||||
|
|
||||||
<!-- jhipster-needle-liquibase-add-column - JHipster will add columns here, do not remove-->
|
<!-- jhipster-needle-liquibase-add-column - JHipster will add columns here, do not remove-->
|
||||||
</createTable>
|
</createTable>
|
||||||
|
|
||||||
</changeSet>
|
</changeSet>
|
||||||
</databaseChangeLog>
|
</databaseChangeLog>
|
||||||
|
@ -1,9 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<databaseChangeLog
|
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
|
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">
|
||||||
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">
|
|
||||||
|
|
||||||
<include file="classpath:config/liquibase/changelog/00000000000000_initial_schema.xml" relativeToChangelogFile="false"/>
|
<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"/>
|
<include file="classpath:config/liquibase/changelog/20170503041524_added_entity_Car.xml" relativeToChangelogFile="false"/>
|
||||||
<!-- jhipster-needle-liquibase-add-changelog - JHipster will add liquibase changelogs here -->
|
<!-- jhipster-needle-liquibase-add-changelog - JHipster will add liquibase changelogs here -->
|
||||||
|
@ -85,7 +85,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.mockito</groupId>
|
<groupId>org.mockito</groupId>
|
||||||
<artifactId>mockito-inline</artifactId>
|
<artifactId>mockito-inline</artifactId>
|
||||||
<version>${mockito.version}</version>
|
<version>${mockito-inline.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -120,6 +120,7 @@
|
|||||||
<reactive.stream.version>1.0.3</reactive.stream.version>
|
<reactive.stream.version>1.0.3</reactive.stream.version>
|
||||||
<reactor.version>3.6.0</reactor.version>
|
<reactor.version>3.6.0</reactor.version>
|
||||||
<jmockit.version>1.49</jmockit.version>
|
<jmockit.version>1.49</jmockit.version>
|
||||||
|
<mockito-inline.version>5.2.0</mockito-inline.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -49,11 +49,23 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<jool.version>0.9.12</jool.version>
|
<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>
|
<vavr.version>0.9.0</vavr.version>
|
||||||
<eclipse-collections.version>8.2.0</eclipse-collections.version>
|
<eclipse-collections.version>8.2.0</eclipse-collections.version>
|
||||||
<streamex.version>0.8.1</streamex.version>
|
<streamex.version>0.8.1</streamex.version>
|
||||||
<protonpack.version>1.15</protonpack.version>
|
<protonpack.version>1.15</protonpack.version>
|
||||||
</properties>
|
</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>
|
</project>
|
||||||
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -78,40 +78,20 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<profiles>
|
|
||||||
<profile>
|
<build>
|
||||||
<id>integration-lite-first</id>
|
<plugins>
|
||||||
<build>
|
<plugin>
|
||||||
<plugins>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<plugin>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<configuration>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<systemPropertyVariables>
|
||||||
<configuration>
|
<logback.configurationFile>${project.basedir}/src/test/resources/logback-test.xml</logback.configurationFile>
|
||||||
<systemPropertyVariables>
|
</systemPropertyVariables>
|
||||||
<logback.configurationFile>${project.basedir}/src/test/resources/logback-test.xml</logback.configurationFile>
|
</configuration>
|
||||||
</systemPropertyVariables>
|
</plugin>
|
||||||
</configuration>
|
</plugins>
|
||||||
</plugin>
|
</build>
|
||||||
</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>
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<json.version>20240303</json.version>
|
<json.version>20240303</json.version>
|
||||||
|
@ -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)
|
- [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)
|
- [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)
|
- [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)
|
||||||
|
|
||||||
|
@ -44,7 +44,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.mockito</groupId>
|
<groupId>org.mockito</groupId>
|
||||||
<artifactId>mockito-core</artifactId>
|
<artifactId>mockito-core</artifactId>
|
||||||
<version>${mockito-core.version}</version>
|
<version>${mockito.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -83,7 +83,6 @@
|
|||||||
<activemq.version>5.14.1</activemq.version>
|
<activemq.version>5.14.1</activemq.version>
|
||||||
<spring-boot-test.version>1.5.10.RELEASE</spring-boot-test.version>
|
<spring-boot-test.version>1.5.10.RELEASE</spring-boot-test.version>
|
||||||
<maven-war-plugin.version>3.3.2</maven-war-plugin.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>
|
<activemq-junit.version>5.16.5</activemq-junit.version>
|
||||||
<testcontainers.version>1.17.3</testcontainers.version>
|
<testcontainers.version>1.17.3</testcontainers.version>
|
||||||
<junit-jupiter.version>5.10.1</junit-jupiter.version>
|
<junit-jupiter.version>5.10.1</junit-jupiter.version>
|
||||||
|
@ -34,7 +34,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springdoc</groupId>
|
<groupId>org.springdoc</groupId>
|
||||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||||
<version>${spring.webmvc.version}</version>
|
<version>${springdoc-openapi-webmvc-ui.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -71,6 +71,7 @@
|
|||||||
<java.version>17</java.version>
|
<java.version>17</java.version>
|
||||||
<conductor.client.version>2.0.8</conductor.client.version>
|
<conductor.client.version>2.0.8</conductor.client.version>
|
||||||
<spring.webmvc.version>2.1.0</spring.webmvc.version>
|
<spring.webmvc.version>2.1.0</spring.webmvc.version>
|
||||||
|
<springdoc-openapi-webmvc-ui.version>2.5.0</springdoc-openapi-webmvc-ui.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -107,6 +107,8 @@
|
|||||||
<spring-boot.version>2.7.11</spring-boot.version>
|
<spring-boot.version>2.7.11</spring-boot.version>
|
||||||
<aspectj.version>1.9.20.1</aspectj.version>
|
<aspectj.version>1.9.20.1</aspectj.version>
|
||||||
<mysql-connector-java.version>8.2.0</mysql-connector-java.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>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -47,12 +47,12 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-api</artifactId>
|
<artifactId>slf4j-api</artifactId>
|
||||||
<version>${slf4j.version}</version>
|
<version>${org.slf4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>jcl-over-slf4j</artifactId>
|
<artifactId>jcl-over-slf4j</artifactId>
|
||||||
<version>${slf4j.version}</version>
|
<version>${org.slf4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
@ -232,8 +232,6 @@
|
|||||||
<spring-boot.version>3.1.5</spring-boot.version>
|
<spring-boot.version>3.1.5</spring-boot.version>
|
||||||
<junit-jupiter.version>5.8.2</junit-jupiter.version>
|
<junit-jupiter.version>5.8.2</junit-jupiter.version>
|
||||||
<native-build-tools-plugin.version>0.9.17</native-build-tools-plugin.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>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -15,13 +15,75 @@
|
|||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencyManagement>
|
||||||
<dependency>
|
<dependencies>
|
||||||
<groupId>org.springframework</groupId>
|
<dependency>
|
||||||
<artifactId>spring-core</artifactId>
|
<groupId>org.springframework</groupId>
|
||||||
<version>${spring.version}</version>
|
<artifactId>spring-core</artifactId>
|
||||||
</dependency>
|
<version>${spring.version}</version>
|
||||||
</dependencies>
|
</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>
|
<properties>
|
||||||
<spring.version>5.3.28</spring.version>
|
<spring.version>5.3.28</spring.version>
|
||||||
|
@ -72,6 +72,8 @@
|
|||||||
<spring-integration-test.version>5.5.14</spring-integration-test.version>
|
<spring-integration-test.version>5.5.14</spring-integration-test.version>
|
||||||
<camel-core.version>3.20.4</camel-core.version>
|
<camel-core.version>3.20.4</camel-core.version>
|
||||||
<camel-test-junit5.version>3.14.0</camel-test-junit5.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>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -16,9 +16,18 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.mockito</groupId>
|
<groupId>org.mockito</groupId>
|
||||||
<artifactId>mockito-inline</artifactId>
|
<artifactId>mockito-inline</artifactId>
|
||||||
<version>${mockito.version}</version>
|
<version>${mockito-inline.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>1.18.32</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
</project>
|
<properties>
|
||||||
|
<mockito-inline.version>5.2.0</mockito-inline.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
||||||
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
||||||
|
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
@ -3,7 +3,6 @@
|
|||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>monkey-patching</artifactId>
|
<artifactId>monkey-patching</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
<name>monkey-patching</name>
|
<name>monkey-patching</name>
|
||||||
@ -19,12 +18,12 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
<version>2.7.0</version>
|
<version>${spring-boot.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
<version>2.7.0</version>
|
<version>${spring-boot.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
@ -45,5 +44,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<spring-boot.version>2.7.0</spring-boot.version>
|
<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>
|
</properties>
|
||||||
</project>
|
</project>
|
||||||
|
42
persistence-modules/duckdb/pom.xml
Normal file
42
persistence-modules/duckdb/pom.xml
Normal 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>
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
11
persistence-modules/duckdb/src/test/resources/customer.csv
Normal file
11
persistence-modules/duckdb/src/test/resources/customer.csv
Normal 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
|
|
17
persistence-modules/duckdb/src/test/resources/product.json
Normal file
17
persistence-modules/duckdb/src/test/resources/product.json
Normal 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"
|
||||||
|
}
|
||||||
|
]
|
6
persistence-modules/hibernate-annotations-2/README.md
Normal file
6
persistence-modules/hibernate-annotations-2/README.md
Normal 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)
|
109
persistence-modules/hibernate-annotations-2/pom.xml
Normal file
109
persistence-modules/hibernate-annotations-2/pom.xml
Normal 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>
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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
|
||||||
|
|
@ -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() {
|
||||||
|
}
|
||||||
|
}
|
@ -1,6 +1,6 @@
|
|||||||
package com.baeldung.hibernate.subselect;
|
package com.baeldung.hibernate.subselect;
|
||||||
|
|
||||||
import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil;
|
import com.baeldung.hibernate.HibernateAnnotationUtil;
|
||||||
import jakarta.persistence.criteria.Root;
|
import jakarta.persistence.criteria.Root;
|
||||||
import liquibase.Contexts;
|
import liquibase.Contexts;
|
||||||
import liquibase.LabelExpression;
|
import liquibase.LabelExpression;
|
@ -4,7 +4,6 @@ import com.baeldung.hibernate.oneToMany.model.Cart;
|
|||||||
import com.baeldung.hibernate.oneToMany.model.CartOIO;
|
import com.baeldung.hibernate.oneToMany.model.CartOIO;
|
||||||
import com.baeldung.hibernate.oneToMany.model.Item;
|
import com.baeldung.hibernate.oneToMany.model.Item;
|
||||||
import com.baeldung.hibernate.oneToMany.model.ItemOIO;
|
import com.baeldung.hibernate.oneToMany.model.ItemOIO;
|
||||||
import com.baeldung.hibernate.subselect.RuntimeConfiguration;
|
|
||||||
import org.hibernate.SessionFactory;
|
import org.hibernate.SessionFactory;
|
||||||
import org.hibernate.boot.Metadata;
|
import org.hibernate.boot.Metadata;
|
||||||
import org.hibernate.boot.MetadataSources;
|
import org.hibernate.boot.MetadataSources;
|
||||||
@ -39,7 +38,6 @@ public class HibernateAnnotationUtil {
|
|||||||
.addAnnotatedClass(CartOIO.class)
|
.addAnnotatedClass(CartOIO.class)
|
||||||
.addAnnotatedClass(Item.class)
|
.addAnnotatedClass(Item.class)
|
||||||
.addAnnotatedClass(ItemOIO.class)
|
.addAnnotatedClass(ItemOIO.class)
|
||||||
.addAnnotatedClass(RuntimeConfiguration.class)
|
|
||||||
.buildMetadata();
|
.buildMetadata();
|
||||||
|
|
||||||
return metadata.buildSessionFactory();
|
return metadata.buildSessionFactory();
|
||||||
|
@ -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.Bookauthor;
|
||||||
import com.baeldung.jooq.jointables.public_.tables.Store;
|
import com.baeldung.jooq.jointables.public_.tables.Store;
|
||||||
|
|
||||||
public class JoinTablesIntegrationTest {
|
public class JoinTablesLiveTest {
|
||||||
|
|
||||||
static DSLContext context;
|
static DSLContext context;
|
||||||
|
|
@ -24,6 +24,7 @@
|
|||||||
<module>core-java-persistence-2</module>
|
<module>core-java-persistence-2</module>
|
||||||
<module>core-java-persistence-3</module>
|
<module>core-java-persistence-3</module>
|
||||||
<module>couchbase</module>
|
<module>couchbase</module>
|
||||||
|
<module>duckdb</module>
|
||||||
<module>elasticsearch</module>
|
<module>elasticsearch</module>
|
||||||
<module>flyway</module>
|
<module>flyway</module>
|
||||||
<module>flyway-repair</module>
|
<module>flyway-repair</module>
|
||||||
@ -68,6 +69,7 @@
|
|||||||
<module>spring-boot-persistence-mongodb</module>
|
<module>spring-boot-persistence-mongodb</module>
|
||||||
<module>spring-boot-persistence-mongodb-2</module>
|
<module>spring-boot-persistence-mongodb-2</module>
|
||||||
<module>spring-boot-persistence-mongodb-3</module>
|
<module>spring-boot-persistence-mongodb-3</module>
|
||||||
|
<module>spring-boot-persistence-mongodb-4</module>
|
||||||
<module>spring-data-arangodb</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</module>--> <!-- failing after upgrading to jdk17. JDK 17 compatibility in progress CASSANDRA-16895 -->
|
||||||
<module>spring-data-cassandra-test</module>
|
<module>spring-data-cassandra-test</module>
|
||||||
|
@ -60,6 +60,11 @@
|
|||||||
<version>${lombok.version}</version>
|
<version>${lombok.version}</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-tx</artifactId>
|
||||||
|
<version>${spring.tx.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -84,6 +89,7 @@
|
|||||||
<modelmapper.version>3.2.0</modelmapper.version>
|
<modelmapper.version>3.2.0</modelmapper.version>
|
||||||
<commons-codec.version>1.16.1</commons-codec.version>
|
<commons-codec.version>1.16.1</commons-codec.version>
|
||||||
<lombok.version>1.18.30</lombok.version>
|
<lombok.version>1.18.30</lombok.version>
|
||||||
|
<spring.tx.version>6.1.4</spring.tx.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -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;
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
package com.baeldung.transactionalandasync;
|
||||||
|
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
public interface AccountRepository extends JpaRepository<Account, Long> {
|
||||||
|
}
|
@ -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
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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)
|
@ -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>
|
@ -1,5 +1,6 @@
|
|||||||
package com.baeldung.mongodb.dbref;
|
package com.baeldung.mongodb.dbref;
|
||||||
|
|
||||||
|
import com.baeldung.mongodb.dbref.repository.PersonRepository;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
@ -7,8 +8,6 @@ import org.springframework.boot.ApplicationArguments;
|
|||||||
import org.springframework.boot.ApplicationRunner;
|
import org.springframework.boot.ApplicationRunner;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import com.baeldung.mongodb.dbref.repository.PersonRepository;
|
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
public class DbRefTester implements ApplicationRunner {
|
public class DbRefTester implements ApplicationRunner {
|
||||||
|
|
@ -1,11 +1,11 @@
|
|||||||
package com.baeldung.mongodb.dbref.model;
|
package com.baeldung.mongodb.dbref.model;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.springframework.data.annotation.Id;
|
import org.springframework.data.annotation.Id;
|
||||||
import org.springframework.data.mongodb.core.mapping.DBRef;
|
import org.springframework.data.mongodb.core.mapping.DBRef;
|
||||||
import org.springframework.data.mongodb.core.mapping.Document;
|
import org.springframework.data.mongodb.core.mapping.Document;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Document(collection = "Person")
|
@Document(collection = "Person")
|
||||||
public class Person {
|
public class Person {
|
||||||
|
|
@ -1,8 +1,7 @@
|
|||||||
package com.baeldung.mongodb.dbref.repository;
|
package com.baeldung.mongodb.dbref.repository;
|
||||||
|
|
||||||
import org.springframework.data.mongodb.repository.MongoRepository;
|
|
||||||
|
|
||||||
import com.baeldung.mongodb.dbref.model.Person;
|
import com.baeldung.mongodb.dbref.model.Person;
|
||||||
|
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||||
|
|
||||||
public interface PersonRepository extends MongoRepository<Person, String> {
|
public interface PersonRepository extends MongoRepository<Person, String> {
|
||||||
|
|
@ -1,15 +1,14 @@
|
|||||||
package com.baeldung.zoneddatetime.config;
|
package com.baeldung.zoneddatetime.config;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import com.baeldung.zoneddatetime.converter.ZonedDateTimeReadConverter;
|
||||||
import java.util.List;
|
import com.baeldung.zoneddatetime.converter.ZonedDateTimeWriteConverter;
|
||||||
|
|
||||||
import org.springframework.core.convert.converter.Converter;
|
import org.springframework.core.convert.converter.Converter;
|
||||||
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
|
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
|
||||||
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
|
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
|
||||||
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
|
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
|
||||||
|
|
||||||
import com.baeldung.zoneddatetime.converter.ZonedDateTimeReadConverter;
|
import java.util.ArrayList;
|
||||||
import com.baeldung.zoneddatetime.converter.ZonedDateTimeWriteConverter;
|
import java.util.List;
|
||||||
|
|
||||||
@EnableMongoRepositories(basePackages = { "com.baeldung" })
|
@EnableMongoRepositories(basePackages = { "com.baeldung" })
|
||||||
public class MongoConfig extends AbstractMongoClientConfiguration {
|
public class MongoConfig extends AbstractMongoClientConfiguration {
|
@ -1,7 +1,6 @@
|
|||||||
package com.baeldung.zoneddatetime.repository;
|
package com.baeldung.zoneddatetime.repository;
|
||||||
|
|
||||||
|
import com.baeldung.zoneddatetime.model.Action;
|
||||||
import org.springframework.data.mongodb.repository.MongoRepository;
|
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||||
|
|
||||||
import com.baeldung.zoneddatetime.model.Action;
|
|
||||||
|
|
||||||
public interface ActionRepository extends MongoRepository<Action, String> { }
|
public interface ActionRepository extends MongoRepository<Action, String> { }
|
@ -0,0 +1 @@
|
|||||||
|
spring.application.name=spring-boot-persistence-mongodb-4
|
@ -1,11 +1,11 @@
|
|||||||
package com.baeldung.mongodb.dbref;
|
package com.baeldung.mongodb.dbref;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import com.baeldung.mongodb.dbref.model.Person;
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import com.baeldung.mongodb.dbref.model.Pet;
|
||||||
|
import com.baeldung.mongodb.dbref.repository.PersonRepository;
|
||||||
import java.util.ArrayList;
|
import com.mongodb.BasicDBObjectBuilder;
|
||||||
import java.util.List;
|
import com.mongodb.DBObject;
|
||||||
|
import com.mongodb.DBRef;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
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.annotation.DirtiesContext;
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
import com.baeldung.mongodb.dbref.model.Person;
|
import java.util.ArrayList;
|
||||||
import com.baeldung.mongodb.dbref.model.Pet;
|
import java.util.List;
|
||||||
import com.baeldung.mongodb.dbref.repository.PersonRepository;
|
|
||||||
import com.mongodb.BasicDBObjectBuilder;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import com.mongodb.DBObject;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import com.mongodb.DBRef;
|
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest
|
@SpringBootTest
|
@ -1,5 +1,8 @@
|
|||||||
package com.baeldung.zoneddatetime;
|
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.After;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Before;
|
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.ContextConfiguration;
|
||||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
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.ZoneOffset;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
|
@ -0,0 +1 @@
|
|||||||
|
spring.mongodb.embedded.version=4.4.9
|
@ -4,8 +4,6 @@
|
|||||||
- [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb)
|
- [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)
|
- [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)
|
- [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)
|
- [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)
|
- [Spring Data MongoDB – Configure Connection](https://www.baeldung.com/spring-data-mongodb-connection)
|
||||||
- More articles: [[next-->]](../spring-boot-persistence-mongodb-2)
|
- More articles: [[next-->]](../spring-boot-persistence-mongodb-2)
|
||||||
|
@ -70,7 +70,6 @@
|
|||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<mockito.version>2.23.0</mockito.version>
|
|
||||||
<validation-api.version>2.0.1.Final</validation-api.version>
|
<validation-api.version>2.0.1.Final</validation-api.version>
|
||||||
<mysql-connector-java.version>8.2.0</mysql-connector-java.version>
|
<mysql-connector-java.version>8.2.0</mysql-connector-java.version>
|
||||||
<start-class>com.baeldung.boot.Application</start-class>
|
<start-class>com.baeldung.boot.Application</start-class>
|
||||||
|
@ -136,6 +136,12 @@
|
|||||||
<type>so</type>
|
<type>so</type>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>net.bytebuddy</groupId>
|
||||||
|
<artifactId>byte-buddy</artifactId>
|
||||||
|
<version>1.14.13</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -5,8 +5,6 @@ import org.junit.runner.RunWith;
|
|||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
import com.baeldung.Application;
|
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest(classes = Application.class)
|
@SpringBootTest(classes = Application.class)
|
||||||
public class SpringContextTest {
|
public class SpringContextTest {
|
||||||
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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();
|
||||||
|
}
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
@ -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
Loading…
x
Reference in New Issue
Block a user