Merge branch 'master' into feature/BAEL-7419-how-to-mock-aws-s3-for-integration-test
This commit is contained in:
commit
b06e7c2777
|
@ -64,13 +64,13 @@ core-java-io/hard_link.txt
|
|||
core-java-io/target_link.txt
|
||||
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
|
||||
ethereum/logs/
|
||||
jmeter/src/main/resources/*-JMeter.csv
|
||||
jmeter/src/main/resources/*-Basic*.csv
|
||||
jmeter/src/main/resources/*-JMeter*.csv
|
||||
jmeter/src/main/resources/*ReportsDashboard*.csv
|
||||
jmeter/src/main/resources/dashboard/*ReportsDashboard*.csv
|
||||
jmeter/src/main/resources/*FileExtractionExample.csv
|
||||
jmeter/src/main/resources/*_Summary-Report.csv
|
||||
testing-modules/jmeter/src/main/resources/*-JMeter.csv
|
||||
testing-modules/jmeter/src/main/resources/*-Basic*.csv
|
||||
testing-modules/jmeter/src/main/resources/*-JMeter*.csv
|
||||
testing-modules/jmeter/src/main/resources/*ReportsDashboard*.csv
|
||||
testing-modules/jmeter/src/main/resources/dashboard/*ReportsDashboard*.csv
|
||||
testing-modules/jmeter/src/main/resources/*FileExtractionExample.csv
|
||||
testing-modules/jmeter/src/main/resources/*_Summary-Report.csv
|
||||
|
||||
ninja/devDb.mv.db
|
||||
|
||||
|
@ -128,3 +128,6 @@ persistence-modules/neo4j/data/**
|
|||
/deep-shallow-copy/.mvn/wrapper
|
||||
/deep-shallow-copy/mvnw
|
||||
/deep-shallow-copy/mvnw.cmd
|
||||
|
||||
#spring-5-webflux-2
|
||||
**/testdb.mv.db
|
|
@ -14,16 +14,6 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
|
|
|
@ -1,7 +1,5 @@
|
|||
package com.baeldung.algorithms;
|
||||
|
||||
|
||||
|
||||
import com.baeldung.algorithms.ga.dijkstra.Dijkstra;
|
||||
import com.baeldung.algorithms.ga.dijkstra.Graph;
|
||||
import com.baeldung.algorithms.ga.dijkstra.Node;
|
||||
|
|
|
@ -6,4 +6,6 @@
|
|||
- [Calculate Distance Between Two Coordinates in Java](https://www.baeldung.com/java-find-distance-between-points)
|
||||
- [Rotate Arrays in Java](https://www.baeldung.com/java-rotate-arrays)
|
||||
- [Find Missing Number From a Given Array in Java](https://www.baeldung.com/java-array-find-missing-number)
|
||||
- [Calculate Weighted Mean in Java](https://www.baeldung.com/java-compute-weighted-average)
|
||||
- [Check if Two Strings Are Rotations of Each Other](https://www.baeldung.com/java-string-check-strings-rotations)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
|
||||
|
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.algorithms.primeundernumber;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class LargestPrimeFinder {
|
||||
|
||||
public static int findByBruteForce(int n) {
|
||||
for (int i = n - 1; i >= 2; i--) {
|
||||
if (isPrime(i)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1; // Return -1 if no prime number is found
|
||||
}
|
||||
|
||||
public static boolean isPrime(int number) {
|
||||
for (int i = 2; i <= Math.sqrt(number); i++) {
|
||||
if (number % i == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static int findBySieveOfEratosthenes(int n) {
|
||||
boolean[] isPrime = new boolean[n];
|
||||
Arrays.fill(isPrime, true);
|
||||
for (int p = 2; p*p < n; p++) {
|
||||
if (isPrime[p]) {
|
||||
for (int i = p * p; i < n; i += p) {
|
||||
isPrime[i] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = n - 1; i >= 2; i--) {
|
||||
if (isPrime[i]) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,123 @@
|
|||
package com.baeldung.algorithms.stringrotation;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class StringRotation {
|
||||
|
||||
public static boolean doubledOriginContainsRotation(String origin, String rotation) {
|
||||
if (origin.length() == rotation.length()) {
|
||||
return origin.concat(origin)
|
||||
.contains(rotation);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean isRotationUsingCommonStartWithOrigin(String origin, String rotation) {
|
||||
|
||||
if (origin.length() == rotation.length()) {
|
||||
|
||||
List<Integer> indexes = IntStream.range(0, origin.length())
|
||||
.filter(i -> rotation.charAt(i) == origin.charAt(0))
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
for (int startingAt : indexes) {
|
||||
if (isRotation(startingAt, rotation, origin)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static boolean isRotation(int startingAt, String rotation, String origin) {
|
||||
|
||||
for (int i = 0; i < origin.length(); i++) {
|
||||
if (rotation.charAt((startingAt + i) % origin.length()) != origin.charAt(i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isRotationUsingQueue(String origin, String rotation) {
|
||||
|
||||
if (origin.length() == rotation.length()) {
|
||||
return checkWithQueue(origin, rotation);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static boolean checkWithQueue(String origin, String rotation) {
|
||||
|
||||
if (origin.length() == rotation.length()) {
|
||||
|
||||
Queue<Character> originQueue = getCharactersQueue(origin);
|
||||
|
||||
Queue<Character> rotationQueue = getCharactersQueue(rotation);
|
||||
|
||||
int k = rotation.length();
|
||||
while (k > 0 && null != rotationQueue.peek()) {
|
||||
k--;
|
||||
char ch = rotationQueue.peek();
|
||||
rotationQueue.remove();
|
||||
rotationQueue.add(ch);
|
||||
if (rotationQueue.equals(originQueue)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static Queue<Character> getCharactersQueue(String origin) {
|
||||
return origin.chars()
|
||||
.mapToObj(c -> (char) c)
|
||||
.collect(Collectors.toCollection(LinkedList::new));
|
||||
}
|
||||
|
||||
public static boolean isRotationUsingSuffixAndPrefix(String origin, String rotation) {
|
||||
|
||||
if (origin.length() == rotation.length()) {
|
||||
return checkPrefixAndSuffix(origin, rotation);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static boolean checkPrefixAndSuffix(String origin, String rotation) {
|
||||
if (origin.length() == rotation.length()) {
|
||||
|
||||
for (int i = 0; i < origin.length(); i++) {
|
||||
if (origin.charAt(i) == rotation.charAt(0)) {
|
||||
if (checkRotationPrefixWithOriginSuffix(origin, rotation, i)) {
|
||||
if (checkOriginPrefixWithRotationSuffix(origin, rotation, i))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean checkRotationPrefixWithOriginSuffix(String origin, String rotation, int i) {
|
||||
return origin.substring(i)
|
||||
.equals(rotation.substring(0, origin.length() - i));
|
||||
}
|
||||
|
||||
private static boolean checkOriginPrefixWithRotationSuffix(String origin, String rotation, int i) {
|
||||
return origin.substring(0, i)
|
||||
.equals(rotation.substring(origin.length() - i));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.algorithms.primeundernumber;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class LargestPrimeFinderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNormalCases_whenFindPrime_ThenFoundResult() {
|
||||
assertEquals(7, LargestPrimeFinder.findByBruteForce(10));
|
||||
assertEquals(97, LargestPrimeFinder.findByBruteForce(100));
|
||||
assertEquals(7, LargestPrimeFinder.findBySieveOfEratosthenes(10));
|
||||
assertEquals(97, LargestPrimeFinder.findBySieveOfEratosthenes(100));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEdgeCases_whenFindPrime_ThenNotFoundResult() {
|
||||
assertEquals(-1, LargestPrimeFinder.findByBruteForce(0));
|
||||
assertEquals(-1, LargestPrimeFinder.findByBruteForce(1));
|
||||
assertEquals(-1, LargestPrimeFinder.findByBruteForce(2));
|
||||
assertEquals(-1, LargestPrimeFinder.findBySieveOfEratosthenes(0));
|
||||
assertEquals(-1, LargestPrimeFinder.findBySieveOfEratosthenes(1));
|
||||
assertEquals(-1, LargestPrimeFinder.findBySieveOfEratosthenes(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLargeInput_whenFindPrime_ThenFoundResult() {
|
||||
assertEquals(99991, LargestPrimeFinder.findByBruteForce(100000));
|
||||
assertEquals(99991, LargestPrimeFinder.findBySieveOfEratosthenes(100000));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.algorithms.stringrotation;
|
||||
|
||||
import static com.baeldung.algorithms.stringrotation.StringRotation.doubledOriginContainsRotation;
|
||||
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingCommonStartWithOrigin;
|
||||
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingQueue;
|
||||
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingSuffixAndPrefix;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class StringRotationUnitTest {
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckIfOriginContainsRotation_thenIsRotation() {
|
||||
assertTrue(doubledOriginContainsRotation("abcd", "cdab"));
|
||||
assertTrue(doubledOriginContainsRotation("abcd", "abcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckIfOriginContainsRotation_thenNoRotation() {
|
||||
assertFalse(doubledOriginContainsRotation("abcd", "bbbb"));
|
||||
assertFalse(doubledOriginContainsRotation("abcd", "abcde"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckingCommonStartWithOrigin_thenIsRotation() {
|
||||
assertTrue(isRotationUsingCommonStartWithOrigin("abcd", "cdab"));
|
||||
assertTrue(isRotationUsingCommonStartWithOrigin("abcd", "abcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckingCommonStartWithOrigin_thenNoRotation() {
|
||||
assertFalse(isRotationUsingCommonStartWithOrigin("abcd", "bbbb"));
|
||||
assertFalse(isRotationUsingCommonStartWithOrigin("abcd", "abcde"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckingUsingQueues_thenIsRotation() {
|
||||
assertTrue(isRotationUsingQueue("abcd", "cdab"));
|
||||
assertTrue(isRotationUsingQueue("abcd", "abcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckingUsingQueues_thenNoRotation() {
|
||||
assertFalse(isRotationUsingQueue("abcd", "bbbb"));
|
||||
assertFalse(isRotationUsingQueue("abcd", "abcde"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckingUsingSuffixAndPrefix_thenIsRotation() {
|
||||
assertTrue(isRotationUsingSuffixAndPrefix("abcd", "cdab"));
|
||||
assertTrue(isRotationUsingSuffixAndPrefix("abcd", "abcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckingUsingSuffixAndPrefix_thenNoRotation() {
|
||||
assertFalse(isRotationUsingSuffixAndPrefix("abcd", "bbbb"));
|
||||
assertFalse(isRotationUsingSuffixAndPrefix("abcd", "abcde"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,153 @@
|
|||
package com.baeldung.algorithms.weightedaverage;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BinaryOperator;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collector;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class WeightedAverageUnitTest {
|
||||
|
||||
private List<Values> values = Arrays.asList(
|
||||
new Values(1, 10),
|
||||
new Values(3, 20),
|
||||
new Values(5, 30),
|
||||
new Values(7, 50),
|
||||
new Values(9, 40)
|
||||
);
|
||||
|
||||
private Double expected = 6.2;
|
||||
|
||||
@Test
|
||||
void twoPass() {
|
||||
double top = values.stream()
|
||||
.mapToDouble(v -> v.value * v.weight)
|
||||
.sum();
|
||||
double bottom = values.stream()
|
||||
.mapToDouble(v -> v.weight)
|
||||
.sum();
|
||||
|
||||
double result = top / bottom;
|
||||
assertEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void onePass() {
|
||||
double top = 0;
|
||||
double bottom = 0;
|
||||
|
||||
for (Values v : values) {
|
||||
top += (v.value * v.weight);
|
||||
bottom += v.weight;
|
||||
}
|
||||
|
||||
double result = top / bottom;
|
||||
assertEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void expanding() {
|
||||
double result = values.stream()
|
||||
.flatMap(v -> Collections.nCopies(v.weight, v.value).stream())
|
||||
.mapToInt(v -> v)
|
||||
.average()
|
||||
.getAsDouble();
|
||||
assertEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reduce() {
|
||||
class WeightedAverage {
|
||||
final double top;
|
||||
final double bottom;
|
||||
|
||||
public WeightedAverage(double top, double bottom) {
|
||||
this.top = top;
|
||||
this.bottom = bottom;
|
||||
}
|
||||
|
||||
double average() {
|
||||
return top / bottom;
|
||||
}
|
||||
}
|
||||
|
||||
double result = values.stream()
|
||||
.reduce(new WeightedAverage(0, 0),
|
||||
(acc, next) -> new WeightedAverage(
|
||||
acc.top + (next.value * next.weight),
|
||||
acc.bottom + next.weight),
|
||||
(left, right) -> new WeightedAverage(
|
||||
left.top + right.top,
|
||||
left.bottom + right.bottom))
|
||||
.average();
|
||||
assertEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void customCollector() {
|
||||
class WeightedAverage implements Collector<Values, WeightedAverage.RunningTotals, Double> {
|
||||
class RunningTotals {
|
||||
double top;
|
||||
double bottom;
|
||||
|
||||
public RunningTotals() {
|
||||
this.top = 0;
|
||||
this.bottom = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Supplier<RunningTotals> supplier() {
|
||||
return RunningTotals::new;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BiConsumer<RunningTotals, Values> accumulator() {
|
||||
return (current, next) -> {
|
||||
current.top += (next.value * next.weight);
|
||||
current.bottom += next.weight;
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public BinaryOperator<RunningTotals> combiner() {
|
||||
return (left, right) -> {
|
||||
left.top += right.top;
|
||||
left.bottom += right.bottom;
|
||||
|
||||
return left;
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Function<RunningTotals, Double> finisher() {
|
||||
return rt -> rt.top / rt.bottom;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Characteristics> characteristics() {
|
||||
return Collections.singleton(Characteristics.UNORDERED);
|
||||
}
|
||||
}
|
||||
|
||||
double result = values.stream()
|
||||
.collect(new WeightedAverage());
|
||||
assertEquals(expected, result);
|
||||
}
|
||||
|
||||
private static class Values {
|
||||
int value;
|
||||
int weight;
|
||||
|
||||
public Values(int value, int weight) {
|
||||
this.value = value;
|
||||
this.weight = weight;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -13,3 +13,4 @@ This module contains articles about searching algorithms.
|
|||
- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search)
|
||||
- [Fast Pattern Matching of Strings Using Suffix Tree in Java](https://www.baeldung.com/java-pattern-matching-suffix-tree)
|
||||
- [Find the Kth Smallest Element in Two Sorted Arrays in Java](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)
|
||||
- [Find the First Non-repeating Element of a List](https://www.baeldung.com/java-list-find-first-non-repeating-element)
|
||||
|
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.algorithms.firstnonrepeating;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class FirstNonRepeatingElement {
|
||||
public static Integer findFirstNonRepeatingUsingForLoop(List<Integer> list) {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
int current = list.get(i);
|
||||
boolean isRepeating = false;
|
||||
for (int j = 0; j < list.size(); j++) {
|
||||
if (i != j && current == list.get(j)) {
|
||||
isRepeating = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!isRepeating) {
|
||||
return current;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Integer findFirstNonRepeatedElementUsingIndex(List<Integer> list) {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
if (list.indexOf(list.get(i)) == list.lastIndexOf(list.get(i))) {
|
||||
return list.get(i);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Integer findFirstNonRepeatingUsingHashMap(List<Integer> list) {
|
||||
Map<Integer, Integer> counts = new HashMap<>();
|
||||
for (int num : list) {
|
||||
counts.put(num, counts.getOrDefault(num, 0) + 1);
|
||||
}
|
||||
for (int num : list) {
|
||||
if (counts.get(num) == 1) {
|
||||
return num;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Integer findFirstNonRepeatingUsingArray(List<Integer> list) {
|
||||
int maxElement = Collections.max(list);
|
||||
int[] frequency = new int[maxElement + 1];
|
||||
for (int num : list) {
|
||||
frequency[num]++;
|
||||
}
|
||||
for (int num : list) {
|
||||
if (frequency[num] == 1) {
|
||||
return num;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.algorithms.firstnonrepeating;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class FirstNonRepeatingElementUnitTest {
|
||||
|
||||
private List<Integer> list;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
list = Arrays.asList(1, 2, 3, 2, 1, 4, 5, 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingForLoop_thenReturnFirstNonRepeatingElement() {
|
||||
int result = FirstNonRepeatingElement.findFirstNonRepeatingUsingForLoop(list);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingIndexOf_thenReturnFirstNonRepeatingElement() {
|
||||
int result = FirstNonRepeatingElement.findFirstNonRepeatedElementUsingIndex(list);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingHashMap_thenReturnFirstNonRepeatingElement() {
|
||||
int result = FirstNonRepeatingElement.findFirstNonRepeatingUsingHashMap(list);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingArray_thenReturnFirstNonRepeatingElement() {
|
||||
int result = FirstNonRepeatingElement.findFirstNonRepeatingUsingArray(list);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
}
|
|
@ -20,8 +20,4 @@
|
|||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<cxf.version>4.0.0</cxf.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -48,7 +48,6 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<cxf.version>4.0.0</cxf.version>
|
||||
<jakarta-xml.version>4.0.0</jakarta-xml.version>
|
||||
<jakarta.jws.version>3.0.0</jakarta.jws.version>
|
||||
</properties>
|
||||
|
|
|
@ -16,12 +16,12 @@
|
|||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
|
||||
<version>4.0.0</version>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-transports-http-jetty</artifactId>
|
||||
<version>4.0.0</version>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.xml.ws</groupId>
|
||||
|
|
|
@ -115,6 +115,7 @@
|
|||
</profiles>
|
||||
|
||||
<properties>
|
||||
<cxf.version>3.1.8</cxf.version>
|
||||
<spring.version>5.3.25</spring.version>
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
<jstl.version>1.2</jstl.version>
|
||||
|
|
|
@ -35,7 +35,7 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<cxf.version>3.1.8</cxf.version>
|
||||
<cxf.version>4.0.0</cxf.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -16,12 +16,12 @@
|
|||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-client</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-sse</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.ws.rs</groupId>
|
||||
|
@ -60,7 +60,6 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<cxf-version>4.0.0</cxf-version>
|
||||
<jakarta-ws.version>3.1.0</jakarta-ws.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
## Relevant Articles
|
||||
- [Understanding XSLT Processing in Java](https://www.baeldung.com/java-extensible-stylesheet-language-transformations)
|
||||
- [Add Camel Route at Runtime in Java](https://www.baeldung.com/java-camel-dynamic-route)
|
||||
|
|
|
@ -19,10 +19,29 @@
|
|||
<artifactId>validation-api</artifactId>
|
||||
<version>${javax.validation.validation-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-core</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-test-junit5</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-main</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<javax.validation.validation-api.version>2.0.1.Final</javax.validation.validation-api.version>
|
||||
<camel.version>4.3.0</camel.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.dynamicrouter;
|
||||
|
||||
import org.apache.camel.ExchangeProperties;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class DynamicRouterBean {
|
||||
public String route(String body, @ExchangeProperties Map<String, Object> properties) {
|
||||
int invoked = (int) properties.getOrDefault("invoked", 0) + 1;
|
||||
|
||||
properties.put("invoked", invoked);
|
||||
|
||||
if (invoked == 1) {
|
||||
switch (body.toLowerCase()) {
|
||||
case "mock":
|
||||
return "mock:dynamicRouter";
|
||||
case "direct":
|
||||
return "mock:directDynamicRouter";
|
||||
case "seda":
|
||||
return "mock:sedaDynamicRouter";
|
||||
case "file":
|
||||
return "mock:fileDynamicRouter";
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.dynamicrouter;
|
||||
|
||||
import org.apache.camel.builder.RouteBuilder;
|
||||
|
||||
public class DynamicRouterRoute extends RouteBuilder {
|
||||
|
||||
@Override
|
||||
public void configure() {
|
||||
|
||||
from("direct:dynamicRouter").dynamicRouter(method(DynamicRouterBean.class, "route"));
|
||||
|
||||
}
|
||||
}
|
|
@ -10,4 +10,6 @@
|
|||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
<logger name="org.apache.camel.impl.engine" level="WARN"/>
|
||||
</configuration>
|
|
@ -0,0 +1,61 @@
|
|||
package dynamicrouter;
|
||||
|
||||
import com.baeldung.dynamicrouter.DynamicRouterRoute;
|
||||
import org.apache.camel.RoutesBuilder;
|
||||
import org.apache.camel.component.mock.MockEndpoint;
|
||||
import org.apache.camel.test.junit5.CamelTestSupport;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class DynamicRouterRouteUnitTest extends CamelTestSupport {
|
||||
|
||||
@Override
|
||||
protected RoutesBuilder createRouteBuilder() {
|
||||
return new DynamicRouterRoute();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndMockAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
|
||||
|
||||
MockEndpoint mockDynamicEndpoint = getMockEndpoint("mock:dynamicRouter");
|
||||
mockDynamicEndpoint.expectedMessageCount(1);
|
||||
|
||||
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
|
||||
.setBody("mock"));
|
||||
MockEndpoint.assertIsSatisfied(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndDirectAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
|
||||
|
||||
MockEndpoint mockDynamicEndpoint = context.getEndpoint("mock:directDynamicRouter", MockEndpoint.class);
|
||||
mockDynamicEndpoint.expectedMessageCount(1);
|
||||
|
||||
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
|
||||
.setBody("direct"));
|
||||
|
||||
MockEndpoint.assertIsSatisfied(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndSedaAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
|
||||
|
||||
MockEndpoint mockDynamicEndpoint = context.getEndpoint("mock:sedaDynamicRouter", MockEndpoint.class);
|
||||
mockDynamicEndpoint.expectedMessageCount(1);
|
||||
|
||||
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
|
||||
.setBody("seda"));
|
||||
MockEndpoint.assertIsSatisfied(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndBookAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
|
||||
|
||||
MockEndpoint mockDynamicEndpoint = getMockEndpoint("mock:fileDynamicRouter");
|
||||
mockDynamicEndpoint.expectedMessageCount(1);
|
||||
|
||||
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
|
||||
.setBody("file"));
|
||||
MockEndpoint.assertIsSatisfied(context);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
<logger name="ch.qos.logback.classic.joran.action" level="WARN"/>
|
||||
</configuration>
|
|
@ -191,7 +191,7 @@
|
|||
<bval.version>2.0.6</bval.version>
|
||||
<javax.validation.validation-api.version>2.0.1.Final</javax.validation.validation-api.version>
|
||||
<meecrowave-junit.version>1.2.15</meecrowave-junit.version>
|
||||
<okhttp.version>4.12.0</okhttp.version>
|
||||
<okhttp.version>5.0.0-alpha.12</okhttp.version>
|
||||
<meecrowave-jpa.version>1.2.15</meecrowave-jpa.version>
|
||||
<meecrowave-core.version>1.2.15</meecrowave-core.version>
|
||||
<meecrowave-maven-plugin.version>1.2.15</meecrowave-maven-plugin.version>
|
||||
|
|
|
@ -14,4 +14,4 @@ This module contains articles about Apache POI.
|
|||
- [Set the Date Format Using Apache POI](https://www.baeldung.com/java-apache-poi-date-format)
|
||||
- [Replacing Variables in a Document Template with Java](https://www.baeldung.com/java-replace-pattern-word-document-doc-docx)
|
||||
- [Lock Header Rows With Apache POI](https://www.baeldung.com/java-apache-poi-lock-header-rows)
|
||||
- More articles: [[<-- prev]](../apache-poi)
|
||||
- More articles: [[<-- prev]](../apache-poi)[[next -->]](../apache-poi-3)
|
||||
|
|
|
@ -27,7 +27,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<poi.version>5.2.3</poi.version>
|
||||
<poi.version>5.2.5</poi.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,3 +1,10 @@
|
|||
## Relevant Articles
|
||||
## Apache POI
|
||||
|
||||
This module contains articles about Apache POI.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [How To Convert Excel Data Into List Of Java Objects](https://www.baeldung.com/java-convert-excel-data-into-list)
|
||||
- [Expand Columns with Apache POI](https://www.baeldung.com/java-apache-poi-expand-columns)
|
||||
- [Apply Bold Text Style for an Entire Row Using Apache POI](https://www.baeldung.com/appache-poi-apply-bold-text-style-entire-row)
|
||||
- More articles: [[<-- prev]](../apache-poi-2)
|
|
@ -24,50 +24,41 @@
|
|||
<artifactId>poi-scratchpad</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/com.github.ozlerhakan/poiji -->
|
||||
<dependency>
|
||||
<groupId>com.github.ozlerhakan</groupId>
|
||||
<artifactId>poiji</artifactId>
|
||||
<version>${poiji.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi/5.2.3 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas/4.1.2 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml-schemas</artifactId>
|
||||
<version>4.1.2</version>
|
||||
<version>${poi-ooxml-schemas.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans/5.1.1 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.xmlbeans</groupId>
|
||||
<artifactId>xmlbeans</artifactId>
|
||||
<version>5.1.1</version>
|
||||
<version>${xmlbeans.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>4.4</version>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.dhatim/fastexcel/0.15.7 -->
|
||||
<dependency>
|
||||
<groupId>org.dhatim</groupId>
|
||||
<artifactId>fastexcel</artifactId>
|
||||
<version>${fastexcel.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.dhatim/fastexcel-reader/0.15.7 -->
|
||||
<dependency>
|
||||
<groupId>org.dhatim</groupId>
|
||||
<artifactId>fastexcel-reader</artifactId>
|
||||
<version>${fastexcel.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl/2.6.12 -->
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.jexcelapi</groupId>
|
||||
<artifactId>jxl</artifactId>
|
||||
|
@ -77,8 +68,11 @@
|
|||
|
||||
<properties>
|
||||
<poi.version>5.2.5</poi.version>
|
||||
<poiji.version>4.1.1</poiji.version>
|
||||
<fastexcel.version>0.15.7</fastexcel.version>
|
||||
<poi-ooxml-schemas.version>4.1.2</poi-ooxml-schemas.version>
|
||||
<poiji.version>4.2.0</poiji.version>
|
||||
<xmlbeans.version>5.2.0</xmlbeans.version>
|
||||
<commons-collections4.version>4.4</commons-collections4.version>
|
||||
<fastexcel.version>0.17.0</fastexcel.version>
|
||||
<jxl.version>2.6.12</jxl.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -60,10 +60,10 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<poi.version>5.2.0</poi.version>
|
||||
<jexcel.version>1.0.6</jexcel.version>
|
||||
<fastexcel.version>0.15.3</fastexcel.version>
|
||||
<maven.resources.plugin.version>3.2.0</maven.resources.plugin.version>
|
||||
<poi.version>5.2.5</poi.version>
|
||||
<jexcel.version>1.0.9</jexcel.version>
|
||||
<fastexcel.version>0.17.0</fastexcel.version>
|
||||
<maven.resources.plugin.version>3.3.1</maven.resources.plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -97,7 +97,7 @@
|
|||
<json-simple.version>1.1.1</json-simple.version>
|
||||
<aws-lambda-java-events.version>3.11.0</aws-lambda-java-events.version>
|
||||
<aws-lambda-java-core.version>1.2.1</aws-lambda-java-core.version>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -31,15 +31,21 @@
|
|||
<version>${jackson-databind.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<artifactId>hibernate-hikaricp</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zaxxer</groupId>
|
||||
<artifactId>HikariCP</artifactId>
|
||||
<version>${hikari.cp.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
|
@ -70,11 +76,12 @@
|
|||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<hibernate.version>5.4.21.Final</hibernate.version>
|
||||
<hibernate.version>6.4.2.Final</hibernate.version>
|
||||
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
|
||||
<aws-lambda-java-events.version>3.1.0</aws-lambda-java-events.version>
|
||||
<jackson-databind.version>2.11.2</jackson-databind.version>
|
||||
<postgresql.version>42.2.16</postgresql.version>
|
||||
<hikari.cp.version>5.1.0</hikari.cp.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -83,7 +83,7 @@ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
|||
}
|
||||
|
||||
private static SessionFactory createSessionFactory() {
|
||||
Map<String, String> settings = new HashMap<>();
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
settings.put(URL, System.getenv("DB_URL"));
|
||||
settings.put(DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
|
||||
settings.put(DEFAULT_SCHEMA, "shipping");
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
package com.baeldung.lambda.shipping;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Embeddable;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
public class Checkin {
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
package com.baeldung.lambda.shipping;
|
||||
|
||||
import javax.persistence.*;
|
||||
import jakarta.persistence.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static javax.persistence.FetchType.EAGER;
|
||||
import static jakarta.persistence.FetchType.EAGER;
|
||||
|
||||
@Entity(name = "consignment")
|
||||
@Table(name = "consignment")
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
package com.baeldung.lambda.shipping;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Embeddable;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
public class Item {
|
||||
|
|
|
@ -37,7 +37,7 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>${maven-plugins-version}</version>
|
||||
<version>${maven-dependency-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy</id>
|
||||
|
@ -58,10 +58,7 @@
|
|||
|
||||
<properties>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<dynamodblocal.version>1.21.1</dynamodblocal.version>
|
||||
<commons-codec-version>1.16.0</commons-codec-version>
|
||||
<jets3t-version>0.9.4.0006L</jets3t-version>
|
||||
<maven-plugins-version>3.1.1</maven-plugins-version>
|
||||
<maven-dependency-plugin.version>3.1.1</maven-dependency-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -27,7 +27,7 @@
|
|||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>bom</artifactId>
|
||||
<version>${awssdk.version}</version>
|
||||
<version>${aws-java-sdk-v2.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
|
@ -93,7 +93,6 @@
|
|||
|
||||
<properties>
|
||||
<spring.version>2.2.1.RELEASE</spring.version>
|
||||
<awssdk.version>2.17.283</awssdk.version>
|
||||
<reactor.version>3.6.0</reactor.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -18,7 +18,7 @@
|
|||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>s3</artifactId>
|
||||
<version>${aws.java.sdk.version}</version>
|
||||
<version>${aws-java-sdk-v2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
|
@ -36,12 +36,12 @@
|
|||
<dependency>
|
||||
<groupId>org.lucee</groupId>
|
||||
<artifactId>jets3t</artifactId>
|
||||
<version>${jets3t-version}</version>
|
||||
<version>${jets3t.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lucee</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec-version}</version>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<!-- adobe s3mock -->
|
||||
<dependency>
|
||||
|
@ -67,10 +67,10 @@
|
|||
|
||||
<properties>
|
||||
<aws.java.sdk.version>2.20.52</aws.java.sdk.version>
|
||||
<commons-codec-version>1.10.L001</commons-codec-version>
|
||||
<jets3t-version>0.9.4.0006L</jets3t-version>
|
||||
<com.adobe.testing.version>3.3.0</com.adobe.testing.version>
|
||||
<org.testcontainers.version>1.19.4</org.testcontainers.version>
|
||||
<commons-codec.version>1.10.L001</commons-codec.version>
|
||||
<jets3t.version>0.9.4.0014L</jets3t.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -33,7 +33,7 @@
|
|||
|
||||
<properties>
|
||||
<aws-java-sdk.version>1.12.331</aws-java-sdk.version>
|
||||
<aws-java-sdk-v2.version>2.20.147</aws-java-sdk-v2.version>
|
||||
<aws-java-sdk-v2.version>2.24.9</aws-java-sdk-v2.version>
|
||||
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -157,7 +157,7 @@
|
|||
<properties>
|
||||
<groovy-wslite.version>1.1.3</groovy-wslite.version>
|
||||
<assembly.plugin.version>3.4.2</assembly.plugin.version>
|
||||
<compiler.plugin.version>3.8.1</compiler.plugin.version>
|
||||
<compiler.plugin.version>3.12.1</compiler.plugin.version>
|
||||
<groovy.compiler.version>3.9.0</groovy.compiler.version>
|
||||
<groovy-eclipse-batch.version>3.0.9-03</groovy-eclipse-batch.version>
|
||||
</properties>
|
||||
|
|
|
@ -1,61 +1,71 @@
|
|||
package com.baeldung.io
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import groovy.io.FileType
|
||||
import groovy.io.FileVisitResult
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.assertTrue
|
||||
|
||||
class TraverseFileTreeUnitTest {
|
||||
@Test
|
||||
void whenUsingEachFile_filesAreListed() {
|
||||
var files = []
|
||||
new File('src/main/resources').eachFile { file ->
|
||||
println file.name
|
||||
files.add(file.name)
|
||||
}
|
||||
assertTrue(files.size() > 1)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException)
|
||||
void whenUsingEachFileOnAFile_anErrorOccurs() {
|
||||
var files = []
|
||||
new File('src/main/resources/ioInput.txt').eachFile { file ->
|
||||
println file.name
|
||||
files.add(file.name)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileMatch_filesAreListed() {
|
||||
var files = []
|
||||
new File('src/main/resources').eachFileMatch(~/io.*\.txt/) { file ->
|
||||
println file.name
|
||||
files.add(file.name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileRecurse_thenFilesInSubfoldersAreListed() {
|
||||
var files = []
|
||||
new File('src/main').eachFileRecurse(FileType.FILES) { file ->
|
||||
println "$file.parent $file.name"
|
||||
files.add("$file.parent $file.name")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileRecurse_thenDirsInSubfoldersAreListed() {
|
||||
var files = []
|
||||
new File('src/main').eachFileRecurse(FileType.DIRECTORIES) { file ->
|
||||
println "$file.parent $file.name"
|
||||
files.add("$file.parent $file.name")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenUsingEachDirRecurse_thenDirsAndSubDirsAreListed() {
|
||||
var files = []
|
||||
new File('src/main').eachDirRecurse { dir ->
|
||||
println "$dir.parent $dir.name"
|
||||
files.add("$dir.parent $dir.name")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenUsingTraverse_thenDirectoryIsTraversed() {
|
||||
var files = []
|
||||
new File('src/main').traverse { file ->
|
||||
if (file.directory && file.name == 'groovy') {
|
||||
FileVisitResult.SKIP_SUBTREE
|
||||
} else {
|
||||
println "$file.parent - $file.name"
|
||||
files.add("$file.parent - $file.name")
|
||||
}
|
||||
}
|
||||
assertTrue(files.size() > 1)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,6 +2,8 @@ package groovy.com.baeldung.stringtypes
|
|||
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.assertFalse
|
||||
|
||||
class DollarSlashyString {
|
||||
|
||||
@Test
|
||||
|
@ -19,6 +21,7 @@ class DollarSlashyString {
|
|||
- $/$$
|
||||
/$
|
||||
|
||||
print(dollarSlashy)
|
||||
//print(dollarSlashy)
|
||||
assertFalse(dollarSlashy.isEmpty())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -45,8 +45,7 @@
|
|||
<properties>
|
||||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
<gson.version>2.10</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,2 +1,3 @@
|
|||
## Relevant Articles
|
||||
- [Deprecate Finalization in Java 18](https://www.baeldung.com/java-18-deprecate-finalization)
|
||||
- [Simple Web Server in Java 18](https://www.baeldung.com/simple-web-server-java-18)
|
||||
|
|
|
@ -0,0 +1,59 @@
|
|||
package com.baeldung.simplewebserver;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.file.Path;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import com.sun.net.httpserver.Filter;
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import com.sun.net.httpserver.HttpHandler;
|
||||
import com.sun.net.httpserver.HttpHandlers;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import com.sun.net.httpserver.Request;
|
||||
import com.sun.net.httpserver.SimpleFileServer;
|
||||
|
||||
public class WebServer {
|
||||
|
||||
private final InetSocketAddress address = new InetSocketAddress(8080);
|
||||
private final Path path = Path.of("/");
|
||||
|
||||
public static void main(String[] args) {
|
||||
WebServer webServer = new WebServer();
|
||||
HttpServer server = webServer.createWithHandler401Response();
|
||||
server.start();
|
||||
}
|
||||
|
||||
private HttpServer createBasic() {
|
||||
return SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE);
|
||||
}
|
||||
|
||||
private HttpServer createWithHandler() throws IOException {
|
||||
HttpServer server = SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE);
|
||||
HttpHandler handler = SimpleFileServer.createFileHandler(Path.of("/Users"));
|
||||
server.createContext("/test", handler);
|
||||
return server;
|
||||
}
|
||||
|
||||
private HttpServer createWithHandler401Response() {
|
||||
Predicate<Request> findAllowedPath = r -> r.getRequestURI()
|
||||
.getPath()
|
||||
.equals("/test/allowed");
|
||||
|
||||
HttpHandler allowedResponse = HttpHandlers.of(200, Headers.of("Allow", "GET"), "Welcome");
|
||||
HttpHandler deniedResponse = HttpHandlers.of(401, Headers.of("Deny", "GET"), "Denied");
|
||||
|
||||
HttpHandler handler = HttpHandlers.handleOrElse(findAllowedPath, allowedResponse, deniedResponse);
|
||||
|
||||
HttpServer server = SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE);
|
||||
server.createContext("/test", handler);
|
||||
return server;
|
||||
}
|
||||
|
||||
private HttpServer createWithFilter() throws IOException {
|
||||
Filter filter = SimpleFileServer.createOutputFilter(System.out, SimpleFileServer.OutputLevel.INFO);
|
||||
HttpHandler handler = SimpleFileServer.createFileHandler(Path.of("/Users"));
|
||||
return HttpServer.create(new InetSocketAddress(8080), 10, "/test", handler, filter);
|
||||
}
|
||||
|
||||
}
|
|
@ -63,7 +63,7 @@ public class VectorAPIExamples {
|
|||
public float[] scalarNormOfTwoArrays(float[] arr1, float[] arr2) {
|
||||
float[] finalResult = new float[arr1.length];
|
||||
for (int i = 0; i < arr1.length; i++) {
|
||||
finalResult[i] = (arr1[i] * arr1[i] + arr2[i] * arr2[i]) * -1.0f;
|
||||
finalResult[i] = (float) Math.sqrt(arr1[i] * arr1[i] + arr2[i] * arr2[i]);
|
||||
}
|
||||
return finalResult;
|
||||
}
|
||||
|
@ -77,13 +77,13 @@ public class VectorAPIExamples {
|
|||
var vb = FloatVector.fromArray(PREFERRED_SPECIES, arr2, i);
|
||||
var vc = va.mul(va)
|
||||
.add(vb.mul(vb))
|
||||
.neg();
|
||||
.sqrt();
|
||||
vc.intoArray(finalResult, i);
|
||||
}
|
||||
|
||||
// tail cleanup
|
||||
for (; i < arr1.length; i++) {
|
||||
finalResult[i] = (arr1[i] * arr1[i] + arr2[i] * arr2[i]) * -1.0f;
|
||||
finalResult[i] = (float) Math.sqrt(arr1[i] * arr1[i] + arr2[i] * arr2[i]);
|
||||
}
|
||||
return finalResult;
|
||||
}
|
||||
|
|
|
@ -28,7 +28,7 @@ public class VectorAPIUnitTest {
|
|||
public void whenTwoValuesProvided_thenComputeScalarNorm() {
|
||||
float[] arr1 = { 1, 2.3f };
|
||||
float[] arr2 = { 1.3f, 2.0f };
|
||||
float[] result = { -2.6899998f, -9.29f };
|
||||
float[] result = { 1.6401219f, 3.047950f };
|
||||
Assertions.assertArrayEquals(result, vector.scalarNormOfTwoArrays(arr1, arr2));
|
||||
}
|
||||
|
||||
|
@ -36,7 +36,7 @@ public class VectorAPIUnitTest {
|
|||
public void whenTwoValuesProvided_thenComputeVectorNorm() {
|
||||
float[] arr1 = { 1, 2.3f };
|
||||
float[] arr2 = { 1.3f, 2.0f };
|
||||
float[] result = { -2.6899998f, -9.29f };
|
||||
float[] result = { 1.6401219f, 3.047950f };
|
||||
Assertions.assertArrayEquals(result, vector.vectorNormalForm(arr1, arr2));
|
||||
}
|
||||
|
||||
|
|
|
@ -3,3 +3,4 @@
|
|||
- [String Templates in Java 21](https://www.baeldung.com/java-21-string-templates)
|
||||
- [Unnamed Classes and Instance Main Methods in Java 21](https://www.baeldung.com/java-21-unnamed-class-instance-main)
|
||||
- [Unnamed Patterns and Variables in Java 21](https://www.baeldung.com/java-unnamed-patterns-variables)
|
||||
- [JFR View Command in Java 21](https://www.baeldung.com/java-flight-recorder-view)
|
||||
|
|
|
@ -10,4 +10,7 @@
|
|||
- [Representing Furthest Possible Date in Java](https://www.baeldung.com/java-date-represent-max)
|
||||
- [Retrieving Unix Time in Java](https://www.baeldung.com/java-retrieve-unix-time)
|
||||
- [Calculate Months Between Two Dates in Java](https://www.baeldung.com/java-months-difference-two-dates)
|
||||
- [Format LocalDate to ISO 8601 With T and Z](https://www.baeldung.com/java-format-localdate-iso-8601-t-z)
|
||||
- [Check if Two Date Ranges Overlap](https://www.baeldung.com/java-check-two-date-ranges-overlap)
|
||||
- [Difference between ZoneOffset.UTC and ZoneId.of(“UTC”)](https://www.baeldung.com/java-zoneoffset-utc-zoneid-of)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
|
||||
|
|
|
@ -12,3 +12,4 @@ This module contains articles about arrays conversion in Java
|
|||
- [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array)
|
||||
- [Convert Char Array to Int Array in Java](https://www.baeldung.com/java-convert-char-int-array)
|
||||
- [How to Convert Byte Array to Char Array](https://www.baeldung.com/java-convert-byte-array-char)
|
||||
- [Convert byte[] to Byte[] and Vice Versa in Java](https://www.baeldung.com/java-byte-array-wrapper-primitive-type-convert)
|
||||
|
|
|
@ -10,3 +10,4 @@ This module contains complete guides about arrays in Java
|
|||
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
|
||||
- [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size)
|
||||
- [Merge Two Arrays and Remove Duplicates in Java](https://www.baeldung.com/java-merge-two-arrays-delete-duplicates)
|
||||
- [Print a Java 2D Array](https://www.baeldung.com/java-2d-array-print)
|
||||
|
|
|
@ -7,10 +7,6 @@
|
|||
<name>core-java-arrays-guides</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<properties>
|
||||
<system-stubs.jupiter.version>2.1.5</system-stubs.jupiter.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
|
@ -34,7 +30,10 @@
|
|||
<version>${system-stubs.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<system-stubs.jupiter.version>2.1.5</system-stubs.jupiter.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,2 +1,4 @@
|
|||
## Relevant Articles
|
||||
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)
|
||||
- [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)
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.equilibriumindex;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
class EquilibriumIndexFinder {
|
||||
|
||||
List<Integer> findEquilibriumIndexes(int[] array) {
|
||||
int[] partialSums = new int[array.length + 1];
|
||||
partialSums[0] = 0;
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
partialSums[i+1] = partialSums[i] + array[i];
|
||||
}
|
||||
|
||||
List<Integer> equilibriumIndexes = new ArrayList<Integer>();
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (partialSums[i] == (partialSums[array.length] - (partialSums[i+1]))) {
|
||||
equilibriumIndexes.add(i);
|
||||
}
|
||||
}
|
||||
return equilibriumIndexes;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.equilibriumindex;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class EquilibriumIndexFinderUnitTest {
|
||||
|
||||
@Test
|
||||
void givenArrayHasEquilibriumIndexes_whenFindEquilibriumIndexes_thenListAllEquilibriumIndexes() {
|
||||
int[] array = {1, -3, 0, 4, -5, 4, 0, 1, -2, -1};
|
||||
assertThat(new EquilibriumIndexFinder().findEquilibriumIndexes(array)).containsExactly(1, 4, 9);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithoutEquilibriumIndexes_whenFindEquilibriumIndexes_thenEmptyList() {
|
||||
int[] array = {1, 2, 3};
|
||||
assertThat(new EquilibriumIndexFinder().findEquilibriumIndexes(array)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithOneElement_whenFindEquilibriumIndexes_thenListFirstIndex() {
|
||||
int[] array = {5};
|
||||
assertThat(new EquilibriumIndexFinder().findEquilibriumIndexes(array)).containsExactly(0);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.movezerototheend;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
public class MoveZeroesToTheEndOfAnArrayUnitTest {
|
||||
private static final int[] EXPECTED = new int[] { 42, 2, 3, 4, 0, 0 };
|
||||
|
||||
@Test
|
||||
void whenCreatingANewArrayAndCopyingValues_thenGetTheExpectedResult() {
|
||||
int[] array = new int[] { 42, 2, 0, 3, 4, 0 };
|
||||
int[] result = new int[array.length];
|
||||
int idx = 0;
|
||||
for (int n : array) {
|
||||
if (n != 0) {
|
||||
result[idx++] = n;
|
||||
}
|
||||
}
|
||||
assertArrayEquals(EXPECTED, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMovingZeroInTheOriginalArray_thenGetTheExpectedResult() {
|
||||
int[] array = new int[] { 42, 2, 0, 3, 4, 0 };
|
||||
int idx = 0;
|
||||
for (int n : array) {
|
||||
if (n != 0) {
|
||||
array[idx++] = n;
|
||||
}
|
||||
}
|
||||
while (idx < array.length) {
|
||||
array[idx++] = 0;
|
||||
}
|
||||
assertArrayEquals(EXPECTED, array);
|
||||
}
|
||||
}
|
|
@ -6,3 +6,4 @@ This module contains articles about Java Character Class
|
|||
- [Character#isAlphabetic vs. Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)
|
||||
- [Difference Between Java’s “char” and “String”](https://www.baeldung.com/java-char-vs-string)
|
||||
- [Increment Character in Java](https://www.baeldung.com/java-char-sequence)
|
||||
- [Creating Unicode Character From Its Code Point Hex String](https://www.baeldung.com/java-unicode-character-from-code-point-hex-string)
|
||||
|
|
|
@ -0,0 +1,70 @@
|
|||
package com.baeldung.unicodechar;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class UnicodeCharFromCodePointHexStringUnitTest {
|
||||
private static final String U_CHECK = "✅"; // U+2705
|
||||
private static final String U_STRONG = "强"; // U+5F3A
|
||||
|
||||
|
||||
@Test
|
||||
void whenEscapeUAndNumberInString_thenGetExpectedUnicodeStr() {
|
||||
String check = "\u2705";
|
||||
assertEquals(U_CHECK, check);
|
||||
|
||||
String strong = "\u5F3A";
|
||||
assertEquals(U_STRONG, strong);
|
||||
|
||||
// "A" U+0041
|
||||
assertEquals("A", "\u0041");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenConcatUAndNumberAsString_thenDoNotGetExpectedUnicodeStr() {
|
||||
String check = "\\u" + "2705";
|
||||
assertEquals("\\u2705", check);
|
||||
|
||||
String strong = "\\u" + "5F3A";
|
||||
assertEquals("\\u5F3A", strong);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenCastHexCodePointToCharAndConvertCharToString_thenGetExpectedUnicodeStr() {
|
||||
|
||||
int codePoint = Integer.parseInt("2705", 16); //Decimal int: 9989
|
||||
char[] checkChar = Character.toChars(codePoint);
|
||||
String check = String.valueOf(checkChar);
|
||||
assertEquals(U_CHECK, check);
|
||||
|
||||
// For Java 11 and later versions
|
||||
// assertEquals(U_CHECK, Character.toString(codePoint));
|
||||
|
||||
codePoint = Integer.parseInt("5F3A", 16); //Decimal int: 24378
|
||||
char[] strongChar = Character.toChars(codePoint);
|
||||
String strong = String.valueOf(strongChar);
|
||||
assertEquals(U_STRONG, strong);
|
||||
|
||||
// For Java 11 and later versions
|
||||
// assertEquals(U_STRONG, Character.toString(codePoint));
|
||||
}
|
||||
|
||||
String stringFromCodePointHex(String codePointHex) {
|
||||
int codePoint = Integer.parseInt(codePointHex, 16);
|
||||
|
||||
// For Java 11 and later versions: return Character.toString(codePoint)
|
||||
|
||||
char[] chars = Character.toChars(codePoint);
|
||||
return String.valueOf(chars);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingstringFromCodePointHex_thenGetExpectedUnicodeStr() {
|
||||
assertEquals("A", stringFromCodePointHex("0041"));
|
||||
assertEquals(U_CHECK, stringFromCodePointHex("2705"));
|
||||
assertEquals(U_STRONG, stringFromCodePointHex("5F3A"));
|
||||
}
|
||||
}
|
|
@ -13,4 +13,5 @@
|
|||
- [Time Complexity of Java Collections Sort in Java](https://www.baeldung.com/java-time-complexity-collections-sort)
|
||||
- [Check if List Contains at Least One Enum](https://www.baeldung.com/java-list-check-enum-presence)
|
||||
- [Comparison of for Loops and Iterators](https://www.baeldung.com/java-for-loops-vs-iterators)
|
||||
- [PriorityQueue iterator() Method in Java](https://www.baeldung.com/java-priorityqueue-iterator)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
|
||||
|
|
|
@ -5,18 +5,6 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-5</artifactId>
|
||||
<name>core-java-collections-5</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>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
|
@ -61,6 +49,19 @@
|
|||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<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>
|
||||
|
||||
<properties>
|
||||
<junit.version>5.9.2</junit.version>
|
||||
<roaringbitmap.version>0.9.38</roaringbitmap.version>
|
||||
|
|
|
@ -22,7 +22,7 @@
|
|||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>31.1-jre</version>
|
||||
<version>${guava.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
|
|
@ -55,13 +55,11 @@
|
|||
<version>${org.json.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<jmh.version>1.21</jmh.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
<org.json.version>20230618</org.json.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -3,3 +3,4 @@
|
|||
- [Removing the Last Node in a Linked List](https://www.baeldung.com/java-linked-list-remove-last-element)
|
||||
- [Call a Method on Each Element of a List in Java](https://www.baeldung.com/java-call-method-each-list-item)
|
||||
- [Sorting One List Based on Another List in Java](https://www.baeldung.com/java-sorting-one-list-using-another)
|
||||
- [Reset ListIterator to First Element of the List in Java](https://www.baeldung.com/java-reset-listiterator)
|
||||
|
|
|
@ -29,4 +29,4 @@
|
|||
<properties>
|
||||
<vavr.version>0.10.4</vavr.version>
|
||||
</properties>
|
||||
</project>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.modifyandprint;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class ModifyAndPrintListElementsUnitTest {
|
||||
|
||||
private final Logger log = LoggerFactory.getLogger(ModifyAndPrintListElementsUnitTest.class);
|
||||
|
||||
@Test
|
||||
void whenPrintingInForEach_thenListIsPrinted() {
|
||||
List<String> theList = Lists.newArrayList("Kai", "Liam", "Eric", "Kevin");
|
||||
theList.forEach(element -> log.info(element));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingModifyAndPrintingSeparately_thenListIsModifiedAndPrinted() {
|
||||
List<String> theList = Lists.newArrayList("Kai", "Liam", "Eric", "Kevin");
|
||||
theList.replaceAll(element -> element.toUpperCase());
|
||||
theList.forEach(element -> log.info(element));
|
||||
assertEquals(List.of("KAI", "LIAM", "ERIC", "KEVIN"), theList);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenPrintingInMap_thenStreamIsModifiedAndPrinted() {
|
||||
List<String> theList = List.of("Kai", "Liam", "Eric", "Kevin");
|
||||
List<String> newList = theList.stream()
|
||||
.map(element -> {
|
||||
String newElement = element.toUpperCase();
|
||||
log.info(newElement);
|
||||
return newElement;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(List.of("KAI", "LIAM", "ERIC", "KEVIN"), newList);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenPrintingInPeek_thenStreamIsModifiedAndPrinted() {
|
||||
List<String> theList = List.of("Kai", "Liam", "Eric", "Kevin");
|
||||
List<String> newList = theList.stream()
|
||||
.map(element -> element.toUpperCase())
|
||||
.peek(element-> log.info(element))
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(List.of("KAI", "LIAM", "ERIC", "KEVIN"), newList);
|
||||
}
|
||||
}
|
|
@ -27,7 +27,7 @@
|
|||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.8.9</version>
|
||||
<version>2.10.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
|
|
|
@ -5,6 +5,8 @@
|
|||
- [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair)
|
||||
- [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file)
|
||||
- [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-size-bound)
|
||||
- [How to Sort LinkedHashMap By Values in Java](https://www.baeldung.com/java-sort-linkedhashmap-using-values)
|
||||
- [How to Sort LinkedHashMap by Values in Java](https://www.baeldung.com/java-sort-linkedhashmap-using-values)
|
||||
- [How to Increment a Map Value in Java](https://www.baeldung.com/java-increment-map-value)
|
||||
- [Collect Stream of entrySet() to a LinkedHashMap](https://www.baeldung.com/java-linkedhashmap-entryset-stream)
|
||||
- [How to Pretty-Print a Map in Java](https://www.baeldung.com/java-map-pretty-print)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)
|
||||
|
|
|
@ -32,17 +32,22 @@
|
|||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>32.1.2-jre</version>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>1.37</version>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>1.37</version>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -63,6 +68,9 @@
|
|||
<properties>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<csv.version>1.5</csv.version>
|
||||
<guava.version>32.1.2-jre</guava.version>
|
||||
<jmh.version>1.37</jmh.version>
|
||||
<commons-collections.version>4.4</commons-collections.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,111 @@
|
|||
package com.baeldung.map.entrysettolinkedhashmap;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.entry;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class EntrySetToLinkedHashMapUnitTest {
|
||||
|
||||
private Map<Integer, String> map;
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingCollectorsGroupingBy_thenCollectToLinkedHashMap() {
|
||||
Map<String, Set<String>> countryToCities = Map.of("Paris", "France", "Nice", "France", "Madrid", "Spain")
|
||||
.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.groupingBy(Map.Entry::getValue, LinkedHashMap::new, Collectors.mapping(Map.Entry::getKey, Collectors.toSet())));
|
||||
|
||||
assertThat(countryToCities).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry("France", Set.of("Paris", "Nice")), entry("Spain", Set.of("Madrid")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingCollectorsToMap_thenCollectAndConvertToLinkedHashMap() {
|
||||
Map<Integer, String> result = new LinkedHashMap<>(map.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingCollectorsToMap_thenCollectToLinkedHashMap() {
|
||||
Map<Integer, String> result = map.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.toMap(
|
||||
Map.Entry::getKey, Map.Entry::getValue,
|
||||
(e1, e2) -> {
|
||||
throw new RuntimeException();
|
||||
},
|
||||
LinkedHashMap::new));
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingLinkedHashMapConstructor_thenObtainLinkedHashMap() {
|
||||
Map<Integer, String> result = new LinkedHashMap<>(map);
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingPutWithForLoop_thenInsertIntoLinkedHashMap() {
|
||||
Map<Integer, String> result = new LinkedHashMap<>();
|
||||
|
||||
for (Map.Entry<Integer, String> entry : map.entrySet()) {
|
||||
result.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingPutWithMapForEach_thenInsertIntoLinkedHashMap() {
|
||||
Map<Integer, String> result = new LinkedHashMap<>();
|
||||
|
||||
map.forEach((k, v) -> result.put(k, v));
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingPutWithSetForEach_thenInsertIntoLinkedHashMap() {
|
||||
Map<Integer, String> result = new LinkedHashMap<>();
|
||||
|
||||
map.entrySet()
|
||||
.forEach(entry -> result.put(entry.getKey(), entry.getValue()));
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingPutWithStreamForEach_thenInsertIntoLinkedHashMapp() {
|
||||
Map<Integer, String> result = new LinkedHashMap<>();
|
||||
|
||||
map.entrySet()
|
||||
.stream()
|
||||
.forEach(entry -> result.put(entry.getKey(), entry.getValue()));
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void init() {
|
||||
map = Map.of(1, "value 1", 2, "value 2");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,202 @@
|
|||
package com.baeldung.map.prettyprintmap;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import org.apache.commons.collections4.MapUtils;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintStream;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
class PrettyPrintMapUnitTest {
|
||||
|
||||
private static final Map<String, Object> MAP;
|
||||
|
||||
static {
|
||||
// using LinkedHashMap to keep insertion order, helpful in assertions
|
||||
MAP = new LinkedHashMap<>();
|
||||
MAP.put("one", 1);
|
||||
MAP.put("two", 2);
|
||||
|
||||
Map<String, Integer> innerMap = new LinkedHashMap<>();
|
||||
innerMap.put("ten", 10);
|
||||
innerMap.put("eleven", 11);
|
||||
|
||||
MAP.put("inner", innerMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenToString_thenOneLine() {
|
||||
String result = MAP.toString();
|
||||
|
||||
String expected = "{one=1, two=2, inner={ten=10, eleven=11}}";
|
||||
Assertions.assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenSimpleForEachLoop_thenPrettyPrintWithoutNested() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
for (Map.Entry<?, ?> entry : MAP.entrySet()) {
|
||||
result.append(String.format("%-15s : %s%n", entry.getKey(), entry.getValue()));
|
||||
}
|
||||
|
||||
String expected =
|
||||
"one : 1\n" +
|
||||
"two : 2\n" +
|
||||
"inner : {ten=10, eleven=11}\n";
|
||||
Assertions.assertThat(result.toString()).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenRecursionForEachLoop_thenPrettyPrint() {
|
||||
String result = printMap(0, MAP);
|
||||
|
||||
String expected =
|
||||
"one : 1\n" +
|
||||
"two : 2\n" +
|
||||
"inner :\n" +
|
||||
" ten : 10\n" +
|
||||
" eleven : 11\n";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenStream_thenPrettyPrintWithoutNested() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
MAP.forEach((k, v) -> result.append(String.format("%-15s : %s%n", k, v)));
|
||||
|
||||
String expected =
|
||||
"one : 1\n" +
|
||||
"two : 2\n" +
|
||||
"inner : {ten=10, eleven=11}\n";
|
||||
Assertions.assertThat(result.toString()).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenExtendedStream_thenPrettyPrintWithoutNested() {
|
||||
String result = MAP.entrySet().stream()
|
||||
.map(entry -> String.format("%-15s : %s", entry.getKey(), entry.getValue()))
|
||||
.collect(Collectors.joining("\n"));
|
||||
|
||||
String expected =
|
||||
"one : 1\n" +
|
||||
"two : 2\n" +
|
||||
"inner : {ten=10, eleven=11}\n";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
@Test
|
||||
void givenMap_whenJackson_thenPrettyPrint() throws JsonProcessingException {
|
||||
String result = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(MAP);
|
||||
|
||||
String expected =
|
||||
"{\n" +
|
||||
" \"one\" : 1,\n" +
|
||||
" \"two\" : 2,\n" +
|
||||
" \"inner\" : {\n" +
|
||||
" \"ten\" : 10,\n" +
|
||||
" \"eleven\" : 11\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenGson_thenPrettyPrint() {
|
||||
String result = new GsonBuilder().setPrettyPrinting().create().toJson(MAP);
|
||||
|
||||
String expected =
|
||||
"{\n" +
|
||||
" \"one\": 1,\n" +
|
||||
" \"two\": 2,\n" +
|
||||
" \"inner\": {\n" +
|
||||
" \"ten\": 10,\n" +
|
||||
" \"eleven\": 11\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenApacheCommonsCollectionsDebugPrint_thenPrettyPrintWithClassNames() throws IOException {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
PrintStream ps = new PrintStream(baos)) {
|
||||
|
||||
MapUtils.debugPrint(ps, "map", MAP);
|
||||
String result = baos.toString();
|
||||
|
||||
String expected =
|
||||
"map = \n" +
|
||||
"{\n" +
|
||||
" one = 1 java.lang.Integer\n" +
|
||||
" two = 2 java.lang.Integer\n" +
|
||||
" inner = \n" +
|
||||
" {\n" +
|
||||
" ten = 10 java.lang.Integer\n" +
|
||||
" eleven = 11 java.lang.Integer\n" +
|
||||
" } java.util.LinkedHashMap\n" +
|
||||
"} java.util.LinkedHashMap\n";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenApacheCommonsCollectionsVerbosePrint_thenPrettyPrint() throws IOException {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
PrintStream ps = new PrintStream(baos)) {
|
||||
|
||||
MapUtils.verbosePrint(ps, "map", MAP);
|
||||
String result = baos.toString();
|
||||
|
||||
String expected =
|
||||
"map = \n" +
|
||||
"{\n" +
|
||||
" one = 1\n" +
|
||||
" two = 2\n" +
|
||||
" inner = \n" +
|
||||
" {\n" +
|
||||
" ten = 10\n" +
|
||||
" eleven = 11\n" +
|
||||
" }\n" +
|
||||
"}\n";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenGuavaJoiner_thenPrettyPrintWithoutNested() {
|
||||
String result = Joiner.on(",\n").withKeyValueSeparator("=").join(MAP);
|
||||
|
||||
String expected =
|
||||
"one=1,\n" +
|
||||
"two=2,\n" +
|
||||
"inner={ten=10, eleven=11}";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
private static String printMap(int leftPadding, Map<?, ?> map) {
|
||||
StringBuilder ret = new StringBuilder();
|
||||
|
||||
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
||||
if (entry.getValue() instanceof Map) {
|
||||
ret.append(String.format("%-15s :%n", entry.getKey()));
|
||||
ret.append(printMap(leftPadding + 4, (Map<?, ?>) entry.getValue()));
|
||||
}
|
||||
else {
|
||||
ret.append(String.format("%" + (leftPadding > 0 ? leftPadding : "") + "s" // adding padding
|
||||
+ "%-15s : %s%n",
|
||||
"", entry.getKey(), entry.getValue()));
|
||||
}
|
||||
}
|
||||
return ret.toString();
|
||||
}
|
||||
|
||||
}
|
|
@ -35,7 +35,7 @@
|
|||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>32.1.1-jre</version>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
|
|
@ -41,7 +41,7 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<gson.version>2.8.5</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -60,14 +60,15 @@ public class HashtableUnitTest {
|
|||
table.put(new Word("dog"), "another animal");
|
||||
|
||||
Iterator<Word> it = table.keySet().iterator();
|
||||
System.out.println("iterator created");
|
||||
// System.out.println("iterator created");
|
||||
|
||||
table.remove(new Word("dog"));
|
||||
System.out.println("element removed");
|
||||
// System.out.println("element removed");
|
||||
|
||||
while (it.hasNext()) {
|
||||
Word key = it.next();
|
||||
System.out.println(table.get(key));
|
||||
// System.out.println(table.get(key));
|
||||
assertNotNull(table.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -85,12 +86,13 @@ public class HashtableUnitTest {
|
|||
table.put(new Word("8"), "eight");
|
||||
|
||||
Enumeration<Word> enumKey = table.keys();
|
||||
System.out.println("Enumeration created");
|
||||
// System.out.println("Enumeration created");
|
||||
table.remove(new Word("1"));
|
||||
System.out.println("element removed");
|
||||
// System.out.println("element removed");
|
||||
while (enumKey.hasMoreElements()) {
|
||||
Word key = enumKey.nextElement();
|
||||
System.out.println(table.get(key));
|
||||
// System.out.println(table.get(key));
|
||||
assertNotNull(table.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -110,7 +112,8 @@ public class HashtableUnitTest {
|
|||
Iterator<Map.Entry<Word, String>> it = table.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry<Word, String> entry = it.next();
|
||||
System.out.println(entry.getValue());
|
||||
// System.out.println(entry.getValue());
|
||||
assertNotNull(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -8,3 +8,6 @@
|
|||
- [How to Check if All Runnables Are Done](https://www.baeldung.com/java-runnables-check-status)
|
||||
- [Parallelize for Loop in Java](https://www.baeldung.com/java-for-loop-parallel)
|
||||
- [How to Effectively Unit Test CompletableFuture](https://www.baeldung.com/java-completablefuture-unit-test)
|
||||
- [How to Collect All Results and Handle Exceptions With CompletableFuture in a Loop](https://www.baeldung.com/java-completablefuture-collect-results-handle-exceptions)
|
||||
- [CompletableFuture runAsync() vs. supplyAsync() in Java](https://www.baeldung.com/java-completablefuture-runasync-supplyasync)
|
||||
- [Difference Between thenApply() and thenApplyAsync() in CompletableFuture](https://www.baeldung.com/java-completablefuture-thenapply-thenapplyasync)
|
||||
|
|
|
@ -0,0 +1,79 @@
|
|||
package com.baeldung.runvssupply;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
public class RunAndSupplyCompare {
|
||||
|
||||
public static void main(String args[]) throws ExecutionException, InterruptedException {
|
||||
chainingOperationCompare();
|
||||
}
|
||||
|
||||
public static void inputAndReturnCompare() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<Void> runAsyncFuture = CompletableFuture.runAsync(() -> {
|
||||
// Perform non-result producing task
|
||||
System.out.println("Task executed asynchronously");
|
||||
});
|
||||
|
||||
CompletableFuture<String> supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
|
||||
// Perform result-producing task
|
||||
return "Result of the asynchronous computation";
|
||||
});
|
||||
// Get the result later
|
||||
String result = supplyAsyncFuture.get();
|
||||
System.out.println("Result: " + result);
|
||||
}
|
||||
|
||||
public static void exceptionHandlingCompare() {
|
||||
CompletableFuture<Void> runAsyncFuture = CompletableFuture.runAsync(() -> {
|
||||
// Task that may throw an exception
|
||||
throw new RuntimeException("Exception occurred in asynchronous task");
|
||||
});
|
||||
try {
|
||||
runAsyncFuture.get();
|
||||
// Exception will be thrown here
|
||||
} catch (ExecutionException ex) {
|
||||
Throwable cause = ex.getCause();
|
||||
System.out.println("Exception caught: " + cause.getMessage());
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
CompletableFuture<Object> supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
|
||||
// Task that may throw an exception
|
||||
throw new RuntimeException("Exception occurred in asynchronous task");
|
||||
})
|
||||
.exceptionally(ex -> {
|
||||
// Exception handling logic
|
||||
return "Default value";
|
||||
});
|
||||
|
||||
Object result = supplyAsyncFuture.join();
|
||||
// Get the result or default value
|
||||
System.out.println("Result: " + result);
|
||||
}
|
||||
|
||||
public static void chainingOperationCompare() {
|
||||
CompletableFuture<Void> runAsyncFuture = CompletableFuture.runAsync(() -> {
|
||||
// Perform non-result producing task
|
||||
System.out.println("Task executed asynchronously");
|
||||
});
|
||||
runAsyncFuture.thenRun(() -> {
|
||||
// Execute another task after the completion of runAsync()
|
||||
System.out.println("Another task executed after runAsync() completes");
|
||||
});
|
||||
|
||||
CompletableFuture<String> supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
|
||||
// Perform result-producing task
|
||||
return "Result of the asynchronous computation";
|
||||
});
|
||||
supplyAsyncFuture.thenApply(result -> {
|
||||
// Transform the result
|
||||
return result.toUpperCase();
|
||||
})
|
||||
.thenAccept(transformedResult -> {
|
||||
// Consume the transformed result
|
||||
System.out.println("Transformed Result: " + transformedResult);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,91 @@
|
|||
package com.baeldung.concurrent.applyvsapplyasync;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
public class ThenApplyAndThenApplyAsyncUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCompletableFuture_whenUsingThenApply_thenResultIsAsExpected() {
|
||||
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||
CompletableFuture<String> thenApplyResultFuture = future.thenApply(num -> "Result: " + num);
|
||||
|
||||
String thenApplyResult = thenApplyResultFuture.join();
|
||||
assertEquals("Result: 5", thenApplyResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCompletableFuture_whenUsingThenApplyAsync_thenResultIsAsExpected() {
|
||||
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||
CompletableFuture<String> thenApplyAsyncResultFuture = future.thenApplyAsync(num -> "Result: " + num);
|
||||
|
||||
String thenApplyAsyncResult = thenApplyAsyncResultFuture.join();
|
||||
assertEquals("Result: 5", thenApplyAsyncResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCompletableFuture_whenUsingThenApply_thenExceptionIsPropagated() {
|
||||
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||
CompletableFuture<String> resultFuture = future.thenApply(num -> "Result: " + num / 0);
|
||||
assertThrows(CompletionException.class, () -> resultFuture.join());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCompletableFuture_whenUsingThenApply_thenExceptionIsHandledAsExpected() {
|
||||
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||
CompletableFuture<String> resultFuture = future.thenApply(num -> "Result: " + num / 0);
|
||||
try {
|
||||
// Accessing the result
|
||||
String result = resultFuture.join();
|
||||
assertEquals("Result: 5", result);
|
||||
} catch (CompletionException e) {
|
||||
assertEquals("java.lang.ArithmeticException: / by zero", e.getMessage());
|
||||
System.err.println("Exception caught: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCompletableFuture_whenUsingThenApplyAsync_thenExceptionIsHandledAsExpected() {
|
||||
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||
CompletableFuture<String> thenApplyAsyncResultFuture = future.thenApplyAsync(num -> "Result: " + num / 0);
|
||||
|
||||
String result = thenApplyAsyncResultFuture.handle((res, error) -> {
|
||||
if (error != null) {
|
||||
// Handle the error appropriately, e.g., return a default value
|
||||
return "Error occurred";
|
||||
} else {
|
||||
return res;
|
||||
}
|
||||
})
|
||||
.join(); // Now join() won't throw the exception
|
||||
assertEquals("Error occurred", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCompletableFutureWithExecutor_whenUsingThenApplyAsync_thenThreadExecutesAsExpected() {
|
||||
ExecutorService customExecutor = Executors.newFixedThreadPool(4);
|
||||
|
||||
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 5;
|
||||
}, customExecutor);
|
||||
|
||||
CompletableFuture<String> resultFuture = future.thenApplyAsync(num -> "Result: " + num, customExecutor);
|
||||
|
||||
String result = resultFuture.join();
|
||||
assertEquals("Result: 5", result);
|
||||
|
||||
customExecutor.shutdown();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,90 @@
|
|||
package com.baeldung.concurrent.completablefuture;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
public class CombiningCompletableFuturesUnitTest {
|
||||
|
||||
private final Logger logger = mock(Logger.class);
|
||||
|
||||
private static Stream<Arguments> clientData() {
|
||||
return Stream.of(
|
||||
Arguments.of(List.of("Good Resource"), 1, 0),
|
||||
Arguments.of(List.of("Bad Resource"), 0, 1),
|
||||
Arguments.of(List.of("Good Resource", "Bad Resource"), 1, 1),
|
||||
Arguments.of(List.of("Good Resource", "Bad Resource", "Good Resource", "Bad Resource", "Good Resource"), 3, 2)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("clientData")
|
||||
public void givenMicroserviceClient_whenMultipleCreateResource_thenCombineResults(List<String> inputs, int successCount, int errorCount) {
|
||||
MicroserviceClient mockMicroservice = mock(MicroserviceClient.class);
|
||||
// Return an identifier of 123 on "Good Resource"
|
||||
when(mockMicroservice.createResource("Good Resource"))
|
||||
.thenReturn(CompletableFuture.completedFuture(123L));
|
||||
// Throw an exception on "Bad Resource"
|
||||
when(mockMicroservice.createResource("Bad Resource"))
|
||||
.thenReturn(CompletableFuture.failedFuture(new IllegalArgumentException("Bad Resource")));
|
||||
|
||||
// Given a list of CompletableFutures from our microservice calls...
|
||||
List<CompletableFuture<Long>> clientCalls = new ArrayList<>();
|
||||
for (String resource : inputs) {
|
||||
clientCalls.add(mockMicroservice.createResource(resource));
|
||||
}
|
||||
|
||||
// When all CompletableFutures are completed (exceptionally or otherwise)...
|
||||
Map<Boolean, List<Long>> resultsByValidity = clientCalls.stream()
|
||||
.map(this::handleFuture)
|
||||
.collect(Collectors.partitioningBy(resourceId -> resourceId != -1L));
|
||||
|
||||
// Then the returned resource identifiers should match what is expected...
|
||||
List<Long> validResults = resultsByValidity.getOrDefault(true, List.of());
|
||||
assertThat(validResults.size()).isEqualTo(successCount);
|
||||
|
||||
// And the logger mock should be called once for each exception with the expected error message
|
||||
List<Long> invalidResults = resultsByValidity.getOrDefault(false, List.of());
|
||||
assertThat(invalidResults.size()).isEqualTo(errorCount);
|
||||
verify(logger, times(errorCount))
|
||||
.error(eq("Encountered error: java.lang.IllegalArgumentException: Bad Resource"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Completes the given CompletableFuture, handling any exceptions that are thrown.
|
||||
* @param future the CompletableFuture to complete.
|
||||
* @return the resource identifier (-1 if the request failed).
|
||||
*/
|
||||
private Long handleFuture(CompletableFuture<Long> future) {
|
||||
return future
|
||||
.exceptionally(this::handleError)
|
||||
.join();
|
||||
}
|
||||
|
||||
private Long handleError(Throwable throwable) {
|
||||
logger.error("Encountered error: " + throwable);
|
||||
return -1L;
|
||||
}
|
||||
|
||||
interface MicroserviceClient {
|
||||
CompletableFuture<Long> createResource(String resourceName);
|
||||
}
|
||||
|
||||
interface Logger {
|
||||
void error(String message);
|
||||
}
|
||||
}
|
|
@ -2,3 +2,4 @@
|
|||
### Relevant Articles:
|
||||
- [Why wait() Requires Synchronization?](https://www.baeldung.com/java-wait-necessary-synchronization)
|
||||
- [Working with Exceptions in Java CompletableFuture](https://www.baeldung.com/java-exceptions-completablefuture)
|
||||
- [CountDownLatch vs. Semaphore](https://www.baeldung.com/java-countdownlatch-vs-semaphore)
|
||||
|
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.countdownlatchvssemaphore;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
public class CountDownLatchDemo {
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
// Create a CountDownLatch with an initial count equal to the number of tasks to be completed
|
||||
int numberOfTasks = 3;
|
||||
CountDownLatch latch = new CountDownLatch(numberOfTasks);
|
||||
|
||||
// Simulate completion of tasks by worker threads
|
||||
for (int i = 1; i <= numberOfTasks; i++) {
|
||||
new Thread(() -> {
|
||||
System.out.println("Task completed by Thread " + Thread.currentThread()
|
||||
.getId());
|
||||
|
||||
// Decrement the latch count to signal completion of a task
|
||||
latch.countDown();
|
||||
}).start();
|
||||
}
|
||||
|
||||
// Main thread waits until all tasks are completed
|
||||
latch.await();
|
||||
System.out.println("All tasks completed. Main thread proceeds.");
|
||||
|
||||
// Attempting to reset will have no effect
|
||||
latch.countDown();
|
||||
// Latch is already at zero, await() returns immediately
|
||||
latch.await(); // This line won't block
|
||||
System.out.println("Latch is already at zero and cannot be reset.");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.countdownlatchvssemaphore;
|
||||
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
public class SemaphoreDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Create a Semaphore with a fixed number of permits
|
||||
int NUM_PERMITS = 3;
|
||||
Semaphore semaphore = new Semaphore(NUM_PERMITS);
|
||||
|
||||
// Simulate resource access by worker threads
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
new Thread(() -> {
|
||||
try {
|
||||
// Acquire a permit to access the resource
|
||||
semaphore.acquire();
|
||||
System.out.println("Thread " + Thread.currentThread().getId() + " accessing resource.");
|
||||
|
||||
// Simulate resource usage
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// Release the permit after resource access is complete
|
||||
semaphore.release();
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
// Simulate resetting the Semaphore by releasing additional permits after a delay
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
|
||||
// Resetting the semaphore permits to the initial count
|
||||
semaphore.release(NUM_PERMITS);
|
||||
System.out.println("Semaphore permits reset to initial count.");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -8,3 +8,5 @@
|
|||
- [System.console() vs. System.out](https://www.baeldung.com/java-system-console-vs-system-out)
|
||||
- [How to Log to the Console in Color](https://www.baeldung.com/java-log-console-in-color)
|
||||
- [Create Table Using ASCII in a Console in Java](https://www.baeldung.com/java-console-ascii-make-table)
|
||||
- [Printing Message on Console without Using main() Method in Java](https://www.baeldung.com/java-no-main-print-message-console)
|
||||
- [Guide to System.in.read()](https://www.baeldung.com/java-system-in-read)
|
||||
|
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.systemin;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
class SystemInRead {
|
||||
static void readSingleCharacter() {
|
||||
System.out.println("Enter a character:");
|
||||
try {
|
||||
int input = System.in.read();
|
||||
System.out.println((char) input);
|
||||
}
|
||||
catch (IOException e) {
|
||||
System.err.println("Error reading input: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
static void readMultipleCharacters() {
|
||||
System.out.println("Enter characters (Press 'Enter' to quit):");
|
||||
try {
|
||||
int input;
|
||||
while ((input = System.in.read()) != '\n') {
|
||||
System.out.print((char) input);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.err.println("Error reading input: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
static void readWithParameters() {
|
||||
try {
|
||||
byte[] byteArray = new byte[5];
|
||||
int bytesRead;
|
||||
int totalBytesRead = 0;
|
||||
|
||||
while ((bytesRead = System.in.read(byteArray, 0, byteArray.length)) != -1) {
|
||||
System.out.print("Data read: " + new String(byteArray, 0, bytesRead));
|
||||
totalBytesRead += bytesRead;
|
||||
}
|
||||
|
||||
System.out.println("\nBytes Read: " + totalBytesRead);
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.systemin;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class SystemInReadUnitTest {
|
||||
@Test
|
||||
void givenUserInput_whenUsingReadMultipleCharacters_thenRead() {
|
||||
System.setIn(new ByteArrayInputStream("Hello\n".getBytes()));
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(outputStream));
|
||||
SystemInRead.readMultipleCharacters();
|
||||
|
||||
assertEquals("Enter characters (Press 'Enter' to quit):\n" + "Hello", outputStream.toString().trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenUserInput_whenUsingReadSingleCharacter_thenRead() {
|
||||
System.setIn(new ByteArrayInputStream("A".getBytes()));
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(outputStream));
|
||||
SystemInRead.readSingleCharacter();
|
||||
|
||||
assertEquals("Enter a character:\nA", outputStream.toString().trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenUserInput_whenUsingReadWithParameters_thenRead() {
|
||||
System.setIn(new ByteArrayInputStream("ABC".getBytes()));
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(outputStream));
|
||||
SystemInRead.readWithParameters();
|
||||
|
||||
assertEquals("Data read: ABC\n" + "Bytes Read: 3", outputStream.toString().trim());
|
||||
}
|
||||
}
|
|
@ -2,5 +2,6 @@
|
|||
This module contains articles about date operations in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
|
||||
- [Calculate Number of Weekdays Between Two Dates in Java](https://www.baeldung.com/java-count-weekdays-between-two-dates)
|
||||
- [Convert Long to Date in Java](https://www.baeldung.com/java-long-date-conversion)
|
||||
- [Convert Date to Unix Timestamp in Java](https://www.baeldung.com/java-convert-date-unix-timestamp)
|
||||
|
|
|
@ -5,6 +5,7 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-date-operations-4</artifactId>
|
||||
<name>core-java-date-operations-4</name>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -39,7 +40,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<joda-time.version>2.12.5</joda-time.version>
|
||||
<joda-time.version>2.12.6</joda-time.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,65 @@
|
|||
package com.baeldung.datetounixtimestamp;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DateToUnixTimeStampUnitTest {
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingInstantClass_thenConvertToUnixTimeStamp() {
|
||||
Instant givenDate = Instant.parse("2020-09-08T12:16:40Z");
|
||||
|
||||
assertEquals(1599567400L, givenDate.getEpochSecond());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingLocalDateTimeClass_thenConvertToUnixTimeStamp() {
|
||||
LocalDateTime givenDate = LocalDateTime.of(2023, 10, 19, 22, 45);
|
||||
|
||||
assertEquals(1697755500L, givenDate.toEpochSecond(ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingDateClass_thenConvertToUnixTimeStamp() throws ParseException {
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
Date givenDate = dateFormat.parse("2023-10-15 22:00:00");
|
||||
|
||||
assertEquals(1697407200L, givenDate.getTime() / 1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingCalendarClass_thenConvertToUnixTimeStamp() {
|
||||
Calendar calendar = new GregorianCalendar(2023, Calendar.OCTOBER, 17);
|
||||
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
|
||||
assertEquals(1697500800L, calendar.getTimeInMillis() / 1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingJodaTimeInstantClass_thenConvertToUnixTimeStamp() {
|
||||
org.joda.time.Instant givenDate = org.joda.time.Instant.parse("2020-09-08T12:16:40Z");
|
||||
|
||||
assertEquals(1599567400L, givenDate.getMillis() / 1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingJodaTimeDateTimeClass_thenConvertToUnixTimeStamp() {
|
||||
DateTime givenDate = new DateTime("2020-09-09T12:16:40Z");
|
||||
|
||||
assertEquals(1599653800L, givenDate.getMillis() / 1000);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
package com.baeldung.longtodate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.joda.time.DateTimeZone;
|
||||
import org.joda.time.Instant;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class LongToDateUnitTest {
|
||||
|
||||
@Test
|
||||
void givenLongValue_whenUsingInstantClass_thenConvert() {
|
||||
Instant expectedDate = Instant.parse("2020-09-08T12:16:40Z");
|
||||
long seconds = 1599567400L;
|
||||
|
||||
Instant date = Instant.ofEpochSecond(seconds);
|
||||
|
||||
assertEquals(expectedDate, date);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLongValue_whenUsingLocalDateClass_thenConvert() {
|
||||
LocalDate expectedDate = LocalDate.of(2023, 10, 17);
|
||||
long epochDay = 19647L;
|
||||
|
||||
LocalDate date = LocalDate.ofEpochDay(epochDay);
|
||||
|
||||
assertEquals(expectedDate, date);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLongValue_whenUsingDateClass_thenConvert() throws ParseException {
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
Date expectedDate = dateFormat.parse("2023-07-15 22:00:00");
|
||||
long milliseconds = 1689458400000L;
|
||||
|
||||
Date date = new Date(milliseconds);
|
||||
|
||||
assertEquals(expectedDate, date);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLongValue_whenUsingCalendarClass_thenConvert() throws ParseException {
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
Date expectedDate = dateFormat.parse("2023-07-15 22:00:00");
|
||||
long milliseconds = 1689458400000L;
|
||||
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
calendar.setTimeInMillis(milliseconds);
|
||||
|
||||
assertEquals(expectedDate, calendar.getTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLongValue_whenUsingJodaTimeLocalDateClass_thenConvert() {
|
||||
org.joda.time.LocalDate expectedDate = new org.joda.time.LocalDate(2023, 7, 15);
|
||||
long milliseconds = 1689458400000L;
|
||||
|
||||
org.joda.time.LocalDate date = new org.joda.time.LocalDate(milliseconds, DateTimeZone.UTC);
|
||||
|
||||
assertEquals(expectedDate, date);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
## Java Date/time conversion Cookbooks and Examples
|
||||
|
||||
This module contains articles about converting between Java date and time objects.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Convert Gregorian to Hijri Date in Java](https://www.baeldung.com/java-date-gregorian-hijri-conversion)
|
||||
- [Convert String Date to XMLGregorianCalendar in Java](https://www.baeldung.com/java-string-date-xmlgregoriancalendar-conversion)
|
|
@ -0,0 +1,56 @@
|
|||
<?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-datetime-conversion-2</artifactId>
|
||||
<name>core-java-datetime-conversion-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.msarhan</groupId>
|
||||
<artifactId>ummalqura-calendar</artifactId>
|
||||
<version>${ummalqura-calendar.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-datetime-conversion-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<joda-time.version>2.12.5</joda-time.version>
|
||||
<ummalqura-calendar.version>2.0.2</ummalqura-calendar.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.stringdatetoxmlgregoriancalendar;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import javax.xml.datatype.DatatypeConfigurationException;
|
||||
import javax.xml.datatype.DatatypeFactory;
|
||||
import javax.xml.datatype.XMLGregorianCalendar;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.format.DateTimeFormat;
|
||||
|
||||
public class StringDateToXMLGregorianCalendarConverter {
|
||||
public static XMLGregorianCalendar usingDatatypeFactoryForDate(String dateAsString) throws DatatypeConfigurationException {
|
||||
return DatatypeFactory.newInstance().newXMLGregorianCalendar(dateAsString);
|
||||
}
|
||||
|
||||
public static XMLGregorianCalendar usingLocalDate(String dateAsString) throws DatatypeConfigurationException {
|
||||
LocalDate localDate = LocalDate.parse(dateAsString);
|
||||
return DatatypeFactory.newInstance().newXMLGregorianCalendar(localDate.toString());
|
||||
}
|
||||
|
||||
public static XMLGregorianCalendar usingSimpleDateFormat(String dateTimeAsString) throws DatatypeConfigurationException, ParseException {
|
||||
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
|
||||
Date date = simpleDateFormat.parse(dateTimeAsString);
|
||||
return DatatypeFactory.newInstance().newXMLGregorianCalendar(simpleDateFormat.format(date));
|
||||
}
|
||||
|
||||
public static XMLGregorianCalendar usingGregorianCalendar(String dateTimeAsString) throws DatatypeConfigurationException, ParseException {
|
||||
GregorianCalendar calendar = new GregorianCalendar();
|
||||
calendar.setTime(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(dateTimeAsString));
|
||||
return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
|
||||
}
|
||||
|
||||
public static XMLGregorianCalendar usingJodaTime(String dateTimeAsString) throws DatatypeConfigurationException {
|
||||
DateTime dateTime = DateTime.parse(dateTimeAsString, DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss"));
|
||||
return DatatypeFactory.newInstance().newXMLGregorianCalendar(dateTime.toGregorianCalendar());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
package com.baeldung.stringdatetoxmlgregoriancalendar;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import javax.xml.datatype.DatatypeConfigurationException;
|
||||
import javax.xml.datatype.XMLGregorianCalendar;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class StringDateToXMLGregorianCalendarConverterUnitTest {
|
||||
private static final String dateAsString = "2014-04-24";
|
||||
private static final String dateTimeAsString = "2014-04-24T15:45:30";
|
||||
|
||||
@Test
|
||||
void givenStringDate_whenUsingDatatypeFactory_thenConvertToXMLGregorianCalendar() throws DatatypeConfigurationException {
|
||||
XMLGregorianCalendar xmlGregorianCalendar = StringDateToXMLGregorianCalendarConverter.usingDatatypeFactoryForDate(dateAsString);
|
||||
assertEquals(24,xmlGregorianCalendar.getDay());
|
||||
assertEquals(4,xmlGregorianCalendar.getMonth());
|
||||
assertEquals(2014,xmlGregorianCalendar.getYear());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringDateTime_whenUsingApacheCommonsLang3_thenConvertToXMLGregorianCalendar() throws DatatypeConfigurationException {
|
||||
XMLGregorianCalendar xmlGregorianCalendar = StringDateToXMLGregorianCalendarConverter.usingLocalDate(dateAsString);
|
||||
assertEquals(24,xmlGregorianCalendar.getDay());
|
||||
assertEquals(4,xmlGregorianCalendar.getMonth());
|
||||
assertEquals(2014,xmlGregorianCalendar.getYear());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringDateTime_whenUsingSimpleDateFormat_thenConvertToXMLGregorianCalendar() throws DatatypeConfigurationException, ParseException {
|
||||
XMLGregorianCalendar xmlGregorianCalendar = StringDateToXMLGregorianCalendarConverter.usingSimpleDateFormat(dateTimeAsString);
|
||||
assertEquals(24,xmlGregorianCalendar.getDay());
|
||||
assertEquals(4,xmlGregorianCalendar.getMonth());
|
||||
assertEquals(2014,xmlGregorianCalendar.getYear());
|
||||
assertEquals(15,xmlGregorianCalendar.getHour());
|
||||
assertEquals(45,xmlGregorianCalendar.getMinute());
|
||||
assertEquals(30,xmlGregorianCalendar.getSecond());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringDateTime_whenUsingGregorianCalendar_thenConvertToXMLGregorianCalendar() throws DatatypeConfigurationException, ParseException {
|
||||
XMLGregorianCalendar xmlGregorianCalendar = StringDateToXMLGregorianCalendarConverter.usingGregorianCalendar(dateTimeAsString);
|
||||
assertEquals(24,xmlGregorianCalendar.getDay());
|
||||
assertEquals(4,xmlGregorianCalendar.getMonth());
|
||||
assertEquals(2014,xmlGregorianCalendar.getYear());
|
||||
assertEquals(15,xmlGregorianCalendar.getHour());
|
||||
assertEquals(45,xmlGregorianCalendar.getMinute());
|
||||
assertEquals(30,xmlGregorianCalendar.getSecond());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringDateTime_whenUsingJodaTime_thenConvertToXMLGregorianCalendar() throws DatatypeConfigurationException {
|
||||
XMLGregorianCalendar xmlGregorianCalendar = StringDateToXMLGregorianCalendarConverter.usingJodaTime(dateTimeAsString);
|
||||
assertEquals(24,xmlGregorianCalendar.getDay());
|
||||
assertEquals(4,xmlGregorianCalendar.getMonth());
|
||||
assertEquals(2014,xmlGregorianCalendar.getYear());
|
||||
assertEquals(15,xmlGregorianCalendar.getHour());
|
||||
assertEquals(45,xmlGregorianCalendar.getMinute());
|
||||
assertEquals(30,xmlGregorianCalendar.getSecond());
|
||||
}
|
||||
}
|
|
@ -4,7 +4,6 @@
|
|||
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-datetime-conversion</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-datetime-conversion</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
@ -25,12 +24,6 @@
|
|||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.msarhan</groupId>
|
||||
<artifactId>ummalqura-calendar</artifactId>
|
||||
<version>${ummalqura-calendar.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -51,7 +44,6 @@
|
|||
|
||||
<properties>
|
||||
<joda-time.version>2.12.5</joda-time.version>
|
||||
<ummalqura-calendar.version>2.0.2</ummalqura-calendar.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -5,3 +5,4 @@ This module contains articles about parsing and formatting Java date and time ob
|
|||
### Relevant Articles:
|
||||
- [Convert String to Instant](https://www.baeldung.com/java-string-to-instant)
|
||||
- [Sort Date Strings in Java](https://www.baeldung.com/java-sort-date-strings)
|
||||
- [Using Current Time as Filename in Java](https://www.baeldung.com/java-current-time-filename)
|
||||
|
|
|
@ -6,3 +6,4 @@
|
|||
- [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain)
|
||||
- [Use Cases for Static Methods in Java](https://www.baeldung.com/java-static-methods-use-cases)
|
||||
- [TriFunction Interface in Java](https://www.baeldung.com/java-trifunction)
|
||||
- [Lazy Field Initialization with Lambdas](https://www.baeldung.com/java-lambda-lazy-field-initialization)
|
||||
|
|
|
@ -4,7 +4,7 @@ import java.util.function.Function;
|
|||
|
||||
public class Currying {
|
||||
|
||||
private static Function<Double, Function<Double, Double>> weight = mass -> gravity -> mass * gravity;
|
||||
private static Function<Double, Function<Double, Double>> weight = gravity -> mass -> mass * gravity;
|
||||
|
||||
private static Function<Double, Double> weightOnEarth = weight.apply(9.81);
|
||||
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue