Merge remote-tracking branch 'origin/master'

This commit is contained in:
Philippe Sevestre
2024-02-24 14:53:24 -03:00
149 changed files with 27230 additions and 119 deletions
+1
View File
@@ -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)
@@ -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,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();
}
}
@@ -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);
+2 -2
View File
@@ -229,8 +229,8 @@
<maven-jar-plugin.version>3.3.0</maven-jar-plugin.version>
<maven-resources-plugin.version>3.3.0</maven-resources-plugin.version>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<spring-boot.version>3.2.2</spring-boot.version>
<junit-jupiter.version>5.10.2</junit-jupiter.version>
<spring-boot.version>3.1.5</spring-boot.version>
<junit-jupiter.version>5.8.2</junit-jupiter.version>
<native-build-tools-plugin.version>0.9.17</native-build-tools-plugin.version>
<logback.version>1.4.4</logback.version>
<slf4j.version>2.0.3</slf4j.version>
+15 -10
View File
@@ -9,9 +9,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencyManagement>
@@ -74,12 +74,6 @@
<version>${reactor.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>${de.flapdoodle.embed.mongo.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
@@ -95,6 +89,17 @@
<artifactId>reactor-netty-http</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mongodb</artifactId>
<version>${mongodb.testcontainer.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -114,9 +119,9 @@
</build>
<properties>
<axon-bom.version>4.6.3</axon-bom.version>
<de.flapdoodle.embed.mongo.version>3.4.8</de.flapdoodle.embed.mongo.version>
<axon-bom.version>4.9.3</axon-bom.version>
<reactor.version>3.6.0</reactor.version>
<mongodb.testcontainer.version>1.17.6</mongodb.testcontainer.version>
</properties>
</project>
@@ -18,7 +18,6 @@ import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.Indexes;
import com.mongodb.client.result.UpdateResult;
import groovyjarjarantlr4.v4.runtime.misc.NotNull;
import org.axonframework.config.ProcessingGroup;
import org.axonframework.eventhandling.EventHandler;
@@ -30,6 +29,7 @@ import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
@@ -172,7 +172,7 @@ public class MongoOrdersEventHandler implements OrdersEventHandler {
.toString());
}
private Order documentToOrder(@NotNull Document document) {
private Order documentToOrder(@NonNull Document document) {
Order order = new Order(document.getString(ORDER_ID_PROPERTY_NAME));
Document products = document.get(PRODUCTS_PROPERTY_NAME, Document.class);
products.forEach((k, v) -> order.getProducts()
@@ -0,0 +1,36 @@
package com.baeldung.axon.querymodel;
import com.mongodb.client.MongoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MongoDBContainer;
import org.testcontainers.junit.jupiter.Container;
@DataMongoTest
public class MongoOrdersEventHandlerLiveTest extends AbstractOrdersEventHandlerUnitTest {
@Autowired
MongoClient mongoClient;
@Container
static MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:6.0").withExposedPorts(27017);
@DynamicPropertySource
static void mongoDbProperties(DynamicPropertyRegistry registry) {
mongoDBContainer.start();
registry.add("spring.data.mongodb.uri", mongoDBContainer::getReplicaSetUrl);
}
@Override
protected OrdersEventHandler getHandler() {
mongoClient.getDatabase("axonframework")
.drop();
return new MongoOrdersEventHandler(mongoClient, emitter);
}
}
@@ -1,20 +0,0 @@
package com.baeldung.axon.querymodel;
import com.mongodb.client.MongoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
@DataMongoTest
public class MongoOrdersEventHandlerUnitTest extends AbstractOrdersEventHandlerUnitTest {
@Autowired
MongoClient mongoClient;
@Override
protected OrdersEventHandler getHandler() {
mongoClient.getDatabase("axonframework")
.drop();
return new MongoOrdersEventHandler(mongoClient, emitter);
}
}
+1 -1
View File
@@ -108,7 +108,7 @@
<module>spring-jpa-2</module>
<module>spring-jdbc</module>
<module>spring-jdbc-2</module>
<module>spring-jooq</module>
<!--<module>spring-jooq</module>-->
<module>spring-mybatis</module>
<module>spring-persistence-simple</module>
<module>spring-data-yugabytedb</module>
+2 -2
View File
@@ -833,7 +833,7 @@
<!--<module>spring-integration</module>--><!-- failing after upgrading to jdk17-->
<module>spring-jenkins-pipeline</module>
<module>spring-jersey</module>
<module>spring-jinq</module>
<!--<module>spring-jinq</module>-->
<module>spring-kafka-2</module>
<module>spring-kafka-3</module>
<module>spring-kafka</module>
@@ -1079,7 +1079,7 @@
<!--<module>spring-integration</module>--><!-- failing after upgrading to jdk17-->
<module>spring-jenkins-pipeline</module>
<module>spring-jersey</module>
<module>spring-jinq</module>
<!--<module>spring-jinq</module>-->
<module>spring-kafka-2</module>
<module>spring-kafka-3</module>
<module>spring-kafka</module>
@@ -1,3 +1,5 @@
server.port=8081
logging.level.root=INFO
logging.level.root=INFO
server.error.include-message=always
@@ -154,6 +154,8 @@
<resource.delimiter>@</resource.delimiter>
<!-- <start-class>com.baeldung.buildproperties.Application</start-class> -->
<start-class>com.baeldung.yaml.MyApplication</start-class>
<spring-boot.version>3.2.2</spring-boot.version>
<junit-jupiter.version>5.10.2</junit-jupiter.version>
</properties>
</project>
@@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
@@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar
+308
View File
File diff suppressed because it is too large Load Diff
+205
View File
@@ -0,0 +1,205 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.2.0
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %WRAPPER_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file
SET WRAPPER_SHA_256_SUM=""
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B
)
IF NOT %WRAPPER_SHA_256_SUM%=="" (
powershell -Command "&{"^
"$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^
"If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^
" Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^
" Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^
" Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^
" exit 1;"^
"}"^
"}"
if ERRORLEVEL 1 goto error
)
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%
@@ -1,14 +1,18 @@
<?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">
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.spring.cloud</groupId>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.baeldung.spring.cloud.aws.sqs</groupId>
<artifactId>spring-cloud-aws-v3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-cloud-aws-v3</name>
<packaging>jar</packaging>
<description>Spring Cloud AWS Examples</description>
<description>spring-cloud-aws-v3</description>
<dependencyManagement>
<dependencies>
@@ -55,14 +59,29 @@
<artifactId>awaitility</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<start-class>com.baeldung.spring.cloud.aws.SpringCloudAwsApplication</start-class>
<start-class>com.baeldung.spring.cloud.aws.sqs.SpringCloudAwsApplication</start-class>
<spring-cloud-aws.version>3.1.0</spring-cloud-aws.version>
<maven.surefire.version>3.1.0</maven.surefire.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<java.version>17</java.version>
</properties>
</project>
</project>
@@ -0,0 +1,16 @@
package com.baeldung.spring.cloud.aws.sqs.acknowledgement;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Profile;
@SpringBootApplication
public class OrderProcessingApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(OrderProcessingApplication.class);
app.setAdditionalProfiles("acknowledgement");
app.run(args);
}
}
@@ -0,0 +1,37 @@
package com.baeldung.spring.cloud.aws.sqs.acknowledgement.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "events.queues")
public class EventsQueuesProperties {
private String orderProcessingRetryQueue;
private String orderProcessingAsyncQueue;
private String orderProcessingNoRetriesQueue;
public String getOrderProcessingRetryQueue() {
return orderProcessingRetryQueue;
}
public void setOrderProcessingRetryQueue(String orderProcessingRetryQueue) {
this.orderProcessingRetryQueue = orderProcessingRetryQueue;
}
public String getOrderProcessingAsyncQueue() {
return orderProcessingAsyncQueue;
}
public void setOrderProcessingAsyncQueue(String orderProcessingAsyncQueue) {
this.orderProcessingAsyncQueue = orderProcessingAsyncQueue;
}
public String getOrderProcessingNoRetriesQueue() {
return orderProcessingNoRetriesQueue;
}
public void setOrderProcessingNoRetriesQueue(String orderProcessingNoRetriesQueue) {
this.orderProcessingNoRetriesQueue = orderProcessingNoRetriesQueue;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.spring.cloud.aws.sqs.acknowledgement.configuration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@EnableConfigurationProperties({ EventsQueuesProperties.class, ProductIdProperties.class})
@Configuration
public class OrderProcessingConfiguration {
}
@@ -0,0 +1,40 @@
package com.baeldung.spring.cloud.aws.sqs.acknowledgement.configuration;
import java.util.UUID;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("product.id")
public class ProductIdProperties {
private UUID smartphone;
private UUID wirelessHeadphones;
private UUID laptop;
public UUID getSmartphone() {
return smartphone;
}
public void setSmartphone(UUID smartphone) {
this.smartphone = smartphone;
}
public UUID getWirelessHeadphones() {
return wirelessHeadphones;
}
public void setWirelessHeadphones(UUID wirelessHeadphones) {
this.wirelessHeadphones = wirelessHeadphones;
}
public UUID getLaptop() {
return laptop;
}
public void setLaptop(UUID laptop) {
this.laptop = laptop;
}
}
@@ -0,0 +1,8 @@
package com.baeldung.spring.cloud.aws.sqs.acknowledgement.exception;
public class OutOfStockException extends RuntimeException {
public OutOfStockException(String errorMessage) {
super(errorMessage);
}
}
@@ -0,0 +1,8 @@
package com.baeldung.spring.cloud.aws.sqs.acknowledgement.exception;
public class ProductNotFoundException extends RuntimeException {
public ProductNotFoundException(String errorMessage) {
super(errorMessage);
}
}
@@ -0,0 +1,65 @@
package com.baeldung.spring.cloud.aws.sqs.acknowledgement.listener;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.baeldung.spring.cloud.aws.sqs.acknowledgement.model.OrderCreatedEvent;
import com.baeldung.spring.cloud.aws.sqs.acknowledgement.model.OrderStatus;
import com.baeldung.spring.cloud.aws.sqs.acknowledgement.service.OrderService;
import com.baeldung.spring.cloud.aws.sqs.acknowledgement.service.InventoryService;
import io.awspring.cloud.sqs.annotation.SqsListener;
import io.awspring.cloud.sqs.annotation.SqsListenerAcknowledgementMode;
import io.awspring.cloud.sqs.listener.acknowledgement.Acknowledgement;
@Component
public class OrderProcessingListeners {
private static final Logger logger = LoggerFactory.getLogger(OrderProcessingListeners.class);
private final InventoryService inventoryService;
private final OrderService orderService;
public OrderProcessingListeners(InventoryService inventoryService, OrderService orderService) {
this.inventoryService = inventoryService;
this.orderService = orderService;
}
@SqsListener(value = "${events.queues.order-processing-retry-queue}", id = "retry-order-processing-container", messageVisibilitySeconds = "1")
public void stockCheckRetry(OrderCreatedEvent orderCreatedEvent) {
logger.info("Message received: {}", orderCreatedEvent);
orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.PROCESSING);
inventoryService.checkInventory(orderCreatedEvent.productId(), orderCreatedEvent.quantity());
orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.PROCESSED);
logger.info("Message processed successfully: {}", orderCreatedEvent);
}
@SqsListener(value = "${events.queues.order-processing-async-queue}", acknowledgementMode = SqsListenerAcknowledgementMode.MANUAL, id = "async-order-processing-container", messageVisibilitySeconds = "3")
public void slowStockCheckAsynchronous(OrderCreatedEvent orderCreatedEvent, Acknowledgement acknowledgement) {
logger.info("Message received: {}", orderCreatedEvent);
orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.PROCESSING);
CompletableFuture.runAsync(() -> inventoryService.slowCheckInventory(orderCreatedEvent.productId(), orderCreatedEvent.quantity()))
.thenRun(() -> orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.PROCESSED))
.thenCompose(voidFuture -> acknowledgement.acknowledgeAsync())
.thenRun(() -> logger.info("Message for order {} acknowledged", orderCreatedEvent.id()));
logger.info("Releasing processing thread.");
}
@SqsListener(value = "${events.queues.order-processing-no-retries-queue}", acknowledgementMode = "${events.acknowledgment.order-processing-no-retries-queue}", id = "no-retries-order-processing-container", messageVisibilitySeconds = "3")
public void stockCheckNoRetries(OrderCreatedEvent orderCreatedEvent) {
logger.info("Message received: {}", orderCreatedEvent);
// Fire and forget scenario where we're not interested on the outcome, e.g. a sales event with limited inventory.
orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.RECEIVED);
inventoryService.checkInventory(orderCreatedEvent.productId(), orderCreatedEvent.quantity());
logger.info("Message processed: {}", orderCreatedEvent);
}
}
@@ -0,0 +1,7 @@
package com.baeldung.spring.cloud.aws.sqs.acknowledgement.model;
import java.util.UUID;
public record OrderCreatedEvent(UUID id, UUID productId, int quantity) {
}
@@ -0,0 +1,15 @@
package com.baeldung.spring.cloud.aws.sqs.acknowledgement.model;
public enum OrderStatus {
RECEIVED,
PROCESSING,
PROCESSED,
ERROR,
UNKNOWN
}
@@ -0,0 +1,62 @@
package com.baeldung.spring.cloud.aws.sqs.acknowledgement.service;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import com.baeldung.spring.cloud.aws.sqs.acknowledgement.configuration.ProductIdProperties;
import com.baeldung.spring.cloud.aws.sqs.acknowledgement.exception.OutOfStockException;
import com.baeldung.spring.cloud.aws.sqs.acknowledgement.exception.ProductNotFoundException;
@Service
public class InventoryService implements InitializingBean {
private final ProductIdProperties productIdProperties;
// Using a Map to simulate storage
private Map<UUID, Integer> inventory;
public InventoryService(ProductIdProperties productIdProperties) {
this.productIdProperties = productIdProperties;
}
@Override
public void afterPropertiesSet() {
this.inventory = new ConcurrentHashMap<>(Map.of(productIdProperties.getSmartphone(), 10,
productIdProperties.getWirelessHeadphones(), 15,
productIdProperties.getLaptop(), 5));
}
public void checkInventory(UUID productId, int quantity) {
Integer stock = inventory.get(productId);
if (stock == null) {
throw new ProductNotFoundException("Product with id %s not found in Inventory".formatted(productId));
}
if (stock < quantity) {
// Simulate Stock Replenishment for Retries
inventory.put(productId, stock + (int) (Math.random() * 5));
throw new OutOfStockException(
"Product with id %s is out of stock. Quantity requested: %s ".formatted(productId, quantity));
}
// Decrease inventory
inventory.put(productId, stock - quantity);
}
public void slowCheckInventory(UUID productId, int quantity) {
simulateBusyConnection();
checkInventory(productId, quantity);
}
private void simulateBusyConnection() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,24 @@
package com.baeldung.spring.cloud.aws.sqs.acknowledgement.service;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Service;
import com.baeldung.spring.cloud.aws.sqs.acknowledgement.model.OrderStatus;
@Service
public class OrderService {
Map<UUID, OrderStatus> ORDER_STATUS_STORAGE = new ConcurrentHashMap<>();
public void updateOrderStatus(UUID orderId, OrderStatus status) {
ORDER_STATUS_STORAGE.put(orderId, status);
}
public OrderStatus getOrderStatus(UUID orderId) {
return ORDER_STATUS_STORAGE.getOrDefault(orderId, OrderStatus.UNKNOWN);
}
}

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