diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5eac309 --- /dev/null +++ b/.gitignore @@ -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/ \ No newline at end of file diff --git a/antifraud-service/.gitignore b/antifraud-service/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/antifraud-service/.gitignore @@ -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/ diff --git a/antifraud-service/.mvn/wrapper/maven-wrapper.properties b/antifraud-service/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..8f96f52 --- /dev/null +++ b/antifraud-service/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip diff --git a/antifraud-service/mvnw b/antifraud-service/mvnw new file mode 100644 index 0000000..d7c358e --- /dev/null +++ b/antifraud-service/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/antifraud-service/mvnw.cmd b/antifraud-service/mvnw.cmd new file mode 100644 index 0000000..6f779cf --- /dev/null +++ b/antifraud-service/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@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.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/antifraud-service/pom.xml b/antifraud-service/pom.xml new file mode 100644 index 0000000..e48f1b5 --- /dev/null +++ b/antifraud-service/pom.xml @@ -0,0 +1,85 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.2 + + + com.lgutierrez + antifraud-service + 0.0.1-SNAPSHOT + antifraud-service + Demo project for Spring Boot Antifraud Service + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.kafka + spring-kafka + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + io.projectreactor + reactor-test + test + + + org.springframework.kafka + spring-kafka-test + test + + + org.projectlombok + lombok + provided + + + com.lgutierrez + transaction-service + 0.0.1-SNAPSHOT + compile + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/antifraud-service/src/main/java/com/lgutierrez/antifraudService/AntifraudServiceApplication.java b/antifraud-service/src/main/java/com/lgutierrez/antifraudService/AntifraudServiceApplication.java new file mode 100644 index 0000000..a82088a --- /dev/null +++ b/antifraud-service/src/main/java/com/lgutierrez/antifraudService/AntifraudServiceApplication.java @@ -0,0 +1,13 @@ +package com.lgutierrez.antifraudService; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AntifraudServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(AntifraudServiceApplication.class, args); + } + +} diff --git a/antifraud-service/src/main/java/com/lgutierrez/antifraudService/config/KafkaTopicConfig.java b/antifraud-service/src/main/java/com/lgutierrez/antifraudService/config/KafkaTopicConfig.java new file mode 100644 index 0000000..fa7fcd3 --- /dev/null +++ b/antifraud-service/src/main/java/com/lgutierrez/antifraudService/config/KafkaTopicConfig.java @@ -0,0 +1,20 @@ +package com.lgutierrez.antifraudService.config; + +import org.apache.kafka.clients.admin.NewTopic; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.config.TopicBuilder; + +@Configuration +public class KafkaTopicConfig { + + @Value("${spring.kafka.topic.name}") + private String topicName; + + //create a bean for kafka topic + @Bean + public NewTopic getTopic() { + return TopicBuilder.name(topicName).build(); + } +} diff --git a/antifraud-service/src/main/java/com/lgutierrez/antifraudService/controller/AntifraudController.java b/antifraud-service/src/main/java/com/lgutierrez/antifraudService/controller/AntifraudController.java new file mode 100644 index 0000000..eacae85 --- /dev/null +++ b/antifraud-service/src/main/java/com/lgutierrez/antifraudService/controller/AntifraudController.java @@ -0,0 +1,30 @@ +package com.lgutierrez.antifraudService.controller; + +import com.lgutierrez.antifraudService.kafka.EventProducer; +import com.lgutierrez.transactionService.entity.Transaction; +import com.lgutierrez.transactionService.enums.TransactionStatus; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/antifraud") +public class AntifraudController { + + private final EventProducer eventProducer; + + public AntifraudController(EventProducer eventProducer){ + this.eventProducer = eventProducer; + } + + @PostMapping + public String evaluateAntifraud(@RequestBody Transaction transaction) throws Exception { + String msj = transaction.getAmount() > 1000 ? "REJECT" : "APPROVED"; + transaction.setStatus(TransactionStatus.valueOf(msj)); + + eventProducer.sendMessage(transaction); + + return "Event handled successfully!"; + } +} diff --git a/antifraud-service/src/main/java/com/lgutierrez/antifraudService/dto/AntifraudDTO.java b/antifraud-service/src/main/java/com/lgutierrez/antifraudService/dto/AntifraudDTO.java new file mode 100644 index 0000000..4a26ddb --- /dev/null +++ b/antifraud-service/src/main/java/com/lgutierrez/antifraudService/dto/AntifraudDTO.java @@ -0,0 +1,14 @@ +package com.lgutierrez.antifraudService.dto; + +import java.util.UUID; + +public record AntifraudDTO( + UUID accountExternalIdDebit, + UUID accountExternalIdCredit, + String transferTypeId, + Double value +) { + public AntifraudDTO { + + } +} diff --git a/antifraud-service/src/main/java/com/lgutierrez/antifraudService/kafka/EventProducer.java b/antifraud-service/src/main/java/com/lgutierrez/antifraudService/kafka/EventProducer.java new file mode 100644 index 0000000..591e205 --- /dev/null +++ b/antifraud-service/src/main/java/com/lgutierrez/antifraudService/kafka/EventProducer.java @@ -0,0 +1,37 @@ +package com.lgutierrez.antifraudService.kafka; + +import com.lgutierrez.transactionService.entity.Transaction; +import org.apache.kafka.clients.admin.NewTopic; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.messaging.Message; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.stereotype.Service; + +@Service +public class EventProducer { + private static final Logger LOGGER = LoggerFactory.getLogger(EventProducer.class); + + private NewTopic topic; + + private KafkaTemplate kafkaTemplate; + + public EventProducer(NewTopic topic, KafkaTemplate kafkaTemplate){ + this.topic = topic; + this.kafkaTemplate = kafkaTemplate; + } + + public void sendMessage(Transaction transaction){ + LOGGER.info(String.format("Transaction event => %s", transaction.toString())); + + //create Message + Message transactionMessage = MessageBuilder.withPayload(transaction) + .setHeader(KafkaHeaders.TOPIC, topic.name()) + .build(); + + kafkaTemplate.send(transactionMessage); + } + +} diff --git a/antifraud-service/src/main/resources/application.properties b/antifraud-service/src/main/resources/application.properties new file mode 100644 index 0000000..1ede1ce --- /dev/null +++ b/antifraud-service/src/main/resources/application.properties @@ -0,0 +1,7 @@ +spring.application.name=transaction-service +server.port=8081 + +spring.kafka.producer.bootstrap-servers=localhost:9092 +spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer +spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer +spring.kafka.topic.name=transactions_fraud \ No newline at end of file diff --git a/antifraud-service/src/test/java/com/lgutierrez/antifraudService/AntifraudServiceApplicationTests.java b/antifraud-service/src/test/java/com/lgutierrez/antifraudService/AntifraudServiceApplicationTests.java new file mode 100644 index 0000000..080f96a --- /dev/null +++ b/antifraud-service/src/test/java/com/lgutierrez/antifraudService/AntifraudServiceApplicationTests.java @@ -0,0 +1,13 @@ +package com.lgutierrez.antifraudService; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class AntifraudServiceApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/docker-compose.yml b/docker-compose.yml deleted file mode 100644 index a59bedf..0000000 --- a/docker-compose.yml +++ /dev/null @@ -1,28 +0,0 @@ -version: "3.7" -services: - postgres: - image: postgres:14 - ports: - - "5432:5432" - environment: - - POSTGRES_USER=postgres - - POSTGRES_PASSWORD=postgres - zookeeper: - image: confluentinc/cp-zookeeper:5.5.3 - environment: - ZOOKEEPER_CLIENT_PORT: 2181 - kafka: - image: confluentinc/cp-enterprise-kafka:5.5.3 - depends_on: [zookeeper] - environment: - KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181" - KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092 - KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT - KAFKA_BROKER_ID: 1 - KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 - KAFKA_JMX_PORT: 9991 - ports: - - 9092:9092 -volumes: - oracle-data: - oracle-backup: diff --git a/transaction-service/.gitignore b/transaction-service/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/transaction-service/.gitignore @@ -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/ diff --git a/transaction-service/.mvn/wrapper/maven-wrapper.properties b/transaction-service/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..8f96f52 --- /dev/null +++ b/transaction-service/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip diff --git a/transaction-service/mvnw b/transaction-service/mvnw new file mode 100644 index 0000000..d7c358e --- /dev/null +++ b/transaction-service/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/transaction-service/mvnw.cmd b/transaction-service/mvnw.cmd new file mode 100644 index 0000000..6f779cf --- /dev/null +++ b/transaction-service/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@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.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/transaction-service/pom.xml b/transaction-service/pom.xml new file mode 100644 index 0000000..1a4a95e --- /dev/null +++ b/transaction-service/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.2 + + + com.lgutierrez + transaction-service + 0.0.1-SNAPSHOT + transaction-service + Demo project for Spring Boot Transaction Service + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.kafka + spring-kafka + + + + org.postgresql + postgresql + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + io.projectreactor + reactor-test + test + + + org.springframework.kafka + spring-kafka-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/TransactionServiceApplication.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/TransactionServiceApplication.java new file mode 100644 index 0000000..80e1878 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/TransactionServiceApplication.java @@ -0,0 +1,13 @@ +package com.lgutierrez.transactionService; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TransactionServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(TransactionServiceApplication.class, args); + } + +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/config/WebClientConfig.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/config/WebClientConfig.java new file mode 100644 index 0000000..43ac676 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/config/WebClientConfig.java @@ -0,0 +1,24 @@ +package com.lgutierrez.transactionService.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.reactive.ClientHttpConnector; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.netty.http.client.HttpClient; + +@Configuration +public class WebClientConfig { + private static final int TIMEOUT = 5000; //5 seconds to timeOut + + @Bean + public WebClient webClient() { + HttpClient httpClient = HttpClient.create() + .responseTimeout(java.time.Duration.ofMillis(TIMEOUT)); + + ClientHttpConnector connector = new ReactorClientHttpConnector(httpClient); + return WebClient.builder() + .clientConnector(connector) + .build(); + } +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/controller/AccountController.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/controller/AccountController.java new file mode 100644 index 0000000..8018017 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/controller/AccountController.java @@ -0,0 +1,25 @@ +package com.lgutierrez.transactionService.controller; + +import com.lgutierrez.transactionService.dto.AccountDTO; +import com.lgutierrez.transactionService.service.AccountService; +import lombok.AllArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@AllArgsConstructor +@RestController +@RequestMapping("/api/account") +public class AccountController { + + private final AccountService accountService; + + @PostMapping + public ResponseEntity createAccount(@RequestBody AccountDTO accountDTO) throws Exception { + AccountDTO accountDTO1 = accountService.registerAccount(accountDTO); + return new ResponseEntity<>(accountDTO1, HttpStatus.CREATED); + } +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/controller/TransactionController.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/controller/TransactionController.java new file mode 100644 index 0000000..523cc0b --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/controller/TransactionController.java @@ -0,0 +1,30 @@ +package com.lgutierrez.transactionService.controller; + +import com.lgutierrez.transactionService.dto.TransactionDTO; +import com.lgutierrez.transactionService.service.TransactionService; +import lombok.AllArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.UUID; + +@AllArgsConstructor +@RestController +@RequestMapping("/api/transactions") +public class TransactionController { + + private final TransactionService transactionService; + + @GetMapping("{id}") + public ResponseEntity getTransaction(@PathVariable("id") UUID transactionId) throws Exception { + TransactionDTO transactionDTO = transactionService.getTransactionById(transactionId); + return ResponseEntity.ok(transactionDTO); + } + + @PostMapping + public ResponseEntity createTransaction(@RequestBody TransactionDTO transactionDTO) throws Exception { + TransactionDTO transactionDTO1 = transactionService.registerTransaction(transactionDTO); + return new ResponseEntity<>(transactionDTO1, HttpStatus.CREATED); + } +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/dto/AccountDTO.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/dto/AccountDTO.java new file mode 100644 index 0000000..92cfe21 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/dto/AccountDTO.java @@ -0,0 +1,19 @@ +package com.lgutierrez.transactionService.dto; + +import com.lgutierrez.transactionService.enums.AccountStatus; +import com.lgutierrez.transactionService.enums.AccountType; + +public record AccountDTO( + AccountStatus accountStatus, + AccountType accountType +) { + public AccountDTO { + if (accountStatus == null){ + throw new IllegalArgumentException("accountStatus cannot be null"); + } + if (accountType == null){ + throw new IllegalArgumentException("accountType cannot be null"); + } + + } +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/dto/ErrorDetails.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/dto/ErrorDetails.java new file mode 100644 index 0000000..24dfd23 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/dto/ErrorDetails.java @@ -0,0 +1,29 @@ +package com.lgutierrez.transactionService.dto; + +import java.util.Date; + +public class ErrorDetails { + + private Date timestamp; + private String message; + private String details; + + public ErrorDetails(Date timestamp, String message, String details) { + this.timestamp = timestamp; + this.message = message; + this.details = details; + } + + public Date getTimestamp() { + return timestamp; + } + + public String getMessage() { + return message; + } + + public String getDetails() { + return details; + } + +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/dto/TransactionDTO.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/dto/TransactionDTO.java new file mode 100644 index 0000000..8718d32 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/dto/TransactionDTO.java @@ -0,0 +1,25 @@ +package com.lgutierrez.transactionService.dto; + +import com.lgutierrez.transactionService.exception.BadRequestException; +import java.util.UUID; + +public record TransactionDTO( + UUID accountExternalIdDebit, + UUID accountExternalIdCredit, + String transferTypeId, + Double value +) { + public TransactionDTO { + if (accountExternalIdDebit == null && accountExternalIdCredit == null) { + throw new BadRequestException("account data not should be null or empty"); + } + + if (transferTypeId == null) { + throw new BadRequestException("invalid transfer type ID"); + } + + if (value == null) { + throw new BadRequestException("invalid value of amount"); + } + } +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/entity/Account.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/entity/Account.java new file mode 100644 index 0000000..2a31c6d --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/entity/Account.java @@ -0,0 +1,44 @@ +package com.lgutierrez.transactionService.entity; + +import com.lgutierrez.transactionService.enums.AccountStatus; +import com.lgutierrez.transactionService.enums.AccountType; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.hibernate.annotations.GenericGenerator; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "accounts") +public class Account { + @Id + @GeneratedValue(strategy = GenerationType.UUID) + @GenericGenerator(name = "UUID", type = org.hibernate.id.uuid.UuidGenerator.class) + private UUID id; + + @Column(name="status") + private AccountStatus status; + + @Column(name="type") + private AccountType type; + + @Column(name="created_at") + private LocalDateTime created_at; + + @Column(name="updated_at") + private LocalDateTime updated_at; + + @OneToMany(mappedBy = "account", cascade = CascadeType.ALL, orphanRemoval = true) + private List transactions = new ArrayList<>(); + +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/entity/Transaction.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/entity/Transaction.java new file mode 100644 index 0000000..1a3e5d8 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/entity/Transaction.java @@ -0,0 +1,48 @@ +package com.lgutierrez.transactionService.entity; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.lgutierrez.transactionService.enums.TransactionStatus; +import com.lgutierrez.transactionService.enums.TransactionType; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.hibernate.annotations.GenericGenerator; + +import java.time.LocalDateTime; +import java.util.UUID; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "transactions") +public class Transaction { + @Id + @GeneratedValue(strategy = GenerationType.UUID) + @GenericGenerator(name = "UUID", type = org.hibernate.id.uuid.UuidGenerator.class) + private UUID id; + + @Column(name="status") + private TransactionStatus status; + + @Column(name="type") + private TransactionType type; + + @Column(name="amount") + private double amount; + + @Column(name="created_at") + private LocalDateTime created_at; + + @Column(name="updated_at") + private LocalDateTime updated_at; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "account_id") + @JsonIgnore + private Account account; + +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/enums/AccountStatus.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/enums/AccountStatus.java new file mode 100644 index 0000000..13a1237 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/enums/AccountStatus.java @@ -0,0 +1,6 @@ +package com.lgutierrez.transactionService.enums; + +public enum AccountStatus { + AVAILABLE, + UNAVAILABLE, +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/enums/AccountType.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/enums/AccountType.java new file mode 100644 index 0000000..f3d6fa9 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/enums/AccountType.java @@ -0,0 +1,6 @@ +package com.lgutierrez.transactionService.enums; + +public enum AccountType { + CREDIT, + DEBIT +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/enums/TransactionStatus.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/enums/TransactionStatus.java new file mode 100644 index 0000000..7e12c75 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/enums/TransactionStatus.java @@ -0,0 +1,7 @@ +package com.lgutierrez.transactionService.enums; + +public enum TransactionStatus { + PENDING, + APPROVED, + REJECT +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/enums/TransactionType.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/enums/TransactionType.java new file mode 100644 index 0000000..fbf77e4 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/enums/TransactionType.java @@ -0,0 +1,8 @@ +package com.lgutierrez.transactionService.enums; + +public enum TransactionType { + EXPRESS, + FAST, + COMMON, + UNUSUAL +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/exception/APIException.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/exception/APIException.java new file mode 100644 index 0000000..f9d938e --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/exception/APIException.java @@ -0,0 +1,28 @@ +package com.lgutierrez.transactionService.exception; + +import org.springframework.http.HttpStatus; + +public class APIException extends RuntimeException{ + private final HttpStatus httpStatus; + private final String message; + + public APIException(HttpStatus httpStatus, String message) { + this.httpStatus = httpStatus; + this.message = message; + } + + public APIException(String message, HttpStatus httpStatus, String message1) { + super(message); + this.httpStatus = httpStatus; + this.message = message1; + } + + public HttpStatus getHttpStatus() { + return httpStatus; + } + + @Override + public String getMessage() { + return message; + } +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/exception/BadRequestException.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/exception/BadRequestException.java new file mode 100644 index 0000000..c41132a --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/exception/BadRequestException.java @@ -0,0 +1,11 @@ +package com.lgutierrez.transactionService.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.BAD_REQUEST) +public class BadRequestException extends RuntimeException{ + public BadRequestException(String message) { + super(message); + } +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/exception/GlobalExceptionHandler.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..417cd00 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/exception/GlobalExceptionHandler.java @@ -0,0 +1,74 @@ +package com.lgutierrez.transactionService.exception; + +import com.lgutierrez.transactionService.dto.ErrorDetails; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.reactive.result.method.annotation.ResponseEntityExceptionHandler; +import org.springframework.web.bind.MethodArgumentNotValidException; + + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +@ControllerAdvice +public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { + //Handle specific exceptions + @ExceptionHandler(ResourceNotFoundException.class) + public ResponseEntity handleResourceNotFoundException(ResourceNotFoundException exception, + WebRequest webRequest){ + ErrorDetails errorDetails = new ErrorDetails(new Date(), + exception.getMessage(), + webRequest.getDescription(false)); + + return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND); + } + + @ExceptionHandler(APIException.class) + public ResponseEntity handleAPIException(APIException exception, + WebRequest webRequest){ + ErrorDetails errorDetails = new ErrorDetails(new Date(), + exception.getMessage(), + webRequest.getDescription(false)); + + return new ResponseEntity<>(errorDetails, HttpStatus.CONFLICT); + } + + @ExceptionHandler(BadRequestException.class) + protected ResponseEntity handleBadRequestException(BadRequestException ex, WebRequest request) { + Map body = new HashMap<>(); + body.put("message", ex.getMessage()); + return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST); + } + + //Global exceptions + @ExceptionHandler(Exception.class) + public ResponseEntity handleGlobalException(Exception exception, + WebRequest webRequest){ + ErrorDetails errorDetails = new ErrorDetails(new Date(), + exception.getMessage(), + webRequest.getDescription(false)); + + return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR); + } + + //@Override + protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, + HttpHeaders headers, + HttpStatusCode status, + WebRequest request) { + Map errors = new HashMap<>(); + ex.getBindingResult().getAllErrors().forEach((error)->{ + String fieldName = ((FieldError)error).getField(); + String message = error.getDefaultMessage(); + errors.put(fieldName,message); + }); + return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); + } +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/exception/ResourceNotFoundException.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/exception/ResourceNotFoundException.java new file mode 100644 index 0000000..7c06a5c --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/exception/ResourceNotFoundException.java @@ -0,0 +1,32 @@ +package com.lgutierrez.transactionService.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +import java.util.UUID; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException{ + private String resourceName; + private String fieldName; + private UUID fieldValue; + + public ResourceNotFoundException(String resourceName, String fieldName, UUID fieldValue){ + super(String.format("%s not found with %s : '%s'", resourceName, fieldName, fieldValue)); + this.resourceName = resourceName; + this.fieldName = fieldName; + this.fieldValue = fieldValue; + } + + public String getResourceName() { + return resourceName; + } + + public String getFieldName() { + return fieldName; + } + + public UUID getFieldValue() { + return fieldValue; + } +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/mapper/AccountMapper.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/mapper/AccountMapper.java new file mode 100644 index 0000000..36792d2 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/mapper/AccountMapper.java @@ -0,0 +1,10 @@ +package com.lgutierrez.transactionService.mapper; + +import com.lgutierrez.transactionService.dto.AccountDTO; +import com.lgutierrez.transactionService.entity.Account; + +public class AccountMapper { + public static AccountDTO mapToAccountDTO(Account account) { + return new AccountDTO(account.getStatus(), account.getType()); + } +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/mapper/TransactionMapper.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/mapper/TransactionMapper.java new file mode 100644 index 0000000..222df7f --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/mapper/TransactionMapper.java @@ -0,0 +1,13 @@ +package com.lgutierrez.transactionService.mapper; + +import com.lgutierrez.transactionService.dto.TransactionDTO; +import com.lgutierrez.transactionService.entity.Transaction; + +public class TransactionMapper { + public static TransactionDTO mapToTransactionDTO(Transaction transaction) { + return new TransactionDTO(transaction.getAccount().getId(), + null, + transaction.getType().toString(), + transaction.getAmount()); + } +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/repository/AccountRepository.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/repository/AccountRepository.java new file mode 100644 index 0000000..cf826bf --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/repository/AccountRepository.java @@ -0,0 +1,10 @@ +package com.lgutierrez.transactionService.repository; + +import com.lgutierrez.transactionService.entity.Account; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.UUID; + +public interface AccountRepository extends JpaRepository { + +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/repository/TransactionRepository.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/repository/TransactionRepository.java new file mode 100644 index 0000000..ba259cb --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/repository/TransactionRepository.java @@ -0,0 +1,11 @@ +package com.lgutierrez.transactionService.repository; + +import com.lgutierrez.transactionService.entity.Transaction; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.UUID; + +@Repository +public interface TransactionRepository extends JpaRepository { +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/service/AccountService.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/service/AccountService.java new file mode 100644 index 0000000..14b15f1 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/service/AccountService.java @@ -0,0 +1,8 @@ +package com.lgutierrez.transactionService.service; + +import com.lgutierrez.transactionService.dto.AccountDTO; +import com.lgutierrez.transactionService.dto.TransactionDTO; + +public interface AccountService { + AccountDTO registerAccount(AccountDTO accountDTO) throws Exception; +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/service/TransactionService.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/service/TransactionService.java new file mode 100644 index 0000000..56a4da0 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/service/TransactionService.java @@ -0,0 +1,12 @@ +package com.lgutierrez.transactionService.service; + +import com.lgutierrez.transactionService.dto.*; + +import java.util.UUID; + +public interface TransactionService { + + TransactionDTO registerTransaction(TransactionDTO transactionDTO) throws Exception; + + TransactionDTO getTransactionById(UUID transactionId); +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/service/impl/AccountServiceImpl.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/service/impl/AccountServiceImpl.java new file mode 100644 index 0000000..b7fa4bd --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/service/impl/AccountServiceImpl.java @@ -0,0 +1,39 @@ +package com.lgutierrez.transactionService.service.impl; + +import com.lgutierrez.transactionService.dto.AccountDTO; +import com.lgutierrez.transactionService.entity.Account; +import com.lgutierrez.transactionService.mapper.AccountMapper; +import com.lgutierrez.transactionService.repository.AccountRepository; +import com.lgutierrez.transactionService.service.AccountService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; + +@Service +public class AccountServiceImpl implements AccountService { + + private static final Logger LOGGER = LoggerFactory.getLogger(TransactionServiceImpl.class); + + private AccountRepository accountRepository; + + public AccountServiceImpl(AccountRepository accountRepository) { + this.accountRepository = accountRepository; + } + + @Override + public AccountDTO registerAccount(AccountDTO accountDTO) throws Exception { + LocalDateTime now = LocalDateTime.now(); + + Account account = new Account(null, + accountDTO.accountStatus(), + accountDTO.accountType(), + now, + now, + null); + Account newAccount = accountRepository.save(account); + + return AccountMapper.mapToAccountDTO(newAccount); + } +} diff --git a/transaction-service/src/main/java/com/lgutierrez/transactionService/service/impl/TransactionServiceImpl.java b/transaction-service/src/main/java/com/lgutierrez/transactionService/service/impl/TransactionServiceImpl.java new file mode 100644 index 0000000..bcbf125 --- /dev/null +++ b/transaction-service/src/main/java/com/lgutierrez/transactionService/service/impl/TransactionServiceImpl.java @@ -0,0 +1,109 @@ +package com.lgutierrez.transactionService.service.impl; + +import com.lgutierrez.transactionService.dto.TransactionDTO; +import com.lgutierrez.transactionService.entity.Account; +import com.lgutierrez.transactionService.entity.Transaction; +import com.lgutierrez.transactionService.enums.TransactionStatus; +import com.lgutierrez.transactionService.enums.TransactionType; +import com.lgutierrez.transactionService.exception.ResourceNotFoundException; +import com.lgutierrez.transactionService.mapper.TransactionMapper; +import com.lgutierrez.transactionService.repository.AccountRepository; +import com.lgutierrez.transactionService.repository.TransactionRepository; +import com.lgutierrez.transactionService.service.TransactionService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Service; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.time.LocalDateTime; +import java.util.UUID; + +@Service +public class TransactionServiceImpl implements TransactionService { + + private static final Logger LOGGER = LoggerFactory.getLogger(TransactionServiceImpl.class); + + private TransactionRepository transactionRepository; + private AccountRepository accountRepository; + + @Autowired + private WebClient webClient; + + public TransactionServiceImpl(TransactionRepository transactionRepository, + AccountRepository accountRepository) { + this.transactionRepository = transactionRepository; + this.accountRepository = accountRepository; + } + + @Override + public TransactionDTO getTransactionById(UUID transactionId) { + Transaction transaction = transactionRepository.findById(transactionId).orElseThrow(() -> + new ResourceNotFoundException("Transaction", "id", transactionId)); + return TransactionMapper.mapToTransactionDTO(transaction); + } + + @Override + public TransactionDTO registerTransaction(TransactionDTO transactionDTO) throws Exception { + //get the account by Id + UUID accountId = transactionDTO.accountExternalIdCredit() == null ? transactionDTO.accountExternalIdDebit() : null; + if(accountId == null) + throw new Exception("something went wrong"); + + Account account = accountRepository.findById(accountId).orElseThrow(() -> + new ResourceNotFoundException("Account", "id", accountId)); + + LocalDateTime now = LocalDateTime.now(); + + //save in DB + Transaction transaction = new Transaction(null, + TransactionStatus.PENDING, + TransactionType.FAST, + transactionDTO.value(), + now, + now, + account); + + Transaction newTransaction = transactionRepository.save(transaction); + + //send to anti-fraud service + String res = SendToAntifraudService(newTransaction); + LOGGER.info(String.format("response message => %s", res)); + //to -> Dto object response + return TransactionMapper.mapToTransactionDTO(newTransaction); + } + + + @KafkaListener(topics = "${spring.kafka.topic.name}", + groupId = "${spring.kafka.consumer.group-id}") + public void consume(Transaction transaction){ + LOGGER.info("update transaction: {}", transaction.toString()); + Transaction transaction1 = transactionRepository.findById(transaction.getId()).orElseThrow(() -> + new ResourceNotFoundException("Transaction", "id", transaction.getId())); + transaction1.setStatus(transaction.getStatus()); + Transaction trnx = transactionRepository.save(transaction1); + LOGGER.info("New transaction saved in DB: {}", trnx); + + } + + + private String SendToAntifraudService(Transaction transaction) { + + return webClient.post() + .uri("http://localhost:8081/api/antifraud") + .body(Mono.just(transaction), Transaction.class) + .retrieve() + .bodyToMono(String.class) + .doOnSuccess(response -> { + // Handle successful response + LOGGER.debug("Success : {}", response); + }) + .doOnError(error -> { + // Handle error response + LOGGER.error("ERROR : {}", error.getMessage()); + }) + .block(); + } +} diff --git a/transaction-service/src/main/resources/application.properties b/transaction-service/src/main/resources/application.properties new file mode 100644 index 0000000..cbd0015 --- /dev/null +++ b/transaction-service/src/main/resources/application.properties @@ -0,0 +1,21 @@ +spring.application.name=transaction-service +spring.datasource.url=jdbc:postgresql://localhost:5433/mydb +spring.datasource.username=postgres +spring.datasource.password=postgres +spring.jpa.show-sql=true +spring.datasource.driver-class-name=org.postgresql.Driver +spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true +server.port=8080 +spring.datasource.hikari.allow-pool-suspension=true +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.properties.hibernate.boot.allow_jdbc_metadata_access=false +spring.jpa.hibernate.ddl-auto=update +spring.sql.init.mode=never + +spring.kafka.consumer.bootstrap-servers=localhost:9092 +spring.kafka.consumer.group-id=stock +spring.kafka.consumer.auto-offset-reset=earliest +spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer +spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer +spring.kafka.consumer.properties.spring.json.trusted.packages=* +spring.kafka.topic.name=transactions_fraud \ No newline at end of file diff --git a/transaction-service/src/test/java/com/lgutierrez/transactionService/TransactionServiceApplicationTests.java b/transaction-service/src/test/java/com/lgutierrez/transactionService/TransactionServiceApplicationTests.java new file mode 100644 index 0000000..3d19690 --- /dev/null +++ b/transaction-service/src/test/java/com/lgutierrez/transactionService/TransactionServiceApplicationTests.java @@ -0,0 +1,13 @@ +package com.lgutierrez.transaction_service; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class TransactionServiceApplicationTests { + + @Test + void contextLoads() { + } + +}