Merge remote-tracking branch 'origin/PR-7308' into PR-7308

This commit is contained in:
parthiv39731 2023-12-16 00:17:01 +05:30
commit b8bf044313
437 changed files with 4387 additions and 1268 deletions

View File

@ -63,11 +63,6 @@
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
</dependencies>
<build>
@ -84,10 +79,9 @@
<mockserver.version>5.6.1</mockserver.version>
<wiremock.version>3.3.1</wiremock.version>
<!-- http client & core 5 -->
<httpcore5.version>5.2</httpcore5.version>
<httpclient5.version>5.2</httpclient5.version>
<httpclient5-fluent.version>5.2</httpclient5-fluent.version>
<httpclient.version>4.5.14</httpclient.version>
<httpcore5.version>5.2.2</httpcore5.version>
<httpclient5.version>5.2.2</httpclient5.version>
<httpclient5-fluent.version>5.2.2</httpclient5-fluent.version>
</properties>
</project>

View File

@ -25,6 +25,7 @@ import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBu
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
@ -33,7 +34,6 @@ import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.reactor.IOReactorConfig;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.junit.jupiter.api.Test;
@ -120,7 +120,7 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer {
.build();
final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
.setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSslContext(sslContext)
.build();

View File

@ -55,7 +55,7 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.databind.version} </version>
<version>${jackson.databind.version}</version>
</dependency>
</dependencies>

View File

@ -181,6 +181,7 @@
</build>
<properties>
<jackson.version>2.13.4</jackson.version>
<kafka.version>3.4.0</kafka.version>
<testcontainers-kafka.version>1.19.3</testcontainers-kafka.version>
<testcontainers-jupiter.version>1.15.3</testcontainers-jupiter.version>

View File

@ -29,7 +29,7 @@ import java.util.List;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class BackupCreatorIntegrationTest {
public class BackupCreatorUnitTest {
public static ObjectMapper mapper;
@Before

View File

@ -10,7 +10,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class WordCapitalizerIntegrationTest {
public class WordCapitalizerUnitTest {
@Test
public void givenDataSet_whenExecuteWordCapitalizer_thenReturnCapitalizedWords() throws Exception {

View File

@ -21,8 +21,7 @@ import org.junit.Ignore;
import org.junit.Test;
public class KafkaStreamsLiveTest {
private String bootstrapServers = "localhost:9092";
private Path stateDirectory;
private final String bootstrapServers = "localhost:9092";
@Test
@Ignore("it needs to have kafka broker running on local")
@ -44,8 +43,8 @@ public class KafkaStreamsLiveTest {
// Use a temporary directory for storing state, which will be automatically removed after the test.
try {
this.stateDirectory = Files.createTempDirectory("kafka-streams");
streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, this.stateDirectory.toAbsolutePath()
Path stateDirectory = Files.createTempDirectory("kafka-streams");
streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, stateDirectory.toAbsolutePath()
.toString());
} catch (final IOException e) {
throw new UncheckedIOException("Cannot create temporary directory", e);

View File

@ -1,7 +0,0 @@
## ASM
This module contains articles about ASM
### Relevant Articles:
- [A Guide to Java Bytecode Manipulation with ASM](https://www.baeldung.com/java-asm)

View File

@ -1,54 +0,0 @@
<?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>
<groupId>com.baeldung.examples</groupId>
<artifactId>asm</artifactId>
<version>1.0</version>
<name>asm</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-util</artifactId>
<version>${asm.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifestEntries>
<Premain-Class>
com.baeldung.examples.asm.instrumentation.Premain
</Premain-Class>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<asm.version>5.2</asm.version>
</properties>
</project>

View File

@ -1,7 +1,7 @@
<?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">
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>aws-dynamodb</artifactId>
<version>0.1.0-SNAPSHOT</version>
@ -40,22 +40,6 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>

View File

@ -34,22 +34,6 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>

View File

@ -63,6 +63,7 @@
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>${reactor.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -94,6 +95,7 @@
<spring.version>2.2.1.RELEASE</spring.version>
<awssdk.version>2.17.283</awssdk.version>
<lombok.version>1.18.20</lombok.version>
<reactor.version>3.6.0</reactor.version>
</properties>
</project>

View File

@ -39,27 +39,6 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<aws.java.sdk.version>2.20.52</aws.java.sdk.version>
<commons-codec-version>1.10.L001</commons-codec-version>

View File

@ -5,6 +5,13 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>aws-modules</artifactId>
<name>aws-modules</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
@ -15,12 +22,6 @@
</dependencies>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>aws-app-sync</module>
<module>aws-dynamodb</module>

View File

@ -167,7 +167,6 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<commons-lang3.version>3.9</commons-lang3.version>
<java.version>1.8</java.version>
<logback.version>1.2.3</logback.version>
</properties>
</project>

View File

@ -13,6 +13,13 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<pluginRepositories>
<pluginRepository>
<id>groovy-plugins-release</id>
<url>https://groovy.jfrog.io/artifactory/plugins-release-local</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
@ -156,8 +163,8 @@
<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>
<groovy.compiler.version>3.7.0</groovy.compiler.version>
<groovy-eclipse-batch.version>3.0.8-01</groovy-eclipse-batch.version>
<groovy.compiler.version>3.9.0</groovy.compiler.version>
<groovy-eclipse-batch.version>3.0.9-03</groovy-eclipse-batch.version>
</properties>
</project>

View File

@ -45,7 +45,7 @@
<properties>
<maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version>
<jackson.version>2.14.1</jackson.version>
<jackson.version>2.16.0</jackson.version>
<gson.version>2.10</gson.version>
</properties>

View File

@ -21,8 +21,4 @@
</dependency>
</dependencies>
<properties>
<java.version>17</java.version>
</properties>
</project>

View File

@ -13,8 +13,4 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<java.version>17</java.version>
</properties>
</project>

View File

@ -26,8 +26,4 @@
</dependency>
</dependencies>
<properties>
<java.version>17</java.version>
</properties>
</project>

View File

@ -3,19 +3,34 @@
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-20</artifactId>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>core-java-20</artifactId>
<properties>
<maven.compiler.source>20</maven.compiler.source>
<maven.compiler.target>20</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.24.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
@ -41,25 +56,10 @@
</plugins>
</build>
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.24.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>20</maven.compiler.source>
<maven.compiler.target>20</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -11,3 +11,4 @@ This module contains articles about arrays conversion in Java
- [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset)
- [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)

View File

@ -57,7 +57,7 @@
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.release>11</maven.compiler.release>
</properties>

View File

@ -43,7 +43,6 @@
<properties>
<vavr.version>0.10.3</vavr.version>
<java.version>11</java.version>
<modelmapper.version>3.2.0</modelmapper.version>
</properties>
</project>

View File

@ -39,7 +39,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
@ -67,7 +67,7 @@
<jmh.version>1.21</jmh.version>
<commons-lang.version>2.2</commons-lang.version>
<gson.version>2.10.1</gson.version>
<jackson.version>2.15.2</jackson.version>
<jackson.version>2.16.0</jackson.version>
<org.json.version>20230618</org.json.version>
</properties>
</project>

View File

@ -13,14 +13,11 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<spring.version>5.2.5.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.1</version>
<version>2.16.0</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
@ -51,4 +48,8 @@
</dependency>
</dependencies>
<properties>
<spring.version>5.2.5.RELEASE</spring.version>
</properties>
</project>

View File

@ -4,5 +4,7 @@
- [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv)
- [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-max-size)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)
- [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 Increment a Map Value in Java](https://www.baeldung.com/java-increment-map-value)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)

View File

@ -1,15 +1,11 @@
<?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">
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-collections-maps-7</artifactId>
<name>core-java-collections-maps-7</name>
<packaging>jar</packaging>
<properties>
<gson.version>2.10.1</gson.version>
<csv.version>1.5</csv.version>
</properties>
<parent>
<artifactId>core-java-modules</artifactId>
@ -63,4 +59,10 @@
</plugin>
</plugins>
</build>
<properties>
<gson.version>2.10.1</gson.version>
<csv.version>1.5</csv.version>
</properties>
</project>

View File

@ -0,0 +1,150 @@
package com.baeldung.concurrent.completablefuture;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import org.junit.Test;
public class CompletableFutureUnitTest {
@Test
public void givenAsyncTask_whenProcessingAsyncSucceed_thenReturnSuccess() throws ExecutionException, InterruptedException {
Microservice mockMicroserviceA = mock(Microservice.class);
Microservice mockMicroserviceB = mock(Microservice.class);
when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello"));
when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("World"));
CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
String result = resultFuture.get();
assertEquals("HelloWorld", result);
}
@Test
public void givenAsyncTask_whenProcessingAsyncWithException_thenReturnException() throws ExecutionException, InterruptedException {
Microservice mockMicroserviceA = mock(Microservice.class);
Microservice mockMicroserviceB = mock(Microservice.class);
when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello"));
when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.failedFuture(new RuntimeException("Simulated Exception")));
CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
// Use assertThrows to verify that the expected exception is thrown
ExecutionException exception = assertThrows(ExecutionException.class, resultFuture::get);
// Assert the exception message
assertEquals("Simulated Exception", exception.getCause()
.getMessage());
}
@Test
public void givenAsyncTask_whenProcessingAsyncWithTimeout_thenHandleTimeoutException() throws ExecutionException, InterruptedException {
Microservice mockMicroserviceA = mock(Microservice.class);
Microservice mockMicroserviceB = mock(Microservice.class);
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor));
Executor delayedExecutor2 = CompletableFuture.delayedExecutor(500, TimeUnit.MILLISECONDS);
when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.supplyAsync(() -> "World", delayedExecutor2));
CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
assertThrows(TimeoutException.class, () -> resultFuture.get(300, TimeUnit.MILLISECONDS));
}
@Test
public void givenCompletableFuture_whenCompleted_thenStateIsDone() {
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> " World");
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
assertFalse(allCf.isDone());
allCf.join();
String result = Arrays.stream(cfs)
.map(CompletableFuture::join)
.collect(Collectors.joining());
assertFalse(allCf.isCancelled());
assertTrue(allCf.isDone());
assertFalse(allCf.isCompletedExceptionally());
assertEquals(result, "Hello World!");
}
@Test
public void givenCompletableFuture_whenCompletedWithException_thenStateIsCompletedExceptionally() throws ExecutionException, InterruptedException {
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
CompletableFuture<String> cf2 = CompletableFuture.failedFuture(new RuntimeException("Simulated Exception"));
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
assertFalse(allCf.isDone());
assertFalse(allCf.isCompletedExceptionally());
// Exception is expected, assert the cause
CompletionException exception = assertThrows(CompletionException.class, allCf::join);
assertEquals("Simulated Exception", exception.getCause()
.getMessage());
assertTrue(allCf.isCompletedExceptionally());
assertTrue(allCf.isDone());
assertFalse(allCf.isCancelled());
}
@Test
public void givenCompletableFuture_whenCancelled_thenStateIsCancelled() throws ExecutionException, InterruptedException {
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> " World");
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
assertFalse(allCf.isDone());
assertFalse(allCf.isCompletedExceptionally());
allCf.cancel(true);
assertTrue(allCf.isCancelled());
assertTrue(allCf.isDone());
}
CompletableFuture<String> processAsync(List<Microservice> microservices) {
List<CompletableFuture<String>> dataFetchFutures = fetchDataAsync(microservices);
return combineResults(dataFetchFutures);
}
private List<CompletableFuture<String>> fetchDataAsync(List<Microservice> microservices) {
return microservices.stream()
.map(client -> client.retrieveAsync(""))
.collect(Collectors.toList());
}
private CompletableFuture<String> combineResults(List<CompletableFuture<String>> dataFetchFutures) {
return CompletableFuture.allOf(dataFetchFutures.toArray(new CompletableFuture[0]))
.thenApply(v -> dataFetchFutures.stream()
.map(future -> future.exceptionally(ex -> {
throw new CompletionException(ex);
})
.join())
.collect(Collectors.joining()));
}
interface Microservice {
CompletableFuture<String> retrieveAsync(String input);
}
}

View File

@ -11,3 +11,4 @@ This module contains articles about converting between Java date and time object
- [Conversion From 12-Hour Time to 24-Hour Time in Java](https://www.baeldung.com/java-convert-time-format)
- [Convert Epoch Time to LocalDate and LocalDateTime](https://www.baeldung.com/java-convert-epoch-localdate)
- [Convert Timestamp String to Long in Java](https://www.baeldung.com/java-convert-timestamp-string-long)
- [Convert Long Timestamp to LocalDateTime in Java](https://www.baeldung.com/java-convert-long-timestamp-localdatetime)

View File

@ -0,0 +1,16 @@
package com.baeldung.lazylambda;
import java.util.function.Supplier;
public class LambdaSupplier<T> {
protected final Supplier<T> expensiveData;
public LambdaSupplier(Supplier<T> expensiveData) {
this.expensiveData = expensiveData;
}
public T getData() {
return expensiveData.get();
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.lazylambda;
import java.util.function.Supplier;
public class LazyLambdaSupplier<T> extends LambdaSupplier<T> {
private T data;
public LazyLambdaSupplier(Supplier<T> expensiveData) {
super(expensiveData);
}
@Override
public T getData() {
if (data != null) {
return data;
}
return data = expensiveData.get();
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.lazylambda;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
public class LazyLambdaThreadSafeSupplier<T> extends LambdaSupplier<T> {
private final AtomicReference<T> data;
public LazyLambdaThreadSafeSupplier(Supplier<T> expensiveData) {
super(expensiveData);
data = new AtomicReference<>();
}
public T getData() {
if (data.get() == null) {
synchronized (data) {
if (data.get() == null) {
data.set(expensiveData.get());
}
}
}
return data.get();
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.lazylambda;
import java.util.function.Supplier;
import org.junit.Test;
import org.mockito.Mockito;
public class LambdaSupplierUnitTest {
@Test
public void whenCalledMultipleTimes_thenShouldBeCalledMultipleTimes() {
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
Mockito.when(mockedExpensiveFunction.get())
.thenReturn("expensive call");
LambdaSupplier<String> testee = new LambdaSupplier<>(mockedExpensiveFunction);
Mockito.verify(mockedExpensiveFunction, Mockito.never())
.get();
testee.getData();
testee.getData();
Mockito.verify(mockedExpensiveFunction, Mockito.times(2))
.get();
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.lazylambda;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
public class LazyLambdaSupplierUnitTest {
@Test
public void whenCalledMultipleTimes_thenShouldBeCalledOnlyOnce() {
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
Mockito.when(mockedExpensiveFunction.get())
.thenReturn("expensive call");
LazyLambdaSupplier<String> testee = new LazyLambdaSupplier<>(mockedExpensiveFunction);
Mockito.verify(mockedExpensiveFunction, Mockito.never())
.get();
testee.getData();
testee.getData();
Mockito.verify(mockedExpensiveFunction, Mockito.times(1))
.get();
}
@Test
public void whenCalledMultipleTimesConcurrently_thenShouldBeCalledMultipleTimes() throws InterruptedException {
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
Mockito.when(mockedExpensiveFunction.get())
.thenAnswer((Answer<String>) invocation -> {
Thread.sleep(1000L);
return "Late response!";
});
LazyLambdaSupplier<String> testee = new LazyLambdaSupplier<>(mockedExpensiveFunction);
Mockito.verify(mockedExpensiveFunction, Mockito.never())
.get();
ExecutorService executorService = Executors.newFixedThreadPool(4);
executorService.invokeAll(List.of(testee::getData, testee::getData));
executorService.shutdown();
if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
Mockito.verify(mockedExpensiveFunction, Mockito.times(2))
.get();
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.lazylambda;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
public class LazyLambdaThreadSafeSupplierUnitTest {
@Test
public void whenCalledMultipleTimes_thenShouldBeCalledOnlyOnce() {
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
Mockito.when(mockedExpensiveFunction.get())
.thenReturn("expensive call");
LazyLambdaThreadSafeSupplier<String> testee = new LazyLambdaThreadSafeSupplier<>(mockedExpensiveFunction);
Mockito.verify(mockedExpensiveFunction, Mockito.never())
.get();
testee.getData();
testee.getData();
Mockito.verify(mockedExpensiveFunction, Mockito.times(1))
.get();
}
@Test
public void whenCalledMultipleTimesConcurrently_thenShouldBeCalledOnlyOnce() throws InterruptedException {
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
Mockito.when(mockedExpensiveFunction.get())
.thenAnswer((Answer<String>) invocation -> {
Thread.sleep(1000L);
return "Late response!";
});
LazyLambdaThreadSafeSupplier<String> testee = new LazyLambdaThreadSafeSupplier<>(mockedExpensiveFunction);
Mockito.verify(mockedExpensiveFunction, Mockito.never())
.get();
ExecutorService executorService = Executors.newFixedThreadPool(4);
executorService.invokeAll(List.of(testee::getData, testee::getData));
executorService.shutdown();
if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
Mockito.verify(mockedExpensiveFunction, Mockito.times(1))
.get();
}
}

View File

@ -9,3 +9,5 @@ This module contains articles about core features in the Java language
- [Get a Random Element From a Set in Java](https://www.baeldung.com/java-set-draw-sample)
- [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code)
- [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects)
- [Return First Non-null Value in Java](https://www.baeldung.com/java-first-non-null)
- [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables)

View File

@ -23,6 +23,16 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
@ -39,6 +49,11 @@
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
<path>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
@ -50,6 +65,7 @@
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mapstruct.version>1.6.0.Beta1</mapstruct.version>
<jmh.version>1.37</jmh.version>
</properties>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.staticfinal;
import java.util.HashMap;
public class Bike {
public static final int TIRE = 2;
public static final int PEDAL;
public static final HashMap<String, Integer> PART = new HashMap<>();
static {
PEDAL = 5;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.recursivelysumintarray;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class RecursivelySumIntArrayUnitTest {
private static final int[] INT_ARRAY = { 1, 2, 3, 4, 5 };
static int sumIntArray1(int[] array) {
if (array.length == 1) {
return array[0];
} else {
return array[0] + sumIntArray1(Arrays.copyOfRange(array, 1, array.length));
}
}
static int sumIntArray2(int[] array, int index) {
if (index == 0) {
return array[index];
} else {
return array[index] + sumIntArray2(array, index - 1);
}
}
@Test
void whenUsingSumIntArray1_thenGetExpectedResult() {
assertEquals(15, sumIntArray1(INT_ARRAY));
}
@Test
void whenUsingSumIntArray2_thenGetExpectedResult() {
assertEquals(15, sumIntArray2(INT_ARRAY, INT_ARRAY.length - 1));
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.recursivelysumintarray;
import static com.baeldung.recursivelysumintarray.RecursivelySumIntArrayUnitTest.sumIntArray1;
import static com.baeldung.recursivelysumintarray.RecursivelySumIntArrayUnitTest.sumIntArray2;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@BenchmarkMode(Mode.AverageTime)
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 2)
@Fork(1)
@Measurement(iterations = 5)
public class SumArrayBenchmark {
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder().include(SumArrayBenchmark.class.getSimpleName())
.build();
new Runner(options).run();
}
@Param({ "10", "10000" })
public int size;
int[] array;
@Setup
public void setup() {
var r = new Random();
array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = r.nextInt();
}
}
@Benchmark
public int withArrayCopy() {
return sumIntArray1(array);
}
@Benchmark
public int withoutArrayCopy() {
return sumIntArray2(array, array.length - 1);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.staticfinal;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class BikeUnitTest {
@Test
void givenTireConstantSetUponDeclaration_whenGetTire_thenReturnTwo() {
assertEquals(2, Bike.TIRE);
}
@Test
void givenPedalConstantSetByStaticBlock_whenGetPedal_thenReturnFive() {
assertEquals(5, Bike.PEDAL);
}
@Test
void givenPartConstantObject_whenObjectStateChanged_thenCorrect() {
Bike.PART.put("seat", 1);
assertEquals(1, Bike.PART.get("seat"));
Bike.PART.put("seat", 5);
assertEquals(5, Bike.PART.get("seat"));
}
@Test
void givenMathClass_whenAccessingPiConstant_thenVerifyPiValueIsCorrect() {
assertEquals(3.141592653589793, Math.PI);
}
}

View File

@ -10,3 +10,4 @@ This module contains articles about Java operators
- [Check if at Least Two Out of Three Booleans Are True in Java](https://www.baeldung.com/java-check-two-of-three-booleans)
- [Alternatives for instanceof Operator in Java](https://www.baeldung.com/java-instanceof-alternatives)
- [What Does “––>” Mean in Java?](https://www.baeldung.com/java-minus-minus-greaterthan)
- [All the Ways Java Uses the Colon Character](https://www.baeldung.com/java-colon)

View File

@ -0,0 +1,178 @@
package com.baeldung.colonexamples;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.util.*;
import java.util.stream.Collectors;
/**
* Examples of the different ways Java uses the colon (:) character.
*/
public class ColonExamples {
private final static Logger LOG = LoggerFactory.getLogger(ColonExamples.class);
public void example1_enhancedForLoop() {
// Original style
for(int i = 0; i < 10; i++) {
// do something
}
// Using enhanced for loop
int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
for(int i : numbers) {
// do something
}
// Using List instead of array
List<Integer> numbersList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
for(Integer i : numbersList) {
// do something
}
}
public void example2_switchStatement(String animal) {
// Original style
if(animal.equals("cat")) {
System.out.println("meow");
}
else if(animal.equals("lion")) {
System.out.println("roar");
}
else if(animal.equals("dog") || animal.equals("seal")) {
System.out.println("bark");
}
else {
System.out.println("unknown");
}
// Using switch statement
switch(animal) {
case "cat":
System.out.println("meow");
break;
case "lion":
System.out.println("roar");
break;
case "dog":
case "seal":
System.out.println("bark");
break;
default:
System.out.println("unknown");
}
}
public void example3_labels() {
// For loops without labels
for(int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (checkSomeCondition()) {
break;
}
}
}
outterLoop: for(int i = 0; i < 10; i++) {
innerLoop: for (int j = 0; j < 10; j++) {
if (checkSomeCondition()) {
break outterLoop;
}
}
}
}
public void example4_ternaryOperator() {
// Original way using if/else
int x;
if(checkSomeCondition()) {
x = 1;
}
else {
x = 2;
}
// Using ternary operator
x = checkSomeCondition() ? 1 : 2;
// Using with other statements
boolean remoteCallResult = callRemoteApi();
LOG.info(String.format(
"The result of the remote API call %s successful",
remoteCallResult ? "was" : "was not"
));
}
public void example5_methodReferences() {
// Original way without lambdas and method references
List<String> names = Arrays.asList("ross", "joey", "chandler");
List<String> upperCaseNames = new ArrayList<>();
for(String name : names) {
upperCaseNames.add(name.toUpperCase());
}
// Using method reference with stream map operation
List<String> petNames = Arrays.asList("ross", "joey", "chandler");
List<String> petUpperCaseNames = petNames
.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
// Method reference with stream filter
List<Animal> pets = Arrays.asList(new Cat(), new Dog(), new Parrot());
List<Animal> onlyDogs = pets
.stream()
.filter(Dog.class::isInstance)
.collect(Collectors.toList());
// Method reference with constructors
Set<Animal> onlyDogsSet = pets
.stream()
.filter(Dog.class::isInstance)
.collect(Collectors.toCollection(TreeSet::new));
}
public void example6_asserttion() {
// Original way without assertions
Connection conn = getConnection();
if(conn == null) {
throw new RuntimeException("Connection is null");
}
// Using assert keyword
assert getConnection() != null : "Connection is null";
}
private boolean checkSomeCondition() {
return new Random().nextBoolean();
}
private boolean callRemoteApi() {
return new Random().nextBoolean();
}
private Connection getConnection() {
return null;
}
private static interface Animal {
}
private static class Dog implements Animal {
}
private static class Cat implements Animal {
}
private static class Parrot implements Animal {
}
}

View File

@ -0,0 +1,2 @@
## Relevant Articles
- [Check if a double Is an Integer in Java](https://www.baeldung.com/java-check-double-integer)

View File

@ -0,0 +1,37 @@
<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-numbers-7</artifactId>
<name>core-java-numbers-7</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>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-numbers-7</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,39 @@
package com.baeldung.bigdecimalzero;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.*;
public class BigDecimalZeroVsNewBigDecimalUnitTest {
@Test
void whenComparingZeroAndNewBigDecimal_thenGetExpectedResult() {
BigDecimal bd1 = new BigDecimal("42.00");
BigDecimal bd2 = new BigDecimal("42.0000");
assertEquals(0, bd1.compareTo(bd2));
assertNotEquals(bd1, bd2);
BigDecimal zero0 = new BigDecimal(0);
assertNotEquals(zero0, new BigDecimal("0.000"));
BigDecimal zero = BigDecimal.ZERO;
assertEquals(zero, zero0);
}
@Test
void whenCallingBigDecimalZero_thenAlwaysGetTheSameObject() {
BigDecimal z1 = BigDecimal.ZERO;
BigDecimal z2 = BigDecimal.ZERO;
assertSame(z1, z2);
}
@Test
void whenCallingNewBigDecimal_thenAlwaysGetTheSameObject() {
BigDecimal z1 = new BigDecimal(0);
BigDecimal z2 = new BigDecimal(0);
assertNotSame(z1, z2);
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.doubleisint;
import com.google.common.math.DoubleMath;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class CheckDoubleIsAnIntegerUnitTest {
boolean notNaNOrInfinity(double d) {
return !(Double.isNaN(d) || Double.isInfinite(d));
}
@Test
void whenConvertingToInt_thenGetExpectedResult() {
double d1 = 42.0D;
boolean d1IsInteger = notNaNOrInfinity(d1) && (int) d1 == d1;
assertTrue(d1IsInteger);
double d2 = 42.42D;
boolean d2IsInteger = notNaNOrInfinity(d2) && (int) d2 == d2;
assertFalse(d2IsInteger);
double d3 = 2.0D * Integer.MAX_VALUE;
boolean d3IsInteger = notNaNOrInfinity(d3) && (int) d3 == d3;
assertTrue(!d3IsInteger); // <-- fails if exceeding Integer's range
}
@Test
void whenUsingModuloOperator_thenGetExpectedResult() {
double d1 = 42.0D;
boolean d1IsInteger = notNaNOrInfinity(d1) && (d1 % 1) == 0;
assertTrue(d1IsInteger);
double d2 = 42.42D;
boolean d2IsInteger = notNaNOrInfinity(d2) && (d2 % 1) == 0;
assertFalse(d2IsInteger);
double d3 = 2.0D * Integer.MAX_VALUE;
boolean d3IsInteger = notNaNOrInfinity(d3) && (d3 % 1) == 0;
assertTrue(d3IsInteger);
}
@Test
void whenCheckingFloorOrCeilingValue_thenGetExpectedResult() {
double d1 = 42.0D;
boolean d1IsInteger = notNaNOrInfinity(d1) && Math.floor(d1) == d1;
assertTrue(d1IsInteger);
double d2 = 42.42D;
boolean d2IsInteger = notNaNOrInfinity(d2) && Math.floor(d2) == d2;
assertFalse(d2IsInteger);
double d3 = 2.0D * Integer.MAX_VALUE;
boolean d3IsInteger = notNaNOrInfinity(d3) && Math.floor(d3) == d3;
assertTrue(d3IsInteger);
}
@Test
void whenUsingGuava_thenGetExpectedResult() {
double d1 = 42.0D;
boolean d1IsInteger = DoubleMath.isMathematicalInteger(d1);
assertTrue(d1IsInteger);
double d2 = 42.42D;
boolean d2IsInteger = DoubleMath.isMathematicalInteger(d2);
assertFalse(d2IsInteger);
double d3 = 2.0D * Integer.MAX_VALUE;
boolean d3IsInteger = DoubleMath.isMathematicalInteger(d3);
assertTrue(d3IsInteger);
boolean isInfinityInt = DoubleMath.isMathematicalInteger(Double.POSITIVE_INFINITY);
assertFalse(isInfinityInt);
boolean isNanInt = DoubleMath.isMathematicalInteger(Double.NaN);
assertFalse(isNanInt);
}
}

View File

@ -4,3 +4,5 @@
- [Convert int to Long in Java](https://www.baeldung.com/java-convert-int-long)
- [How To Convert Double To Float In Java](https://www.baeldung.com/java-convert-double-float)
- [Converting from float to BigDecimal in Java](https://www.baeldung.com/java-convert-float-bigdecimal)
- [Convert Positive Integer to Negative and Vice Versa in Java](https://www.baeldung.com/java-negating-integer)
- [Rounding Up a Number to Nearest Multiple of 5 in Java](https://www.baeldung.com/java-round-nearest-multiple-five)

View File

@ -23,7 +23,7 @@ public class AppUnitTest {
soundRecorder.build(af);
try {
soundRecorder.start();
Thread.sleep(20000);
Thread.sleep(5000);
soundRecorder.stop();
} catch (InterruptedException ex) {
fail("Exception: " + ex);

View File

@ -69,7 +69,7 @@ public class ProcessApiUnitTest {
});
});
Thread.sleep(10000);
Thread.sleep(5000);
childProc = ProcessHandle.current().children();
childProc.forEach(procHandle -> {
@ -100,7 +100,7 @@ public class ProcessApiUnitTest {
private void waistCPU() throws NoSuchAlgorithmException {
ArrayList<Integer> randArr = new ArrayList<Integer>(4096);
SecureRandom sr = SecureRandom.getInstanceStrong();
Duration somecpu = Duration.ofMillis(4200L);
Duration somecpu = Duration.ofMillis(2000L);
Instant end = Instant.now().plus(somecpu);
while (Instant.now().isBefore(end)) {
// System.out.println(sr.nextInt());

View File

@ -1,7 +1,7 @@
<?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">
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-reflection-3</artifactId>
<name>core-java-reflection-3</name>

View File

@ -5,4 +5,5 @@ This module contains articles about core Java Security
### Relevant Articles:
- [Check if Certificate Is Self-Signed or CA-Signed With Java](https://www.baeldung.com/java-check-certificate-sign)
- [Extract CN From X509 Certificate in Java](https://www.baeldung.com/java-extract-common-name-x509-certificate)
- [Check Certificate Name and Alias in Keystore File](https://www.baeldung.com/java-keystore-check-certificate-name-alias)
- More articles: [[<-- prev]](/core-java-modules/core-java-security-3)

View File

@ -71,7 +71,7 @@
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>${io.reactor3.version}</version>
<version>${reactor-core.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
@ -121,7 +121,7 @@
<rx.java2.version>2.2.2</rx.java2.version>
<rx.java3.version>3.1.5</rx.java3.version>
<io.varv.version>1.0.0-alpha-4</io.varv.version>
<io.reactor3.version>3.5.1</io.reactor3.version>
<reactor-core.version>3.6.0</reactor-core.version>
<apache.commons.collection4.version>4.4</apache.commons.collection4.version>
<cyclops.version>10.4.1</cyclops.version>
</properties>

View File

@ -48,6 +48,11 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,21 @@
package com.baeldung.streams.firstmatchingelement;
public class User {
private String userName;
private Integer userId;
public User(Integer userId, String userName) {
this.userId = userId;
this.userName = userName;
}
public String getUserName() {
return userName;
}
public Integer getUserId() {
return userId;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.findfirstnullpointerexception;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import org.junit.Test;
public class FindFirstNullPointerExceptionUnitTest {
private final List<String> inputs = Arrays.asList(null, "foo", "bar");
@Test(expected = NullPointerException.class)
public void givenStream_whenCallingFindFirst_thenThrowNullPointerException() {
Optional<String> firstElement = inputs.stream()
.findFirst();
}
@Test
public void givenStream_whenUsingOfNullableBeforeFindFirst_thenCorrect() {
Optional<String> firstElement = inputs.stream()
.map(Optional::ofNullable)
.findFirst()
.flatMap(Function.identity());
assertTrue(firstElement.isEmpty());
}
@Test
public void givenStream_whenUsingFilterBeforeFindFirst_thenCorrect() {
Optional<String> firstNonNullElement = inputs.stream()
.filter(Objects::nonNull)
.findFirst();
assertTrue(firstNonNullElement.isPresent());
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.streams.firstmatchingelement;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import org.apache.commons.collections4.IterableUtils;
import org.junit.Test;
import com.google.common.collect.Iterables;
public class FirstMatchingElementUnitTest {
private List<User> userList = List.of(new User(1, "David"), new User(2, "John"), new User(3, "Roger"), new User(4, "John"));
private String searchName = "John";
@Test
public void whenUsingStream_thenFindFirstMatchingUserIndex() {
AtomicInteger counter = new AtomicInteger(-1);
int index = userList.stream()
.filter(user -> {
counter.getAndIncrement();
return searchName.equals(user.getUserName());
})
.mapToInt(user -> counter.get())
.findFirst()
.orElse(-1);
assertEquals(1, index);
}
@Test
public void whenUsingIntStream_thenFindFirstMatchingUserIndex() {
int index = IntStream.range(0, userList.size() - 1)
.filter(streamIndex -> searchName.equals(userList.get(streamIndex).getUserName()))
.findFirst()
.orElse(-1);
assertEquals(1, index);
}
@Test
public void whenUsingTakeWhile_thenFindFirstMatchingUserIndex() {
long predicateIndex = userList.stream()
.takeWhile(user -> !user.getUserName().equals(searchName))
.count();
assertEquals(1, predicateIndex);
}
@Test
public void whenUsingTakeWhile_thenFindIndexFromNoMatchingElement() {
List<User> userList = List.of(new User(1, "David"), new User(2, "Vick"), new User(3, "Roger"), new User(4, "James"));
long predicateIndex = userList.stream()
.takeWhile(user -> !user.getUserName().equals(searchName))
.count();
assertEquals(4, predicateIndex);
}
@Test
public void whenUsingGoogleGuava_thenFindFirstMatchingUserIndex() {
int index = Iterables.indexOf(userList, user -> searchName.equals(user.getUserName()));
assertEquals(1, index);
}
@Test
public void whenUsingApacheCommons_thenFindFirstMatchingUserIndex() {
int index = IterableUtils.indexOf(userList, user -> searchName.equals(user.getUserName()));
assertEquals(1, index);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.skipinputstream;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import static org.junit.Assert.assertArrayEquals;
public class SkipInputStreamUnitTest {
@Test
public void givenInputStreamWithBytes_whenSkipBytes_thenRemainingBytes() throws IOException {
byte[] inputData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
InputStream inputStream = new ByteArrayInputStream(inputData);
long bytesToSkip = 3;
long skippedBytes = inputStream.skip(bytesToSkip);
assertArrayEquals(new byte[]{4, 5, 6, 7, 8, 9, 10}, readRemainingBytes(inputStream));
assert skippedBytes == bytesToSkip : "Incorrect number of bytes skipped";
}
private byte[] readRemainingBytes(InputStream inputStream) throws IOException {
byte[] buffer = new byte[inputStream.available()];
int bytesRead = inputStream.read(buffer);
if (bytesRead == -1) {
throw new IOException("End of stream reached");
}
return buffer;
}
}

View File

@ -44,10 +44,10 @@
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-core.version}</version>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-core.version}</version>
</dependency>
</dependencies>

View File

@ -72,7 +72,7 @@
<spring-core.version>5.3.9</spring-core.version>
<maven-artifact.version>3.6.3</maven-artifact.version>
<gradle-core.version>6.1.1</gradle-core.version>
<jackson-core.version>2.11.1</jackson-core.version>
<jackson-core.version>2.16.0</jackson-core.version>
<semver4j.version>3.1.0</semver4j.version>
</properties>

View File

@ -87,7 +87,7 @@ public class VersionComparisonUnitTest {
assertTrue(version1_1_maven.compareTo(version1_1_gradle) < 0);
Version version1_1_snapshot = new Version(1, 1, 0, "snapshot", null, null);
assertEquals(0, version1_1.compareTo(version1_1_snapshot));
assertEquals(1, version1_1.compareTo(version1_1_snapshot));
assertTrue(version1_1_snapshot.isSnapshot());
}

View File

@ -0,0 +1,35 @@
package com.baeldung.stringmaxlength;
public class StringMaxLengthMain {
public static void main(String[] args) {
displayRuntimeMaxStringLength();
displayMaxStringLength();
simulateStringOverflow();
}
public static void simulateStringOverflow() {
try {
int maxLength = Integer.MAX_VALUE;
char[] charArray = new char[maxLength];
for (int i = 0; i < maxLength; i++) {
charArray[i] = 'a';
}
String longString = new String(charArray);
System.out.println("Successfully created a string of length: " + longString.length());
} catch (OutOfMemoryError e) {
System.err.println("Overflow error: Attempting to create a string longer than Integer.MAX_VALUE");
e.printStackTrace();
}
}
public static void displayRuntimeMaxStringLength() {
long maxMemory = Runtime.getRuntime().maxMemory();
System.out.println("Maximum String length based on available memory: " + (maxMemory));
}
public static void displayMaxStringLength() {
int maxStringLength = Integer.MAX_VALUE;
System.out.println("Maximum String length based on Integer.MAX_VALUE: " + maxStringLength);
}
}

View File

@ -28,6 +28,7 @@ public class ComparePerformance {
@Benchmark
public String benchmarkStringConcatenation() {
strFinal = "";
strFinal += strInitial;
return strFinal;
}

View File

@ -6,3 +6,4 @@
- [Validate UUID String in Java](https://www.baeldung.com/java-validate-uuid-string)
- [Generate the Same UUID From a String in Java](https://www.baeldung.com/java-generate-same-uuid-from-string)
- [Generating Time Based UUIDs](https://www.baeldung.com/java-generating-time-based-uuids)
- [Generating Unique Positive long Using UUID in Java](https://www.baeldung.com/java-uuid-unique-long-generation)

View File

@ -59,16 +59,16 @@
<module>core-java-lang-oop-constructors-2</module>
<module>core-java-methods</module>
<module>core-java-networking-3</module>
<module>core-java-os</module>
<!--<module>core-java-os</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-perf-2</module>
<module>core-java-streams-4</module>
<module>core-java-streams-5</module>
<module>core-java-streams-collect</module>
<module>core-java-streams-maps</module>
<module>core-java-string-algorithms-3</module>
<module>core-java-string-operations-3</module>
<!--<module>core-java-string-operations-3</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-string-operations-4</module>
<module>core-java-string-operations-5</module>
<!--<module>core-java-string-operations-5</module>--> <!-- failing after upgrading to jdk17 -->
<!--<module>core-java-strings</module> Failing test cases JAVA-24414-->
<module>core-java-time-measurements</module>
<module>core-java-annotations</module>
@ -123,13 +123,13 @@
<module>core-java-io</module>
<module>core-java-io-2</module>
<module>core-java-io-3</module>
<module>core-java-io-4</module>
<!--<module>core-java-io-4</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-io-5</module>
<module>core-java-io-apis</module>
<module>core-java-io-apis-2</module>
<module>core-java-io-conversions</module>
<module>core-java-jar</module>
<module>core-java-jndi</module>
<!--<module>core-java-jndi</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-jvm</module>
<module>core-java-jvm-2</module>
<module>core-java-jvm-3</module>
@ -144,11 +144,11 @@
<module>core-java-lang-oop-constructors</module>
<module>core-java-lang-oop-patterns</module>
<module>core-java-lang-oop-generics</module>
<module>core-java-lang-oop-modifiers</module>
<!--<module>core-java-lang-oop-modifiers</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-lang-oop-types</module>
<module>core-java-lang-oop-types-2</module>
<module>core-java-lang-oop-inheritance</module>
<module>core-java-lang-oop-methods</module>
<!--<module>core-java-lang-oop-methods</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-lang-oop-others</module>
<module>core-java-lang-operators</module>
<module>core-java-lang-operators-2</module>
@ -166,6 +166,7 @@
<module>core-java-numbers-4</module>
<module>core-java-numbers-5</module>
<module>core-java-numbers-6</module>
<module>core-java-numbers-7</module>
<module>core-java-optional</module>
<module>core-java-perf</module>
<module>core-java-properties</module>
@ -184,8 +185,8 @@
<module>core-java-string-algorithms</module>
<module>core-java-string-algorithms-2</module>
<module>core-java-string-apis</module>
<!--<module>core-java-string-apis-2</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-swing</module>
<module>core-java-string-apis-2</module>
<module>core-java-string-conversions</module>
<module>core-java-string-conversions-2</module>
<module>core-java-string-conversions-3</module>
@ -225,5 +226,4 @@
</dependency>
</dependencies>
</dependencyManagement>
</project>

View File

@ -68,7 +68,6 @@
<properties>
<dl4j.version>0.9.1</dl4j.version> <!-- Latest non beta version -->
<httpclient.version>4.3.5</httpclient.version>
<lombok.version>1.18.20</lombok.version>
</properties>
</project>

View File

@ -25,8 +25,6 @@
</dependencyManagement>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<guava.version>32.1.3-jre</guava.version>
</properties>

View File

@ -27,6 +27,7 @@
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>${reactor.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -45,7 +46,7 @@
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<version>2.7.1</version>
<version>${jib-maven-plugin.version}</version>
<configuration>
<to>
<image>docker-demo-jib</image>
@ -55,4 +56,10 @@
</plugins>
</build>
<properties>
<reactor.version>3.6.0</reactor.version>
<jib-maven-plugin.version>2.7.1</jib-maven-plugin.version>
</properties>
</project>

View File

@ -24,8 +24,4 @@
<module>docker-java-jar</module>
</modules>
<properties>
<java.version>11</java.version>
</properties>
</project>

View File

@ -5,4 +5,5 @@
- [Working With Multiple Repositories in Gradle](https://www.baeldung.com/java-gradle-multiple-repositories)
- [Different Dependency Version Declarations in Gradle](https://www.baeldung.com/gradle-different-dependency-version-declarations)
- [Generating Javadoc With Gradle](https://www.baeldung.com/java-gradle-javadoc)
- [Generating WSDL Stubs With Gradle](https://www.baeldung.com/java-gradle-create-wsdl-stubs)
- [Generating WSDL Stubs With Gradle](https://www.baeldung.com/java-gradle-create-wsdl-stubs)
- [Gradle Proxy Configuration](https://www.baeldung.com/gradle-proxy-configuration)

View File

@ -203,7 +203,6 @@
</profiles>
<properties>
<java.version>17</java.version>
<!-- util -->
<commons-codec.version>1.16.0</commons-codec.version>
<!-- testing -->

View File

@ -0,0 +1,27 @@
package com.baeldung.mismatchedinputexception;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Animals {
private final int id;
private String name;
public Animals(@JsonProperty("id") int id, @JsonProperty("name")String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.mismatchedinputexception;
public class Book {
private int id;
private String title;
public Book(int id, String title) {
this.id = id;
this.title = title;
}
public Book() {
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.mismatchedinputexception;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class MismatchedinputExceptionUnitTest {
@Test
void givenJsonString_whenDeserializingToJavaObjectWithImmutableField_thenIdIsCorrect() throws JsonProcessingException {
String jsonString = "{\"id\":10,\"name\":\"Dog\"}";
ObjectMapper mapper = new ObjectMapper();
Animals animal = mapper.readValue(jsonString, Animals.class);
assertEquals(animal.getId(),10);
}
@Test
void givenJsonString_whenDeserializingToBook_thenIdIsCorrect() throws JsonProcessingException {
String jsonString = "{\"id\":\"10\",\"title\":\"Harry Potter\"}";
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(jsonString, Book.class);
assertEquals(book.getId(),10);
}
@Test
void givenJsonString_whenDeserializingToBookList_thenTitleIsCorrect() throws JsonProcessingException {
String jsonString = "[{\"id\":\"10\",\"title\":\"Harry Potter\"}]";
ObjectMapper mapper = new ObjectMapper();
List<Book> book = mapper.readValue(jsonString, new TypeReference<List<Book>>(){});
assertEquals(book.get(0).getTitle(),"Harry Potter");
}
}

View File

@ -16,7 +16,7 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-core.version}</version>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
@ -36,7 +36,7 @@
</build>
<properties>
<jackson-core.version>2.15.2</jackson-core.version>
<jackson.version>2.16.0</jackson.version>
<reflections.version>0.9.11</reflections.version>
</properties>

View File

@ -33,8 +33,7 @@
</build>
<properties>
<jackson.version>2.15.2</jackson.version>
<java.version>17</java.version>
<jackson.version>2.16.0</jackson.version>
</properties>
</project>

View File

@ -7,4 +7,4 @@ This module contains articles about JavaFX.
- [Introduction to JavaFx](https://www.baeldung.com/javafx)
- [Display Custom Items in JavaFX ListView](https://www.baeldung.com/javafx-listview-display-custom-items)
- [Adding EventHandler to JavaFX Button](https://www.baeldung.com/javafx-button-eventhandler)
- [How to Use a Custom Font in Java](https://www.baeldung.com/java-custom-font)

View File

@ -1125,7 +1125,6 @@
<properties>
<!-- Build properties -->
<maven.version>3.0.0</maven.version>
<java.version>11</java.version>
<scala.version>2.12.6</scala.version>
<node.version>v10.15.0</node.version>
<npm.version>6.4.1</npm.version>

View File

@ -1,7 +1,5 @@
## JHipster
This module contains articles about JHipster.
### Relevant articles:
This module contains articles about JHipster.
Relevant articles are listed in the nested module folders.

View File

@ -23,13 +23,13 @@
<docker-maven-plugin.version>0.4.13</docker-maven-plugin.version>
<hazelcast-hibernate52.version>1.2</hazelcast-hibernate52.version>
<hibernate.version>5.2.8.Final</hibernate.version>
<hikaricp.version>2.6.0</hikaricp.version>
<hikaricp.version>5.1.0</hikaricp.version>
<jacoco-maven-plugin.version>0.7.9</jacoco-maven-plugin.version>
<java.version>1.8</java.version>
<javassist.version>3.21.0-GA</javassist.version>
<jcache.version>1.0.0</jcache.version>
<jhipster.server.version>1.1.0</jhipster.server.version>
<jjwt.version>0.7.0</jjwt.version>
<jjwt.version>0.12.3</jjwt.version>
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
<liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
<liquibase-slf4j.version>2.0.0</liquibase-slf4j.version>
@ -216,7 +216,7 @@
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<artifactId>jjwt-api</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>

View File

@ -70,7 +70,7 @@ public class TokenProvider {
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secretKey)
.setSigningKey(secretKey).build()
.parseClaimsJws(token)
.getBody();
@ -86,7 +86,7 @@ public class TokenProvider {
public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken);
Jwts.parser().setSigningKey(secretKey).build().parseClaimsJws(authToken);
return true;
} catch (SignatureException e) {
log.info("Invalid JWT signature.");

View File

@ -23,12 +23,12 @@
<docker-maven-plugin.version>0.4.13</docker-maven-plugin.version>
<hazelcast-hibernate52.version>1.2</hazelcast-hibernate52.version>
<hibernate.version>5.2.8.Final</hibernate.version>
<hikaricp.version>2.6.0</hikaricp.version>
<hikaricp.version>5.1.0</hikaricp.version>
<jacoco-maven-plugin.version>0.7.9</jacoco-maven-plugin.version>
<javassist.version>3.21.0-GA</javassist.version>
<jcache.version>1.0.0</jcache.version>
<jhipster.server.version>1.1.0</jhipster.server.version>
<jjwt.version>0.7.0</jjwt.version>
<jjwt.version>0.12.3</jjwt.version>
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
<liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
<liquibase-slf4j.version>2.0.0</liquibase-slf4j.version>
@ -215,7 +215,7 @@
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<artifactId>jjwt-api</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>

View File

@ -70,7 +70,7 @@ public class TokenProvider {
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secretKey)
.setSigningKey(secretKey).build()
.parseClaimsJws(token)
.getBody();
@ -86,7 +86,7 @@ public class TokenProvider {
public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken);
Jwts.parser().setSigningKey(secretKey).build().parseClaimsJws(authToken);
return true;
} catch (SignatureException e) {
log.info("Invalid JWT signature.");

View File

@ -26,12 +26,12 @@
<frontend-maven-plugin.version>1.3</frontend-maven-plugin.version>
<hazelcast-hibernate52.version>1.2</hazelcast-hibernate52.version>
<hibernate.version>5.2.8.Final</hibernate.version>
<hikaricp.version>2.6.0</hikaricp.version>
<hikaricp.version>5.1.0</hikaricp.version>
<jacoco-maven-plugin.version>0.7.9</jacoco-maven-plugin.version>
<javassist.version>3.21.0-GA</javassist.version>
<jcache.version>1.0.0</jcache.version>
<jhipster.server.version>1.1.0</jhipster.server.version>
<jjwt.version>0.7.0</jjwt.version>
<jjwt.version>0.12.3</jjwt.version>
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
<liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
<liquibase-slf4j.version>2.0.0</liquibase-slf4j.version>
@ -243,7 +243,7 @@
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<artifactId>jjwt-api</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>

View File

@ -70,7 +70,7 @@ public class TokenProvider {
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secretKey)
.setSigningKey(secretKey).build()
.parseClaimsJws(token)
.getBody();
@ -86,7 +86,7 @@ public class TokenProvider {
public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken);
Jwts.parser().setSigningKey(secretKey).build().parseClaimsJws(authToken);
return true;
} catch (SignatureException e) {
log.info("Invalid JWT signature.");

View File

@ -122,7 +122,7 @@
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<artifactId>jjwt-api</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
@ -892,12 +892,12 @@
<gatling-maven-plugin.version>2.2.1</gatling-maven-plugin.version>
<gatling.version>2.2.3</gatling.version>
<hibernate.version>5.2.8.Final</hibernate.version>
<hikaricp.version>2.6.0</hikaricp.version>
<hikaricp.version>5.1.0</hikaricp.version>
<jacoco-maven-plugin.version>0.7.9</jacoco-maven-plugin.version>
<javassist.version>3.21.0-GA</javassist.version>
<jcache.version>1.0.0</jcache.version>
<jhipster.server.version>1.1.0</jhipster.server.version>
<jjwt.version>0.7.0</jjwt.version>
<jjwt.version>0.12.3</jjwt.version>
<jzlib.version>1.1.3</jzlib.version>
<liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
<liquibase-slf4j.version>2.0.0</liquibase-slf4j.version>

View File

@ -70,7 +70,7 @@ public class TokenProvider {
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secretKey)
.setSigningKey(secretKey).build()
.parseClaimsJws(token)
.getBody();
@ -86,7 +86,7 @@ public class TokenProvider {
public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken);
Jwts.parser().setSigningKey(secretKey).build().parseClaimsJws(authToken);
return true;
} catch (SignatureException e) {
log.info("Invalid JWT signature.");

View File

@ -5,4 +5,4 @@ This module contains articles about Gson
### Relevant Articles:
- [Solving Gson Parsing Errors](https://www.baeldung.com/gson-parsing-errors)
- [Difference between Gson @Expose and @SerializedName](https://www.baeldung.com/gson-expose-vs-serializedname)
- [Resolving Gsons “Multiple JSON Fields” Exception](https://www.baeldung.com/java-gson-multiple-json-fields-exception)

View File

@ -0,0 +1,29 @@
package com.baeldung.jsonnodetojsonobject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.Test;
import static org.junit.Assert.*;
public class JsonNodeToJsonObjectUnitTest {
public static String jsonString = "{\"name\": \"John\", \"gender\": \"male\", \"company\": \"Baeldung\", \"isEmployee\": true, \"age\": 30}";
@Test
public void givenJsonNode_whenConvertingToObjectNode_thenVerifyFieldsIntegrity() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);
ObjectNode objectNode = objectMapper.createObjectNode().setAll((ObjectNode) jsonNode);
assertEquals("John", objectNode.get("name").asText());
assertEquals("male", objectNode.get("gender").asText());
assertEquals("Baeldung", objectNode.get("company").asText());
assertTrue(objectNode.get("isEmployee").asBoolean());
assertEquals(30, objectNode.get("age").asInt());
}
}

View File

@ -12,4 +12,5 @@ This module contains articles about JSON.
- [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration)
- [Escape JSON String in Java](https://www.baeldung.com/java-json-escaping)
- [Reducing JSON Data Size](https://www.baeldung.com/json-reduce-data-size)
- [How to Convert JsonNode to ObjectNode](https://www.baeldung.com/java-jackson-jsonnode-objectnode)
- More Articles: [[next -->]](../json-2)

View File

@ -17,7 +17,7 @@
<repository>
<id>confluent</id>
<name>confluent-repo</name>
<url>http://packages.confluent.io/maven/</url>
<url>https://packages.confluent.io/maven/</url>
</repository>
</repositories>

View File

@ -22,6 +22,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<optional>true</optional>
</dependency>
<dependency>
@ -32,6 +33,7 @@
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>${reactor.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -78,4 +80,9 @@
</plugins>
</build>
<properties>
<reactor.version>3.6.0</reactor.version>
</properties>
</project>

View File

@ -33,6 +33,7 @@
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>${reactor.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -46,8 +47,8 @@
</plugins>
</build>
<properties>
<java.version>11</java.version>
</properties>
<properties>
<reactor.version>3.6.0</reactor.version>
</properties>
</project>

View File

@ -10,13 +10,10 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
### Relevant articles
- [A Guide to jBPM with Java](https://www.baeldung.com/jbpm-java)
- [Guide to Classgraph Library](https://www.baeldung.com/classgraph)
- [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program)
- [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors)
- [Templating with Handlebars](https://www.baeldung.com/handlebars)
- [A Guide to Crawler4j](https://www.baeldung.com/crawler4j)
- [Key Value Store with Chronicle Map](https://www.baeldung.com/java-chronicle-map)
- [Guide to MapDB](https://www.baeldung.com/mapdb)
- [A Guide to Apache Mesos](https://www.baeldung.com/apache-mesos)
- [JasperReports with Spring](https://www.baeldung.com/spring-jasper)
- More articles [[<-- prev]](/libraries) [[next -->]](/libraries-3)

View File

@ -18,11 +18,6 @@
<artifactId>mapdb</artifactId>
<version>${mapdb.version}</version>
</dependency>
<dependency>
<groupId>com.pivovarit</groupId>
<artifactId>parallel-collectors</artifactId>
<version>${parallel-collectors.version}</version>
</dependency>
<dependency>
<groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId>
@ -41,11 +36,6 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>info.picocli</groupId>
<artifactId>picocli</artifactId>
<version>${picocli.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
@ -83,17 +73,6 @@
<artifactId>mesos</artifactId>
<version>${mesos.library.version}</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>${jasperreports.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
@ -133,14 +112,11 @@
<mapdb.version>3.0.8</mapdb.version>
<classgraph.version>4.8.153</classgraph.version>
<jbpm.version>7.20.0.Final</jbpm.version>
<picocli.version>4.7.0</picocli.version>
<chronicle.map.version>3.24ea1</chronicle.map.version>
<crawler4j.version>4.4.0</crawler4j.version>
<spring-boot-starter.version>2.7.8</spring-boot-starter.version>
<mesos.library.version>1.11.0</mesos.library.version>
<parallel-collectors.version>1.1.0</parallel-collectors.version>
<handlebars.version>4.3.1</handlebars.version>
<jasperreports.version>6.20.0</jasperreports.version>
<spring.version>5.3.25</spring.version>
<hsqldb.version>2.7.1</hsqldb.version>
</properties>

View File

@ -8,9 +8,7 @@ The code examples related to different libraries are each in their own module.
Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases.
### Relevant Articles:
- [Parsing Command-Line Parameters with JCommander](https://www.baeldung.com/jcommander-parsing-command-line-parameters)
- [Guide to the Cactoos Library](https://www.baeldung.com/java-cactoos)
- [Parsing Command-Line Parameters with Airline](https://www.baeldung.com/java-airline)
- [Introduction to cache2k](https://www.baeldung.com/java-cache2k)
- [Introduction to the jcabi-aspects AOP Annotations Library](https://www.baeldung.com/java-jcabi-aspects)
- [Introduction to Takes](https://www.baeldung.com/java-takes)

View File

@ -13,21 +13,11 @@
</parent>
<dependencies>
<dependency>
<groupId>com.beust</groupId>
<artifactId>jcommander</artifactId>
<version>${jcommander.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>com.github.rvesse</groupId>
<artifactId>airline</artifactId>
<version>${airline.version}</version>
</dependency>
<dependency>
<groupId>org.cactoos</groupId>
<artifactId>cactoos</artifactId>
@ -125,7 +115,7 @@
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
<version>${javax.annotation-api.version}</version>
</dependency>
</dependencies>
@ -159,10 +149,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
<resources>
@ -214,9 +200,7 @@
</profiles>
<properties>
<jcommander.version>1.78</jcommander.version>
<cactoos.version>0.43</cactoos.version>
<airline.version>2.7.2</airline.version>
<cache2k.version>1.2.3.Final</cache2k.version>
<jcabi-aspects.version>0.22.6</jcabi-aspects.version>
<aspectjrt.version>1.9.20.1</aspectjrt.version>
@ -233,6 +217,7 @@
<structurizr.version>1.0.0</structurizr.version>
<immutables.version>2.5.6</immutables.version>
<mutabilitydetector.version>0.9.6</mutabilitydetector.version>
<javax.annotation-api.version>1.3.2</javax.annotation-api.version>
</properties>
</project>

View File

@ -11,9 +11,7 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
- [Quick Guide to RSS with Rome](https://www.baeldung.com/rome-rss)
- [Introduction to PCollections](https://www.baeldung.com/java-pcollections)
- [Introduction to Eclipse Collections](https://www.baeldung.com/eclipse-collections)
- [DistinctBy in the Java Stream API](https://www.baeldung.com/java-streams-distinct-by)
- [Introduction to NoException](https://www.baeldung.com/no-exception)
- [Spring Yarg Integration](https://www.baeldung.com/spring-yarg)
- [Delete a Directory Recursively in Java](https://www.baeldung.com/java-delete-directory)
- [Guide to JDeferred](https://www.baeldung.com/jdeferred)
- [Introduction to MBassador](https://www.baeldung.com/mbassador)

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