Avances de Update Card Status

This commit is contained in:
Juan Loreto 2025-12-16 06:59:50 -04:00
parent bb342e3c79
commit 257b29ea73
227 changed files with 19835 additions and 0 deletions

View File

1
bus-update-card-status/.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
* text=auto

49
bus-update-card-status/.gitignore vendored Normal file
View File

@ -0,0 +1,49 @@
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
### Config ###
.mvn/*
dependency-reduced-pom.xml
## no track
application-local.yaml
application-local.properties
*:Zone.Identifier

0
bus-update-card-status/.gitmodules vendored Normal file
View File

View File

@ -0,0 +1,9 @@
boveda_express_
=======================
Here you can see the full list of changes between each Flask-RESTful release.
Version 0.1
-------------
First public release

View File

View File

@ -0,0 +1,14 @@
## Build stage ##
FROM default-route-openshift-image-registry.apps.desplakur3.desintra.banesco.com/runners-gitlab/openjdk-17:1.20-2.1721752931 AS build
COPY . /home/default/
COPY pom.xml /home/default
COPY settings.xml /home/default
RUN mvn -s /home/default/settings.xml -f /home/default/pom.xml -Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true -DskipTests=true clean package
RUN ls -ltra /home/default/target/
### Package stage ###
FROM default-route-openshift-image-registry.apps.desplakur3.desintra.banesco.com/runners-gitlab/openjdk-17:1.20-2.1721752931
WORKDIR /home/default
CMD ["ls"]
COPY --from=build /home/default/target/*.jar app.jar
CMD ["java","-jar","app.jar"]

View File

@ -0,0 +1,18 @@
# Getting Started
### Reference Documentation
For further reference, please consider the following sections:
* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html)
* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/3.3.2/maven-plugin)
* [Create an OCI image](https://docs.spring.io/spring-boot/3.3.2/maven-plugin/build-image.html)
### Maven Parent overrides
Due to Maven's design, elements are inherited from the parent POM to the project POM.
While most of the inheritance is fine, it also inherits unwanted elements like `<license>` and `<developers>` from the
parent.
To prevent this, the project POM contains empty overrides for these elements.
If you manually switch to a different parent and actually want the inheritance, you need to remove those overrides.

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Banesco Banco Universal, C.A.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,24 @@
# Banesco
> Application:
## Distribution
The project is composed or will be distributed under the following organisational scheme:
1. apps (Folder containing all available applications and apis)
2. config (Folder containing initial system configuration)
3. config/main (Folder containing static files and media files)
1. media (folder containing filed upload by user)
2. private (folder containing css, images, js)
3. static (folder that will contain all the collectstatic generated from the private folder for production display)
4. templates
4. requirements (folder containter requirements necesaries for proyect)
## How to install?
You will need to fill in all the configuration necessary to build this project and how it is configured for use.
Go, enjoy!
### Banesco Banco Universal, C.A.

259
bus-update-card-status/mvnw vendored Normal file
View File

@ -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-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -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 "$@"

149
bus-update-card-status/mvnw.cmd vendored Normal file
View File

@ -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-<version>,maven-mvnd-<version>-<platform>}/<hash>
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"

View File

@ -0,0 +1,242 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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.banesco</groupId>
<artifactId>bus-update-card-status</artifactId>
<version>1.0-native-quarkus-jdk17</version>
<name>bus-update-card-status</name>
<description>API Business - Update card status</description>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<compiler-plugin.version>3.13.0</compiler-plugin.version>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<quarkus.platform.artifact-id>quarkus-bom</quarkus.platform.artifact-id>
<quarkus.platform.group-id>io.quarkus.platform</quarkus.platform.group-id>
<quarkus.platform.version>3.19.3</quarkus.platform.version>
<skipITs>true</skipITs>
<surefire-plugin.version>3.5.2</surefire-plugin.version>
<quarkus.main-class>com.banesco.BusUpdateCardStatusApplication</quarkus.main-class>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>${quarkus.platform.group-id}</groupId>
<artifactId>${quarkus.platform.artifact-id}</artifactId>
<version>${quarkus.platform.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>${quarkus.platform.group-id}</groupId>
<artifactId>quarkus-camel-bom</artifactId>
<version>${quarkus.platform.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.banesco</groupId>
<artifactId>commons-bian</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-core</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest-client</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-redis-client</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest-client-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-config-yaml</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest-jsonb</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-openapi</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-health</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-arc</artifactId>
</dependency>
<!-- unit tests -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5-mockito</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.17.2</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.logmanager</groupId>
<artifactId>jboss-logmanager</artifactId>
<version>3.0.6.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.6.0.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.13</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jkube</groupId>
<artifactId>openshift-maven-plugin</artifactId>
<version>1.0.0</version>
<configuration>
<resources>
<volumeMounts>
<volumeMount>
<name>maven-volumen</name>
<mountPath>/root/.m2</mountPath>
</volumeMount>
</volumeMounts>
</resources>
</configuration>
</plugin>
<plugin>
<groupId>${quarkus.platform.group-id}</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus.platform.version}</version>
<extensions>true</extensions>
<executions>
<execution>
<goals>
<goal>build</goal>
<goal>generate-code</goal>
<goal>generate-code-tests</goal>
<goal>native-image-agent</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
<configuration>
<parameters>true</parameters>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<systemPropertyVariables>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
<maven.home>${maven.home}</maven.home>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>3.0.0-M5</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<native.image.path>${project.build.directory}/${project.build.finalName}-runner
</native.image.path>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
<maven.home>${maven.home}</maven.home>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>native</id>
<activation>
<property>
<name>native</name>
</property>
</activation>
<properties>
<skipITs>false</skipITs>
<quarkus.package.type>native</quarkus.package.type>
<quarkus.native.enabled>true</quarkus.native.enabled>
</properties>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>application-dev.yaml</exclude>
<exclude>application-local.yaml</exclude>
</excludes>
</resource>
</resources>
</build>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,31 @@
####
# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode.
# It uses a micro base image, tuned for Quarkus native executables.
# It reduces the size of the resulting container image.
# Check https://quarkus.io/guides/quarkus-runtime-base-image for further information about this image.
#
# Before building the container image run:
#
# ./mvnw package -Dnative
#
# Then, build the image with:
#
# docker build -f src/main/docker/Dockerfile.native-micro -t quarkus/rec-update-card-status .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/rec-update-card-transaction-switch
#
###
FROM quay.io/quarkus/quarkus-micro-image:2.0
RUN mkdir -p /work
ENV TZ="America/Caracas"
ENV LANGUAGE='en_US:en'
VOLUME /tmp
COPY /file/*-runner /work/recUpdateCardStatus
RUN chmod -R 775 /work
RUN ls -ltra /work/
EXPOSE 8080
WORKDIR /work/
ENTRYPOINT ["./recUpdateCardStatus", "-Dquarkus.http.host=0.0.0.0"]

View File

@ -0,0 +1,97 @@
####
# This Dockerfile_mvn is used in order to build a container that runs the Quarkus application in JVM mode
#
# Before building the container image run:
#
# ./mvnw package
#
# Then, build the image with:
#
# docker build -f src/main/docker/Dockerfile_mvn.jvm -t quarkus/prv-send-mail-jvm .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/prv-send-mail-jvm
#
# If you want to include the debug port into your docker image
# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005.
# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005
# when running the container
#
# Then run the container using :
#
# docker run -i --rm -p 8080:8080 quarkus/prv-send-mail-jvm
#
# This image uses the `run-java.sh` script to run the application.
# This scripts computes the command line to execute your Java application, and
# includes memory/GC tuning.
# You can configure the behavior using the following environment properties:
# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class")
# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options
# in JAVA_OPTS (example: "-Dsome.property=foo")
# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is
# used to calculate a default maximal heap memory based on a containers restriction.
# If used in a container without any memory constraints for the container then this
# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio
# of the container available memory as set here. The default is `50` which means 50%
# of the available memory is used as an upper boundary. You can skip this mechanism by
# setting this value to `0` in which case no `-Xmx` option is added.
# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This
# is used to calculate a default initial heap memory based on the maximum heap memory.
# If used in a container without any memory constraints for the container then this
# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio
# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx`
# is used as the initial heap size. You can skip this mechanism by setting this value
# to `0` in which case no `-Xms` option is added (example: "25")
# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS.
# This is used to calculate the maximum value of the initial heap memory. If used in
# a container without any memory constraints for the container then this option has
# no effect. If there is a memory constraint then `-Xms` is limited to the value set
# here. The default is 4096MB which means the calculated value of `-Xms` never will
# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096")
# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output
# when things are happening. This option, if set to true, will set
# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true").
# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example:
# true").
# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787").
# - CONTAINER_CORE_LIMIT: A calculated core limit as described in
# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2")
# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024").
# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion.
# (example: "20")
# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking.
# (example: "40")
# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection.
# (example: "4")
# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus
# previous GC times. (example: "90")
# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20")
# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100")
# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should
# contain the necessary JRE command-line options to specify the required GC, which
# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC).
# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080")
# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080")
# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be
# accessed directly. (example: "foo.example.com,bar.example.com")
#
###
FROM registry.access.redhat.com/ubi8/openjdk-17:1.20
ENV LANGUAGE='en_US:en'
# We make four distinct layers so if there are application changes the library layers can be re-used
COPY --chown=185 target/quarkus-app/lib/ /deployments/lib/
COPY --chown=185 target/quarkus-app/*.jar /deployments/
COPY --chown=185 target/quarkus-app/app/ /deployments/app/
COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/
EXPOSE 8080
USER 185
ENV JAVA_OPTS_APPEND="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager"
ENV JAVA_APP_JAR="/deployments/quarkus-run.jar"
ENTRYPOINT [ "/opt/jboss/container/java/run/run-java.sh" ]

View File

@ -0,0 +1,93 @@
####
# This Dockerfile_mvn is used in order to build a container that runs the Quarkus application in JVM mode
#
# Before building the container image run:
#
# ./mvnw package -Dquarkus.package.jar.type=legacy-jar
#
# Then, build the image with:
#
# docker build -f src/main/docker/Dockerfile_mvn.legacy-jar -t quarkus/prv-send-mail-legacy-jar .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/prv-send-mail-legacy-jar
#
# If you want to include the debug port into your docker image
# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005.
# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005
# when running the container
#
# Then run the container using :
#
# docker run -i --rm -p 8080:8080 quarkus/prv-send-mail-legacy-jar
#
# This image uses the `run-java.sh` script to run the application.
# This scripts computes the command line to execute your Java application, and
# includes memory/GC tuning.
# You can configure the behavior using the following environment properties:
# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class")
# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options
# in JAVA_OPTS (example: "-Dsome.property=foo")
# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is
# used to calculate a default maximal heap memory based on a containers restriction.
# If used in a container without any memory constraints for the container then this
# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio
# of the container available memory as set here. The default is `50` which means 50%
# of the available memory is used as an upper boundary. You can skip this mechanism by
# setting this value to `0` in which case no `-Xmx` option is added.
# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This
# is used to calculate a default initial heap memory based on the maximum heap memory.
# If used in a container without any memory constraints for the container then this
# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio
# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx`
# is used as the initial heap size. You can skip this mechanism by setting this value
# to `0` in which case no `-Xms` option is added (example: "25")
# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS.
# This is used to calculate the maximum value of the initial heap memory. If used in
# a container without any memory constraints for the container then this option has
# no effect. If there is a memory constraint then `-Xms` is limited to the value set
# here. The default is 4096MB which means the calculated value of `-Xms` never will
# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096")
# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output
# when things are happening. This option, if set to true, will set
# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true").
# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example:
# true").
# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787").
# - CONTAINER_CORE_LIMIT: A calculated core limit as described in
# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2")
# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024").
# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion.
# (example: "20")
# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking.
# (example: "40")
# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection.
# (example: "4")
# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus
# previous GC times. (example: "90")
# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20")
# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100")
# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should
# contain the necessary JRE command-line options to specify the required GC, which
# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC).
# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080")
# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080")
# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be
# accessed directly. (example: "foo.example.com,bar.example.com")
#
###
FROM registry.access.redhat.com/ubi8/openjdk-17:1.20
ENV LANGUAGE='en_US:en'
COPY target/lib/* /deployments/lib/
COPY target/*-runner.jar /deployments/quarkus-run.jar
EXPOSE 8080
USER 185
ENV JAVA_OPTS_APPEND="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager"
ENV JAVA_APP_JAR="/deployments/quarkus-run.jar"
ENTRYPOINT [ "/opt/jboss/container/java/run/run-java.sh" ]

View File

@ -0,0 +1,29 @@
####
# This Dockerfile_mvn is used in order to build a container that runs the Quarkus application in native (no JVM) mode.
#
# Before building the container image run:
#
# ./mvnw package -Dnative
#
# Then, build the image with:
#
# docker build -f src/main/docker/Dockerfile_mvn.native -t quarkus/prv-send-mail .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/prv-send-mail
#
###
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.10
WORKDIR /work/
RUN ls -ltra /work
RUN ls -ltra target/
RUN chown 1001 /work \
&& chmod "g+rwX" /work \
&& chown 1001:root /work
COPY --chown=1001:root target/*-runner /work/application
EXPOSE 8080
USER 1001
ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"]

View File

@ -0,0 +1,30 @@
####
# This Dockerfile_mvn is used in order to build a container that runs the Quarkus application in native (no JVM) mode.
# It uses a micro base image, tuned for Quarkus native executables.
# It reduces the size of the resulting container image.
# Check https://quarkus.io/guides/quarkus-runtime-base-image for further information about this image.
#
# Before building the container image run:
#
# ./mvnw package -Dnative
#
# Then, build the image with:
#
# docker build -f src/main/docker/Dockerfile_mvn.native-micro -t quarkus/prv-send-mail .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/prv-send-mail
#
###
FROM quay.io/quarkus/quarkus-micro-image:2.0
WORKDIR /work/
RUN chown 1001 /work \
&& chmod "g+rwX" /work \
&& chown 1001:root /work
COPY --chown=1001:root target/*-runner /work/application
EXPOSE 8080
USER 1001
ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"]

View File

@ -0,0 +1,13 @@
package com.banesco;
import io.quarkus.runtime.Quarkus;
import io.quarkus.runtime.annotations.QuarkusMain;
@QuarkusMain
public class BusUpdateCardStatusApplication {
public static void main(String[] args) {
System.out.println("Starting Business Update Card Status ...........");
Quarkus.run();
}
}

View File

@ -0,0 +1,42 @@
package com.banesco.application;
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@RegisterForReflection
public class UpdateConfigResponse {
private String result;
private List<ConfigModel> configMapList;
private String error;
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class ConfigModel {
private String namespace;
private String configMapName;
private List<PropertyChange> properties;
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class PropertyChange {
private String name;
private String oldValue;
private String newValue;
private String withError;
}
}
}

View File

@ -0,0 +1,95 @@
package com.banesco.application.helper;
import com.banesco.common.application.exception.BanRuntimeException;
import com.banesco.common.domain.dto.bian.device.StringHelper;
import com.banesco.commons.config.StatusCodes;
import com.banesco.domain.bian.request.BusUpdateCardStatusRequest;
import jakarta.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class UpdateCardStatusRequestValidator {
// Function to check invalid fields
public void validatedRequest(
BusUpdateCardStatusRequest request
) {
if (request == null) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "body");
}
//check header
if (StringHelper.isEmpty(request.getCustomerReferenceFintechId())) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "customerReferenceFintechId");
}
if (StringHelper.isEmpty(request.getRequestId())) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "requestId");
}
// Device
if (request.getDevice() == null) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "device");
}
if (StringHelper.isEmpty(request.getDevice().getDeviceType())) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "device.deviceType");
}
if (StringHelper.isEmpty(request.getDevice().getDeviceDescription())) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "device.deviceDescription");
}
if (StringHelper.isEmpty(request.getDevice().getDeviceSessionReference())) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "device.deviceSessionReference");
}
// Customer
var customerReference = request.getCustomerReference();
if (customerReference == null) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "customerReference");
}
if (StringHelper.isEmpty(customerReference.getCustomerIdType())) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "customerReference.customerIdType");
}
// Card
var paymentCard = request.getCardReference();
if (paymentCard == null) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "cardReference.paymentCard");
}
if (StringHelper.isEmpty(paymentCard.getCardType())) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "cardReference.cardType");
}
if (StringHelper.isEmpty(paymentCard.getCardNumber())) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "cardReference.cardNumber");
}
if (StringHelper.isEmpty(paymentCard.getCardStatusCode())) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "cardReference.cardStatusCode");
}
if (StringHelper.isEmpty(paymentCard.getCardStatusAction())) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "cardReference.cardStatusAction");
}
if (StringHelper.isEmpty(paymentCard.getCardStatusReason())) {
throw new BanRuntimeException(StatusCodes.FIELD_REQUIRED, "cardReference.cardStatusReason");
}
}
}

View File

@ -0,0 +1,217 @@
package com.banesco.application.rest.controllers;
import com.banesco.application.helper.UpdateCardStatusRequestValidator;
import com.banesco.common.application.exception.BanBackendException;
import com.banesco.common.application.exception.BanRuntimeException;
import com.banesco.common.domain.dto.bian.device.JsonHelper;
import com.banesco.common.domain.dto.bian.device.LoggerHelper;
import com.banesco.common.domain.dto.bian.response.StatusResponse;
import com.banesco.commons.config.AppConf;
import com.banesco.commons.config.StatusCodes;
import com.banesco.domain.bian.request.BusUpdateCardStatusRequest;
import com.banesco.domain.bian.response.BusUpdateCardStatusResponse;
import com.banesco.domain.ports.inbound.UpdateCardStatusUseCase;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.openapi.annotations.OpenAPIDefinition;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.info.Info;
import org.eclipse.microprofile.openapi.annotations.media.Content;
import org.eclipse.microprofile.openapi.annotations.media.ExampleObject;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
@OpenAPIDefinition(info = @Info(
title = "bus-update-card-status",
version = "1.0",
description = "API Business - Cancelación de TDD")
)
@Path("/card/status/update")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Slf4j
public class UpdateCardStatusController {
private final UpdateCardStatusRequestValidator updateCardStatusRequestValidator;
private final UpdateCardStatusUseCase updateCardStatusUseCase;
@Inject
AppConf appConf;
@Inject
public UpdateCardStatusController(
UpdateCardStatusRequestValidator updateCardStatusRequestValidator,
UpdateCardStatusUseCase updateCardStatusUseCase
) {
this.updateCardStatusRequestValidator = updateCardStatusRequestValidator;
this.updateCardStatusUseCase = updateCardStatusUseCase;
}
@PUT
@Operation(
summary = "updateCardStatus",
description = "Permite cambiar el estatus de las tarjetas de los clientes."
)
@RequestBody(
description = "Datos de la solicitud para actualizar el estatus de la tarjeta",
required = true,
content = @Content(
mediaType = MediaType.APPLICATION_JSON,
schema = @Schema(implementation = BusUpdateCardStatusRequest.class),
examples = {
@ExampleObject(
name = "Ejemplo exitoso",
summary = "Petición con datos válidos",
value = "{\n" +
" \"requestId\": \"Req123\",\n" +
" \"customerReferenceFintechId \": \"500634269\"\n" +
" \"customerReference\": {\n" +
" \"customerIdType\": \"J\",\n" +
" \"customerId\": \"500634269\"\n" +
" },\n" +
" \"device\": {\n" +
" \"deviceType\": \"Mobile\",\n" +
" \"deviceDescription\": \"Xiaomi Note 11 PRO\",\n" +
" \"deviceIp\": \"127.0.0.1\",\n" +
" \"deviceSessionReference\": \"12345678901304\"\n" +
" },\n" +
" \"cardReference\": {\n" +
" \"cardType\": \"DebitCard\",\n" +
" \"cardNumber\": \"6012-8862-0791-7605\",\n" +
" \"cardStatusCode\": \"52\",\n" +
" \"cardStatusAction\": \"CV\",\n" +
" \"cardStatusReason\": \"Bloqueo Temporal\"\n" +
" }\n" +
"}"
),
@ExampleObject(
name = "Ejemplo Error de validación",
summary = "Petición con formato inválido",
value = "{\n" +
" \"requestId\": \"Req123\",\n" +
" \"customerReferenceFintechId \": \"500634269\"\n" +
" \"customerReference\": {\n" +
" \"customerIdType\": \"V\",\n" +
" \"customerId\": \"500634269\"\n" +
" },\n" +
" \"device\": {\n" +
" \"deviceType\": \"Mobile\",\n" +
" \"deviceDescription\": \"Xiaomi Note 11 PRO\",\n" +
" \"deviceIp\": \"127.0.0.1\",\n" +
" \"deviceSessionReference\": \"12345678901304\"\n" +
" },\n" +
" \"cardReference\": {\n" +
" \"cardType\": \"DebitCard\",\n" +
" \"cardNumber\": \"6012886207917605\",\n" +
" \"cardStatusCode\": \"52\",\n" +
" \"cardStatusAction\": \"CV\",\n" +
" \"cardStatusReason\": \"Bloqueo Temporal\"\n" +
" }\n" +
"}"
)
}
)
)
@APIResponses(value = {
@APIResponse(
responseCode = "200",
description = "Operación exitosa",
content = @Content(
mediaType = MediaType.APPLICATION_JSON,
schema = @Schema(implementation = BusUpdateCardStatusResponse.class),
examples = @ExampleObject(
name = "Ejemplo exitoso",
value = "{\"statusResponse\":{\"status\":\"ok\",\"statusCode\":\"200\",\"message\":\"Operacion exitosa\",\"requestId\":\"UCSS123456789\"}}"
)
)
),
@APIResponse(
responseCode = "400",
description = "Error en formato o campo requerido",
content = @Content(
mediaType = MediaType.APPLICATION_JSON,
schema = @Schema(implementation = BusUpdateCardStatusResponse.class),
examples = @ExampleObject(
name = "Ejemplo Error de validación",
value = "{\"statusResponse\":{\"status\":\"error\",\"statusCode\":\"VDE02\",\"message\":\"VDE02 - Error en formato del campo: cardReference.cardNumber\",\"requestId\":\"UCSS123456789\"}}"
)
)
)
})
public Response updateCardStatus(
BusUpdateCardStatusRequest request) {
BusUpdateCardStatusResponse dataResponse = null;
log.info("INICIO =>");
String requestId = request.getRequestId();
log.info(LoggerHelper.buildInfoRequest(requestId, JsonHelper.getJsonFromObject(request)));
String backendCode = StatusCodes.INTERNAL_ERROR.getStatusCode();
String backendDesc = StatusCodes.INTERNAL_ERROR.getStatusDesc();
String target = null;
try {
// Validate Request
updateCardStatusRequestValidator.validatedRequest(request);
updateCardStatusUseCase.execute(request);
backendCode = StatusCodes.SUCCESS_OPERATION.getStatusCode();
backendDesc = StatusCodes.SUCCESS_OPERATION.getStatusDesc();
} catch (BanRuntimeException e) {
backendCode = e.getStatusCode().getStatusCode();
log.error(LoggerHelper.buildError(requestId, backendCode + " - " + e.getMessage()));
if (e.getTarget() != null) {
backendDesc = e.getStatusCode().getStatusDesc().formatted(e.getTarget());
} else {
backendDesc = e.getStatusCode().getStatusDesc();
}
} catch (BanBackendException e) {
backendCode = e.getBackendCode();
log.error(LoggerHelper.buildError(requestId, backendCode + " - " + e.getMessage()));
if (e.getTarget() != null) {
backendDesc = e.getBackendDesc() + " - " + e.getTarget();
} else {
backendDesc = e.getBackendDesc();
}
} catch (Exception e) {
log.error(LoggerHelper.buildError(requestId, backendCode + " - " + e.getMessage()));
}
BusUpdateCardStatusResponse response = new BusUpdateCardStatusResponse();
response.setStatusResponse(
new StatusResponse(
backendCode.equals(StatusCodes.SUCCESS_OPERATION.getStatusCode()) ? "ok" : "error",
backendCode,
backendDesc,
requestId
)
);
String outputJson = response.toString();
log.info(LoggerHelper.buildInfoResponse(requestId, outputJson));
return Response.status(200)
.entity(outputJson)
.build();
}
}

View File

@ -0,0 +1,97 @@
package com.banesco.commons.config;
import com.banesco.common.application.exception.BanRuntimeException;
import com.banesco.common.domain.dto.bian.device.DateHelper;
import com.banesco.common.domain.dto.bian.device.JsonHelper;
import com.banesco.common.domain.dto.bian.device.RequestHelper;
import com.banesco.common.domain.model.ApiConfig;
import com.banesco.commons.exceptions.BanConfigException;
import com.banesco.domain.models.CurrentState;
import jakarta.inject.Singleton;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
import java.time.LocalDateTime;
import java.util.NoSuchElementException;
@Singleton
@Getter
@Slf4j
public class AppConf {
private static AppConf _INSTANCE;
private final String appSourceId;
private final Config configEnv;
private final RequestHelper requestHelper;
public String soapDomainCurrent;
DateHelper dateHelper = DateHelper.getInstance();
public static void getInstance() {
synchronized (AppConf.class) {
if (_INSTANCE == null) {
log.info("AppConf getInstance-->");
_INSTANCE = new AppConf();
}
}
}
public AppConf() {
log.info("NEW INSTANCE AppConf**********************************");
try {
configEnv = ConfigProvider.getConfig();
requestHelper = new RequestHelper();
soapDomainCurrent = configEnv.getValue("soap.domain.current", String.class);
appSourceId = configEnv.getValue("api.source-id", String.class);
_INSTANCE = this;
} catch (NoSuchElementException e) {
String errorMessage = "[ERROR CONFIG]: [%s]".formatted(e.getMessage());
log.error(errorMessage);
throw new BanConfigException(errorMessage);
} catch (Exception e) {
String errorMessage = "[ERROR CONFIG]: [%s]".formatted(e.getMessage());
log.error(errorMessage);
throw new BanConfigException(errorMessage);
}
}
public ApiConfig loadApiConfig(String apiName) {
try {
log.info("Loading APIConfig with key:{}", apiName);
String apiConfig = configEnv.getValue(apiName, String.class);
return JsonHelper.getObjectFromJson(apiConfig, ApiConfig.class);
} catch (Exception e) {
log.error("Error Loading API Config: {} -> {}", apiName, e.getMessage());
throw new BanRuntimeException(StatusCodes.INTERNAL_ERROR);
}
}
public CurrentState getCurrentState(String requestId) {
LocalDateTime now = dateHelper.getCurrentDateTime();
return new CurrentState(
dateHelper.getDate(now),
dateHelper.getTime(now),
requestId
);
}
}

View File

@ -0,0 +1,28 @@
package com.banesco.commons.config;
import com.banesco.common.domain.interfaces.BaseStatusCodesEnum;
import lombok.Getter;
/**
* Clase para definir Status de Respuesta.
*/
@Getter
public enum StatusCodes implements BaseStatusCodesEnum {
SUCCESS_OPERATION("OK", "Operación exitosa"),
REDIS_DATA_NOT_FOUND("R404", "Datos de validación no encontrado."),
FIELD_REQUIRED("VDE01", "ERROR CAMPO REQUERIDO: %s"),
INVALID_FORMAT("VDE02", "ERROR EN FORMATO DEL CAMPO: %s"),
INTERNAL_ERROR("500", "ERROR INTERNO"),
FAILED_DEPENDENCY("424", "FALLA DE DEPENDENCIA");
private String statusCode;
private String statusDesc;
StatusCodes(String statusCode, String statusDesc) {
this.statusCode = statusCode;
this.statusDesc = statusDesc;
}
}

View File

@ -0,0 +1,9 @@
package com.banesco.commons.exceptions;
public class BanConfigException extends RuntimeException {
public BanConfigException(String message) {
super(message);
}
}

View File

@ -0,0 +1,55 @@
package com.banesco.commons.exceptions;
import com.banesco.common.domain.dto.bian.response.StatusResponse;
import com.banesco.domain.bian.response.BusUpdateCardStatusResponse;
import io.vertx.ext.web.RoutingContext;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
import org.jboss.resteasy.reactive.server.ServerExceptionMapper;
import org.jboss.resteasy.reactive.server.UnwrapException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletionException;
@UnwrapException({CompletionException.class, BanConfigException.class})
@Slf4j
public class InternalExceptionMapper {
@Inject
RoutingContext routingContext; // Injecting the RoutingContext
@ServerExceptionMapper
public Response handleConfigException(Exception ex) {
String uri = routingContext.request().uri();
switch (uri) {
case "/card/status/update":
BusUpdateCardStatusResponse response = new BusUpdateCardStatusResponse();
response.setStatusResponse(
new StatusResponse(
"error",
"CONFLICT",
"Uso interno",
null
)
);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(response.toString())
.build();
default:
}
Map<String, String> errorMap = new HashMap<>();
errorMap.put("error", "USO INTERNO");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(errorMap).build();
}
}

View File

@ -0,0 +1,46 @@
package com.banesco.commons.exceptions;
import com.banesco.common.domain.dto.bian.response.StatusResponse;
import com.banesco.commons.config.StatusCodes;
import com.banesco.domain.bian.response.BusUpdateCardStatusResponse;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.RoutingContext;
import jakarta.inject.Inject;
import jakarta.json.bind.JsonbException;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
import lombok.extern.slf4j.Slf4j;
@Provider
@Slf4j
public class MalformedPayloadExceptionMapper implements ExceptionMapper<JsonbException> {
@Inject
RoutingContext routingContext; // Injecting the RoutingContext
@Override
public Response toResponse(JsonbException exception) {
HttpServerRequest headers = routingContext.request();
log.error("INICIO ERROR => {}", exception.getMessage());
log.error("[HEADERS {}]: [\nfintechId: {}\nappId: {}]",
headers.getHeader("fintechId"),
headers.getHeader("appId"));
String jsonResult = (new BusUpdateCardStatusResponse( new StatusResponse(
"error",
StatusCodes.INVALID_FORMAT.getStatusCode(),
StatusCodes.INVALID_FORMAT.getStatusDesc().formatted("body"),
null
))).toString();
log.error("[RESPONSE]: [{}]", jsonResult);
return Response.status(Response.Status.BAD_REQUEST)
.entity(
jsonResult
)
.build();
}
}

View File

@ -0,0 +1,12 @@
package com.banesco.commons.utils;
import com.banesco.common.domain.dto.bian.response.StatusResponse;
import com.banesco.commons.config.StatusCodes;
public class ResponseUtil {
public static StatusResponse mapErrorResponse(String requestId, StatusCodes statusCodes) {
return new StatusResponse("error", statusCodes.getStatusCode(), statusCodes.getStatusDesc(), requestId);
}
}

View File

@ -0,0 +1,17 @@
package com.banesco.domain.bian.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CardReference {
String cardType;
String cardNumber;
String cardStatusCode;
String cardStatusAction;
String cardStatusReason;
}

View File

@ -0,0 +1,20 @@
package com.banesco.domain.bian.request;
import com.banesco.common.domain.dto.bian.customer.CustomerReference;
import com.banesco.common.domain.dto.bian.device.Device;
import com.banesco.domain.bian.dto.CardReference;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BusUpdateCardStatusRequest {
String requestId;
String customerReferenceFintechId;
CustomerReference customerReference;
Device device;
CardReference cardReference;
}

View File

@ -0,0 +1,28 @@
package com.banesco.domain.bian.response;
import com.banesco.common.domain.dto.bian.response.BaseResponse;
import com.banesco.common.domain.dto.bian.response.StatusResponse;
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.EqualsAndHashCode;
@RegisterForReflection
@EqualsAndHashCode(callSuper = false)
public class BusUpdateCardStatusResponse extends BaseResponse {
public BusUpdateCardStatusResponse() {
super();
}
public BusUpdateCardStatusResponse(StatusResponse statusResponse) {
super(statusResponse);
}
@Override
public String toString() {
return "{\"statusResponse\":%s}".formatted(statusResponse.toString());
}
}

View File

@ -0,0 +1,13 @@
package com.banesco.domain.models;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public record CurrentState(String date, String time, String requestId) {
public String getTransactionDate() {
return date.concat("T".concat(time));
}
}

View File

@ -0,0 +1,10 @@
package com.banesco.domain.ports.inbound;
import com.banesco.domain.bian.request.BusUpdateCardStatusRequest;
public interface UpdateCardStatusUseCase {
void execute(
BusUpdateCardStatusRequest request
);
}

View File

@ -0,0 +1,9 @@
package com.banesco.domain.ports.outbound;
import com.banesco.common.domain.dto.bian.response.StatusResponse;
import com.banesco.domain.bian.request.BusUpdateCardStatusRequest;
public interface PaymentCardPort {
StatusResponse updateCardStatus(String productAccountId, BusUpdateCardStatusRequest request);
}

View File

@ -0,0 +1,8 @@
package com.banesco.domain.ports.outbound;
public interface RedisPort {
String findValue(String key);
void setValue(String key, String objectStr, long expiration);
}

View File

@ -0,0 +1,90 @@
package com.banesco.domain.services;
import com.banesco.common.application.exception.BanBackendException;
import com.banesco.common.application.exception.BanRuntimeException;
import com.banesco.common.domain.dto.bian.customer.CustomerReference;
import com.banesco.common.domain.dto.bian.device.JsonHelper;
import com.banesco.common.domain.dto.bian.device.StringHelper;
import com.banesco.common.domain.dto.bian.response.StatusResponse;
import com.banesco.common.domain.model.RedisParam;
import com.banesco.commons.config.AppConf;
import com.banesco.commons.config.StatusCodes;
import com.banesco.domain.bian.request.BusUpdateCardStatusRequest;
import com.banesco.domain.ports.inbound.UpdateCardStatusUseCase;
import com.banesco.domain.ports.outbound.PaymentCardPort;
import com.banesco.domain.ports.outbound.RedisPort;
import com.banesco.infrastructure.dtos.CustomerProduct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
@ApplicationScoped
public class UpdateCardStatusService implements UpdateCardStatusUseCase {
private final PaymentCardPort paymentCardPort;
private final String RESULT_OK = StatusCodes.SUCCESS_OPERATION.getStatusCode();
private final RedisParam redisParam;
private final RedisPort redisPort;
@Inject
public UpdateCardStatusService(AppConf appConf, PaymentCardPort paymentCardPort, RedisPort redisPort) {
this.paymentCardPort = paymentCardPort;
this.redisPort = redisPort;
redisParam = JsonHelper.getObjectFromJson(appConf.getConfigEnv().getValue("api.redis.get-evaluate-customer-product", String.class), RedisParam.class);
}
@Override
public void execute(BusUpdateCardStatusRequest request) {
CustomerProduct customerProduct = getCustomerProductByCardNumber(request.getCustomerReference(),
request.getDevice().getDeviceSessionReference(),
request.getCardReference().getCardNumber());
StatusResponse statusResponse = paymentCardPort.updateCardStatus(customerProduct.getClearAccount(), request);
if (!statusResponse.statusCode().equals(RESULT_OK)) {
throw new BanBackendException(statusResponse.statusCode(), statusResponse.message());
}
}
private CustomerProduct getCustomerProductByCardNumber(CustomerReference customerReference, String deviceSessionReference, String cardNumber) {
String redisKey = redisParam.getPrefix().formatted(customerReference.getCustomerIdType(),
customerReference.getCustomerId(),
deviceSessionReference);
String products = redisPort.findValue(redisKey);
if (products == null) {
throw new BanRuntimeException(StatusCodes.REDIS_DATA_NOT_FOUND);
}
CustomerProduct customerProduct = null;
try {
List<CustomerProduct> productList = JsonHelper.getListFromJson(products, CustomerProduct.class);
if (productList != null) {
customerProduct = productList.stream().filter(account -> account.getMaskedAccount().equals(cardNumber))
.findFirst()
.orElse(null);
}
} catch (Exception e) {
throw new BanRuntimeException(StatusCodes.INTERNAL_ERROR, "Error parsing customer products from Redis");
}
if (customerProduct == null || StringHelper.isEmpty(customerProduct.getClearAccount())) {
throw new BanRuntimeException(StatusCodes.REDIS_DATA_NOT_FOUND);
}
return customerProduct;
}
}

View File

@ -0,0 +1,24 @@
package com.banesco.infrastructure.dtos;
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@RegisterForReflection
public class CustomerProduct {
String id;
String sid;
String customerId;
String clearAccount;
String maskedAccount;
String currency;
String accountType;
String otp;
String username;
}

View File

@ -0,0 +1,22 @@
package com.banesco.infrastructure.dtos.card;
import com.banesco.common.domain.dto.bian.customer.CustomerReference;
import com.banesco.common.domain.dto.bian.device.Device;
import com.banesco.domain.bian.dto.CardReference;
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@RegisterForReflection
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UpdateCardStatusRequest {
String requestId;
String fintechId;
CustomerReference customerReference;
Device device;
CardReference cardReference;
}

View File

@ -0,0 +1,22 @@
package com.banesco.infrastructure.dtos.card;
import com.banesco.common.domain.dto.bian.response.BaseResponse;
import com.banesco.common.domain.dto.bian.response.StatusResponse;
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.Data;
import lombok.EqualsAndHashCode;
@RegisterForReflection
@Data
@EqualsAndHashCode(callSuper = false)
public class UpdateCardStatusResponse extends BaseResponse {
public UpdateCardStatusResponse() {
super();
}
public UpdateCardStatusResponse(StatusResponse statusResponse) {
super(statusResponse);
}
}

View File

@ -0,0 +1,141 @@
package com.banesco.infrastructure.dtos.osb;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public class AdditionalStatus {
protected String statusType;
protected String statusCode;
protected String statusDesc;
protected String validationType;
protected String severity;
protected String lineNumber;
/**
* Gets the value of the statusType property.
*
* @return possible object is
* {@link String }
*/
public String getStatusType() {
return statusType;
}
/**
* Sets the value of the statusType property.
*
* @param value allowed object is
* {@link String }
*/
public void setStatusType(String value) {
this.statusType = value;
}
/**
* Gets the value of the statusCode property.
*
* @return possible object is
* {@link String }
*/
public String getStatusCode() {
return statusCode;
}
/**
* Sets the value of the statusCode property.
*
* @param value allowed object is
* {@link String }
*/
public void setStatusCode(String value) {
this.statusCode = value;
}
/**
* Gets the value of the statusDesc property.
*
* @return possible object is
* {@link String }
*/
public String getStatusDesc() {
return statusDesc;
}
/**
* Sets the value of the statusDesc property.
*
* @param value allowed object is
* {@link String }
*/
public void setStatusDesc(String value) {
this.statusDesc = value;
}
/**
* Gets the value of the validationType property.
*
* @return possible object is
* {@link String }
*/
public String getValidationType() {
return validationType;
}
/**
* Sets the value of the validationType property.
*
* @param value allowed object is
* {@link String }
*/
public void setValidationType(String value) {
this.validationType = value;
}
/**
* Gets the value of the severity property.
*
* @return possible object is
* {@link String }
*/
public String getSeverity() {
return severity;
}
/**
* Sets the value of the severity property.
*
* @param value allowed object is
* {@link String }
*/
public void setSeverity(String value) {
this.severity = value;
}
/**
* Gets the value of the lineNumber property.
*
* @return possible object is
* {@link String }
*/
public String getLineNumber() {
return lineNumber;
}
/**
* Sets the value of the lineNumber property.
*
* @param value allowed object is
* {@link String }
*/
public void setLineNumber(String value) {
this.lineNumber = value;
}
}

View File

@ -0,0 +1,40 @@
package com.banesco.infrastructure.dtos.osb;
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@RegisterForReflection
@NoArgsConstructor
public class ApplicantData implements Cloneable {
protected String enterpriseCode;
protected String privateChannelId;
protected String ipAddress;
protected String hostName;
protected String stadisticId;
protected String application;
protected String nationality;
protected String idDocument;
protected String rolType;
protected String planCode;
protected String channel;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

View File

@ -0,0 +1,523 @@
package com.banesco.infrastructure.dtos.osb;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
import java.util.ArrayList;
import java.util.List;
/**
* <p>Java class for MsgRqHdr complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="MsgRqHdr"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="MessageDate" type="{http://xmlns.banesco.com/EnterpriseObjects/MsgRqHdr}datePattern" minOccurs="0"/&gt;
* &lt;element name="MessageTime" type="{http://xmlns.banesco.com/EnterpriseObjects/MsgRqHdr}timePattern" minOccurs="0"/&gt;
* &lt;element name="RequestId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="LastStatusRequest" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="FinalStatusRequest" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="ResumeId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="ReverseId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="LineId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="SourceChannelCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="SupervisorCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="OperatorCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="RequestedOperationType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="NetworkTrnInfo" type="{http://xmlns.banesco.com/EnterpriseObjects/MsgRqHdr}NetworkTrnInfo" maxOccurs="unbounded" minOccurs="0"/&gt;
* &lt;element name="ApplicantData" type="{http://xmlns.banesco.com/EnterpriseObjects/MsgRqHdr}ApplicantData" minOccurs="0"/&gt;
* &lt;element name="RecCtrlIn" type="{http://xmlns.banesco.com/EnterpriseObjects/MsgRqHdr}RecCtrlIn" minOccurs="0"/&gt;
* &lt;element name="ReturnValue" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="MessageId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="Priority" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt;
* &lt;element name="VBProtocol" type="{http://xmlns.banesco.com/EnterpriseObjects/MsgRqHdr}VBProtocol" minOccurs="0"/&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MsgRqHdr", propOrder = {
"messageDate",
"messageTime",
"requestId",
"lastStatusRequest",
"finalStatusRequest",
"resumeId",
"reverseId",
"lineId",
"sourceChannelCode",
"supervisorCode",
"operatorCode",
"requestedOperationType",
"networkTrnInfo",
"applicantData",
"recCtrlIn",
"returnValue",
"messageId",
"priority",
"vbProtocol"
})
@RegisterForReflection
public class MsgRqHdr implements Cloneable {
@XmlElement(name = "MessageDate")
protected String messageDate;
@XmlElement(name = "MessageTime")
protected String messageTime;
@XmlElement(name = "RequestId")
protected String requestId;
@XmlElement(name = "LastStatusRequest")
protected String lastStatusRequest;
@XmlElement(name = "FinalStatusRequest")
protected String finalStatusRequest;
@XmlElement(name = "ResumeId")
protected String resumeId;
@XmlElement(name = "ReverseId")
protected String reverseId;
@XmlElement(name = "LineId")
protected String lineId;
@XmlElement(name = "SourceChannelCode")
protected String sourceChannelCode;
@XmlElement(name = "SupervisorCode")
protected String supervisorCode;
@XmlElement(name = "OperatorCode")
protected String operatorCode;
@XmlElement(name = "RequestedOperationType")
protected String requestedOperationType;
@XmlElement(name = "NetworkTrnInfo")
protected List<NetworkTrnInfo> networkTrnInfo;
@XmlElement(name = "ApplicantData")
protected ApplicantData applicantData;
@XmlElement(name = "RecCtrlIn")
protected RecCtrlIn recCtrlIn;
@XmlElement(name = "ReturnValue")
protected String returnValue;
@XmlElement(name = "MessageId")
protected String messageId;
@XmlElement(name = "Priority")
protected String priority;
@XmlElement(name = "VBProtocol")
protected VBProtocol vbProtocol;
/**
* Gets the value of the messageDate property.
*
* @return possible object is
* {@link String }
*/
public String getMessageDate() {
return messageDate;
}
/**
* Sets the value of the messageDate property.
*
* @param value allowed object is
* {@link String }
*/
public void setMessageDate(String value) {
this.messageDate = value;
}
/**
* Gets the value of the messageTime property.
*
* @return possible object is
* {@link String }
*/
public String getMessageTime() {
return messageTime;
}
/**
* Sets the value of the messageTime property.
*
* @param value allowed object is
* {@link String }
*/
public void setMessageTime(String value) {
this.messageTime = value;
}
/**
* Gets the value of the requestId property.
*
* @return possible object is
* {@link String }
*/
public String getRequestId() {
return requestId;
}
/**
* Sets the value of the requestId property.
*
* @param value allowed object is
* {@link String }
*/
public void setRequestId(String value) {
this.requestId = value;
}
/**
* Gets the value of the lastStatusRequest property.
*
* @return possible object is
* {@link String }
*/
public String getLastStatusRequest() {
return lastStatusRequest;
}
/**
* Sets the value of the lastStatusRequest property.
*
* @param value allowed object is
* {@link String }
*/
public void setLastStatusRequest(String value) {
this.lastStatusRequest = value;
}
/**
* Gets the value of the finalStatusRequest property.
*
* @return possible object is
* {@link String }
*/
public String getFinalStatusRequest() {
return finalStatusRequest;
}
/**
* Sets the value of the finalStatusRequest property.
*
* @param value allowed object is
* {@link String }
*/
public void setFinalStatusRequest(String value) {
this.finalStatusRequest = value;
}
/**
* Gets the value of the resumeId property.
*
* @return possible object is
* {@link String }
*/
public String getResumeId() {
return resumeId;
}
/**
* Sets the value of the resumeId property.
*
* @param value allowed object is
* {@link String }
*/
public void setResumeId(String value) {
this.resumeId = value;
}
/**
* Gets the value of the reverseId property.
*
* @return possible object is
* {@link String }
*/
public String getReverseId() {
return reverseId;
}
/**
* Sets the value of the reverseId property.
*
* @param value allowed object is
* {@link String }
*/
public void setReverseId(String value) {
this.reverseId = value;
}
/**
* Gets the value of the lineId property.
*
* @return possible object is
* {@link String }
*/
public String getLineId() {
return lineId;
}
/**
* Sets the value of the lineId property.
*
* @param value allowed object is
* {@link String }
*/
public void setLineId(String value) {
this.lineId = value;
}
/**
* Gets the value of the sourceChannelCode property.
*
* @return possible object is
* {@link String }
*/
public String getSourceChannelCode() {
return sourceChannelCode;
}
/**
* Sets the value of the sourceChannelCode property.
*
* @param value allowed object is
* {@link String }
*/
public void setSourceChannelCode(String value) {
this.sourceChannelCode = value;
}
/**
* Gets the value of the supervisorCode property.
*
* @return possible object is
* {@link String }
*/
public String getSupervisorCode() {
return supervisorCode;
}
/**
* Sets the value of the supervisorCode property.
*
* @param value allowed object is
* {@link String }
*/
public void setSupervisorCode(String value) {
this.supervisorCode = value;
}
/**
* Gets the value of the operatorCode property.
*
* @return possible object is
* {@link String }
*/
public String getOperatorCode() {
return operatorCode;
}
/**
* Sets the value of the operatorCode property.
*
* @param value allowed object is
* {@link String }
*/
public void setOperatorCode(String value) {
this.operatorCode = value;
}
/**
* Gets the value of the requestedOperationType property.
*
* @return possible object is
* {@link String }
*/
public String getRequestedOperationType() {
return requestedOperationType;
}
/**
* Sets the value of the requestedOperationType property.
*
* @param value allowed object is
* {@link String }
*/
public void setRequestedOperationType(String value) {
this.requestedOperationType = value;
}
/**
* Gets the value of the networkTrnInfo property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the Jakarta XML Binding object.
* This is why there is not a <CODE>set</CODE> method for the networkTrnInfo property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNetworkTrnInfo().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link NetworkTrnInfo }
*/
public List<NetworkTrnInfo> getNetworkTrnInfo() {
if (networkTrnInfo == null) {
networkTrnInfo = new ArrayList<NetworkTrnInfo>();
}
return this.networkTrnInfo;
}
/**
* Gets the value of the applicantData property.
*
* @return possible object is
* {@link ApplicantData }
*/
public ApplicantData getApplicantData() {
return applicantData;
}
/**
* Sets the value of the applicantData property.
*
* @param value allowed object is
* {@link ApplicantData }
*/
public void setApplicantData(ApplicantData value) {
this.applicantData = value;
}
/**
* Gets the value of the recCtrlIn property.
*
* @return possible object is
* {@link RecCtrlIn }
*/
public RecCtrlIn getRecCtrlIn() {
return recCtrlIn;
}
/**
* Sets the value of the recCtrlIn property.
*
* @param value allowed object is
* {@link RecCtrlIn }
*/
public void setRecCtrlIn(RecCtrlIn value) {
this.recCtrlIn = value;
}
/**
* Gets the value of the returnValue property.
*
* @return possible object is
* {@link String }
*/
public String getReturnValue() {
return returnValue;
}
/**
* Sets the value of the returnValue property.
*
* @param value allowed object is
* {@link String }
*/
public void setReturnValue(String value) {
this.returnValue = value;
}
/**
* Gets the value of the messageId property.
*
* @return possible object is
* {@link String }
*/
public String getMessageId() {
return messageId;
}
/**
* Sets the value of the messageId property.
*
* @param value allowed object is
* {@link String }
*/
public void setMessageId(String value) {
this.messageId = value;
}
/**
* Gets the value of the priority property.
*
* @return possible object is
* {@link String }
*/
public String getPriority() {
return priority;
}
/**
* Sets the value of the priority property.
*
* @param value allowed object is
* {@link String }
*/
public void setPriority(String value) {
this.priority = value;
}
/**
* Gets the value of the vbProtocol property.
*
* @return possible object is
* {@link VBProtocol }
*/
public VBProtocol getVBProtocol() {
return vbProtocol;
}
public void setTransactionCode(String transactionCode) {
this.getNetworkTrnInfo().get(0).setTransactionCode(transactionCode);
}
public void setNetworkTrnInfo(List<NetworkTrnInfo> networkTrnInfo) {
this.networkTrnInfo = networkTrnInfo;
}
/* public void setVBProtocol(VBProtocol value) {
this.vbProtocol = value;
}
*/
public void setVbprotocol(VBProtocol value) {
this.vbProtocol = value;
}
public void setVbProtocol(VBProtocol value) {
this.vbProtocol = value;
}
@Override
public MsgRqHdr clone() throws CloneNotSupportedException {
MsgRqHdr msgRqHdrClone = (MsgRqHdr) super.clone();
msgRqHdrClone.applicantData = (ApplicantData) applicantData.clone();
msgRqHdrClone.vbProtocol = (VBProtocol) vbProtocol.clone();
msgRqHdrClone.networkTrnInfo = new ArrayList<>();
for (NetworkTrnInfo trnInfo : networkTrnInfo) {
msgRqHdrClone.networkTrnInfo.add((NetworkTrnInfo) trnInfo.clone());
}
return msgRqHdrClone;
}
}

View File

@ -0,0 +1,527 @@
package com.banesco.infrastructure.dtos.osb;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.List;
@RegisterForReflection
public class MsgRsHdr {
protected String privateChannelId;
protected String finalStatusRequest;
protected String countDataOut;
protected String headerTypeReg;
protected String detailTypeReg;
protected String transactionCode;
protected String supervisorCode;
protected String operationType;
protected String transactionConsecutive;
protected String detailReg;
protected List<String> registerNumber;
protected String transactionType;
protected String requestId;
protected String requestedOperationType;
protected String messageDate;
protected String transactionTime;
protected String lastStatusRequest;
protected String returnValue;
protected String requestStatus;
protected String messageTime;
protected String transacctionDate;
protected String requestNumber;
protected String appName;
/**
* Gets the value of the privateChannelId property.
*
* @return possible object is
* {@link String }
*/
public String getPrivateChannelId() {
return privateChannelId;
}
/**
* Sets the value of the privateChannelId property.
*
* @param value allowed object is
* {@link String }
*/
public void setPrivateChannelId(String value) {
this.privateChannelId = value;
}
/**
* Gets the value of the finalStatusRequest property.
*
* @return possible object is
* {@link String }
*/
public String getFinalStatusRequest() {
return finalStatusRequest;
}
/**
* Sets the value of the finalStatusRequest property.
*
* @param value allowed object is
* {@link String }
*/
public void setFinalStatusRequest(String value) {
this.finalStatusRequest = value;
}
/**
* Gets the value of the countDataOut property.
*
* @return possible object is
* {@link String }
*/
public String getCountDataOut() {
return countDataOut;
}
/**
* Sets the value of the countDataOut property.
*
* @param value allowed object is
* {@link String }
*/
public void setCountDataOut(String value) {
this.countDataOut = value;
}
/**
* Gets the value of the headerTypeReg property.
*
* @return possible object is
* {@link String }
*/
public String getHeaderTypeReg() {
return headerTypeReg;
}
/**
* Sets the value of the headerTypeReg property.
*
* @param value allowed object is
* {@link String }
*/
public void setHeaderTypeReg(String value) {
this.headerTypeReg = value;
}
/**
* Gets the value of the detailTypeReg property.
*
* @return possible object is
* {@link String }
*/
public String getDetailTypeReg() {
return detailTypeReg;
}
/**
* Sets the value of the detailTypeReg property.
*
* @param value allowed object is
* {@link String }
*/
public void setDetailTypeReg(String value) {
this.detailTypeReg = value;
}
/**
* Gets the value of the transactionCode property.
*
* @return possible object is
* {@link String }
*/
public String getTransactionCode() {
return transactionCode;
}
/**
* Sets the value of the transactionCode property.
*
* @param value allowed object is
* {@link String }
*/
public void setTransactionCode(String value) {
this.transactionCode = value;
}
/**
* Gets the value of the supervisorCode property.
*
* @return possible object is
* {@link String }
*/
public String getSupervisorCode() {
return supervisorCode;
}
/**
* Sets the value of the supervisorCode property.
*
* @param value allowed object is
* {@link String }
*/
public void setSupervisorCode(String value) {
this.supervisorCode = value;
}
/**
* Gets the value of the operationType property.
*
* @return possible object is
* {@link String }
*/
public String getOperationType() {
return operationType;
}
/**
* Sets the value of the operationType property.
*
* @param value allowed object is
* {@link String }
*/
public void setOperationType(String value) {
this.operationType = value;
}
/**
* Gets the value of the transactionConsecutive property.
*
* @return possible object is
* {@link String }
*/
public String getTransactionConsecutive() {
return transactionConsecutive;
}
/**
* Sets the value of the transactionConsecutive property.
*
* @param value allowed object is
* {@link String }
*/
public void setTransactionConsecutive(String value) {
this.transactionConsecutive = value;
}
/**
* Gets the value of the detailReg property.
*
* @return possible object is
* {@link String }
*/
public String getDetailReg() {
return detailReg;
}
/**
* Sets the value of the detailReg property.
*
* @param value allowed object is
* {@link String }
*/
public void setDetailReg(String value) {
this.detailReg = value;
}
/**
* Gets the value of the registerNumber property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the Jakarta XML Binding object.
* This is why there is not a <CODE>set</CODE> method for the registerNumber property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRegisterNumber().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*/
public List<String> getRegisterNumber() {
if (registerNumber == null) {
registerNumber = new ArrayList<String>();
}
return this.registerNumber;
}
/**
* Gets the value of the transactionType property.
*
* @return possible object is
* {@link String }
*/
public String getTransactionType() {
return transactionType;
}
/**
* Sets the value of the transactionType property.
*
* @param value allowed object is
* {@link String }
*/
public void setTransactionType(String value) {
this.transactionType = value;
}
/**
* Gets the value of the requestId property.
*
* @return possible object is
* {@link String }
*/
public String getRequestId() {
return requestId;
}
/**
* Sets the value of the requestId property.
*
* @param value allowed object is
* {@link String }
*/
public void setRequestId(String value) {
this.requestId = value;
}
/**
* Gets the value of the requestedOperationType property.
*
* @return possible object is
* {@link String }
*/
public String getRequestedOperationType() {
return requestedOperationType;
}
/**
* Sets the value of the requestedOperationType property.
*
* @param value allowed object is
* {@link String }
*/
public void setRequestedOperationType(String value) {
this.requestedOperationType = value;
}
/**
* Gets the value of the messageDate property.
*
* @return possible object is
* {@link String }
*/
public String getMessageDate() {
return messageDate;
}
/**
* Sets the value of the messageDate property.
*
* @param value allowed object is
* {@link String }
*/
public void setMessageDate(String value) {
this.messageDate = value;
}
/**
* Gets the value of the transactionTime property.
*
* @return possible object is
* {@link String }
*/
public String getTransactionTime() {
return transactionTime;
}
/**
* Sets the value of the transactionTime property.
*
* @param value allowed object is
* {@link String }
*/
public void setTransactionTime(String value) {
this.transactionTime = value;
}
/**
* Gets the value of the lastStatusRequest property.
*
* @return possible object is
* {@link String }
*/
public String getLastStatusRequest() {
return lastStatusRequest;
}
/**
* Sets the value of the lastStatusRequest property.
*
* @param value allowed object is
* {@link String }
*/
public void setLastStatusRequest(String value) {
this.lastStatusRequest = value;
}
/**
* Gets the value of the returnValue property.
*
* @return possible object is
* {@link String }
*/
public String getReturnValue() {
return returnValue;
}
/**
* Sets the value of the returnValue property.
*
* @param value allowed object is
* {@link String }
*/
public void setReturnValue(String value) {
this.returnValue = value;
}
/**
* Gets the value of the requestStatus property.
*
* @return possible object is
* {@link String }
*/
public String getRequestStatus() {
return requestStatus;
}
/**
* Sets the value of the requestStatus property.
*
* @param value allowed object is
* {@link String }
*/
public void setRequestStatus(String value) {
this.requestStatus = value;
}
/**
* Gets the value of the messageTime property.
*
* @return possible object is
* {@link String }
*/
public String getMessageTime() {
return messageTime;
}
/**
* Sets the value of the messageTime property.
*
* @param value allowed object is
* {@link String }
*/
public void setMessageTime(String value) {
this.messageTime = value;
}
/**
* Gets the value of the transacctionDate property.
*
* @return possible object is
* {@link String }
*/
public String getTransacctionDate() {
return transacctionDate;
}
/**
* Sets the value of the transacctionDate property.
*
* @param value allowed object is
* {@link String }
*/
public void setTransacctionDate(String value) {
this.transacctionDate = value;
}
/**
* Gets the value of the requestNumber property.
*
* @return possible object is
* {@link String }
*/
public String getRequestNumber() {
return requestNumber;
}
/**
* Sets the value of the requestNumber property.
*
* @param value allowed object is
* {@link String }
*/
public void setRequestNumber(String value) {
this.requestNumber = value;
}
/**
* Gets the value of the appName property.
*
* @return possible object is
* {@link String }
*/
public String getAppName() {
return appName;
}
/**
* Sets the value of the appName property.
*
* @param value allowed object is
* {@link String }
*/
public void setAppName(String value) {
this.appName = value;
}
}

View File

@ -0,0 +1,412 @@
package com.banesco.infrastructure.dtos.osb;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "NetworkTrnInfo", propOrder = {
"transactionConsecutive",
"registerNumber",
"originatorName",
"operationType",
"transactionType",
"transactionCode",
"transactionDate",
"transactionTime",
"bankId",
"agencyCode",
"channelId",
"channelUserId",
"operationExecIndicator",
"configuredTransactionCode",
"desc",
"userId",
"userType"
})
@RegisterForReflection
public class NetworkTrnInfo implements Cloneable {
@XmlElement(name = "TransactionConsecutive")
protected String transactionConsecutive;
@XmlElement(name = "RegisterNumber")
protected String registerNumber;
@XmlElement(name = "OriginatorName")
protected String originatorName;
@XmlElement(name = "OperationType")
protected String operationType;
@XmlElement(name = "TransactionType")
protected String transactionType;
@XmlElement(name = "TransactionCode")
protected String transactionCode;
@XmlElement(name = "TransactionDate")
protected String transactionDate;
@XmlElement(name = "TransactionTime")
protected String transactionTime;
@XmlElement(name = "BankId")
protected String bankId;
@XmlElement(name = "AgencyCode")
protected String agencyCode;
@XmlElement(name = "ChannelId")
protected String channelId;
@XmlElement(name = "ChannelUserId")
protected String channelUserId;
@XmlElement(name = "OperationExecIndicator")
protected String operationExecIndicator;
@XmlElement(name = "ConfiguredTransactionCode")
protected String configuredTransactionCode;
@XmlElement(name = "Desc")
protected String desc;
@XmlElement(name = "UserId")
protected String userId;
@XmlElement(name = "UserType")
protected String userType;
/**
* Gets the value of the transactionConsecutive property.
*
* @return possible object is
* {@link String }
*/
public String getTransactionConsecutive() {
return transactionConsecutive;
}
/**
* Sets the value of the transactionConsecutive property.
*
* @param value allowed object is
* {@link String }
*/
public void setTransactionConsecutive(String value) {
this.transactionConsecutive = value;
}
/**
* Gets the value of the registerNumber property.
*
* @return possible object is
* {@link String }
*/
public String getRegisterNumber() {
return registerNumber;
}
/**
* Sets the value of the registerNumber property.
*
* @param value allowed object is
* {@link String }
*/
public void setRegisterNumber(String value) {
this.registerNumber = value;
}
/**
* Gets the value of the originatorName property.
*
* @return possible object is
* {@link String }
*/
public String getOriginatorName() {
return originatorName;
}
/**
* Sets the value of the originatorName property.
*
* @param value allowed object is
* {@link String }
*/
public void setOriginatorName(String value) {
this.originatorName = value;
}
/**
* Gets the value of the operationType property.
*
* @return possible object is
* {@link String }
*/
public String getOperationType() {
return operationType;
}
/**
* Sets the value of the operationType property.
*
* @param value allowed object is
* {@link String }
*/
public void setOperationType(String value) {
this.operationType = value;
}
/**
* Gets the value of the transactionType property.
*
* @return possible object is
* {@link String }
*/
public String getTransactionType() {
return transactionType;
}
/**
* Sets the value of the transactionType property.
*
* @param value allowed object is
* {@link String }
*/
public void setTransactionType(String value) {
this.transactionType = value;
}
/**
* Gets the value of the transactionCode property.
*
* @return possible object is
* {@link String }
*/
public String getTransactionCode() {
return transactionCode;
}
/**
* Sets the value of the transactionCode property.
*
* @param value allowed object is
* {@link String }
*/
public void setTransactionCode(String value) {
this.transactionCode = value;
}
/**
* Gets the value of the transactionDate property.
*
* @return possible object is
* {@link String }
*/
public String getTransactionDate() {
return transactionDate;
}
/**
* Sets the value of the transactionDate property.
*
* @param value allowed object is
* {@link String }
*/
public void setTransactionDate(String value) {
this.transactionDate = value;
}
/**
* Gets the value of the transactionTime property.
*
* @return possible object is
* {@link String }
*/
public String getTransactionTime() {
return transactionTime;
}
/**
* Sets the value of the transactionTime property.
*
* @param value allowed object is
* {@link String }
*/
public void setTransactionTime(String value) {
this.transactionTime = value;
}
/**
* Gets the value of the bankId property.
*
* @return possible object is
* {@link String }
*/
public String getBankId() {
return bankId;
}
/**
* Sets the value of the bankId property.
*
* @param value allowed object is
* {@link String }
*/
public void setBankId(String value) {
this.bankId = value;
}
/**
* Gets the value of the agencyCode property.
*
* @return possible object is
* {@link String }
*/
public String getAgencyCode() {
return agencyCode;
}
/**
* Sets the value of the agencyCode property.
*
* @param value allowed object is
* {@link String }
*/
public void setAgencyCode(String value) {
this.agencyCode = value;
}
/**
* Gets the value of the channelId property.
*
* @return possible object is
* {@link String }
*/
public String getChannelId() {
return channelId;
}
/**
* Sets the value of the channelId property.
*
* @param value allowed object is
* {@link String }
*/
public void setChannelId(String value) {
this.channelId = value;
}
/**
* Gets the value of the channelUserId property.
*
* @return possible object is
* {@link String }
*/
public String getChannelUserId() {
return channelUserId;
}
/**
* Sets the value of the channelUserId property.
*
* @param value allowed object is
* {@link String }
*/
public void setChannelUserId(String value) {
this.channelUserId = value;
}
/**
* Gets the value of the operationExecIndicator property.
*
* @return possible object is
* {@link String }
*/
public String getOperationExecIndicator() {
return operationExecIndicator;
}
/**
* Sets the value of the operationExecIndicator property.
*
* @param value allowed object is
* {@link String }
*/
public void setOperationExecIndicator(String value) {
this.operationExecIndicator = value;
}
/**
* Gets the value of the configuredTransactionCode property.
*
* @return possible object is
* {@link String }
*/
public String getConfiguredTransactionCode() {
return configuredTransactionCode;
}
/**
* Sets the value of the configuredTransactionCode property.
*
* @param value allowed object is
* {@link String }
*/
public void setConfiguredTransactionCode(String value) {
this.configuredTransactionCode = value;
}
/**
* Gets the value of the desc property.
*
* @return possible object is
* {@link String }
*/
public String getDesc() {
return desc;
}
/**
* Sets the value of the desc property.
*
* @param value allowed object is
* {@link String }
*/
public void setDesc(String value) {
this.desc = value;
}
/**
* Gets the value of the userId property.
*
* @return possible object is
* {@link String }
*/
public String getUserId() {
return userId;
}
/**
* Sets the value of the userId property.
*
* @param value allowed object is
* {@link String }
*/
public void setUserId(String value) {
this.userId = value;
}
/**
* Gets the value of the userType property.
*
* @return possible object is
* {@link String }
*/
public String getUserType() {
return userType;
}
/**
* Sets the value of the userType property.
*
* @param value allowed object is
* {@link String }
*/
public void setUserType(String value) {
this.userType = value;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

View File

@ -0,0 +1,23 @@
package com.banesco.infrastructure.dtos.osb;
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@RegisterForReflection
@NoArgsConstructor
@AllArgsConstructor
public class RecCtrlIn implements Cloneable {
protected String maxRec;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

View File

@ -0,0 +1,218 @@
package com.banesco.infrastructure.dtos.osb;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
@RegisterForReflection
public class Status {
protected String statusType;
protected String statusCode;
protected String statusDesc;
protected String applicationName;
protected BigInteger lineNumber;
protected List<AdditionalStatus> additionalStatus;
protected String severity;
protected String statusInd;
protected String logId;
/**
* Gets the value of the statusType property.
*
* @return possible object is
* {@link String }
*/
public String getStatusType() {
return statusType;
}
/**
* Sets the value of the statusType property.
*
* @param value allowed object is
* {@link String }
*/
public void setStatusType(String value) {
this.statusType = value;
}
/**
* Gets the value of the statusCode property.
*
* @return possible object is
* {@link String }
*/
public String getStatusCode() {
return statusCode;
}
/**
* Sets the value of the statusCode property.
*
* @param value allowed object is
* {@link String }
*/
public void setStatusCode(String value) {
this.statusCode = value;
}
/**
* Gets the value of the statusDesc property.
*
* @return possible object is
* {@link String }
*/
public String getStatusDesc() {
return statusDesc;
}
/**
* Sets the value of the statusDesc property.
*
* @param value allowed object is
* {@link String }
*/
public void setStatusDesc(String value) {
this.statusDesc = value;
}
/**
* Gets the value of the applicationName property.
*
* @return possible object is
* {@link String }
*/
public String getApplicationName() {
return applicationName;
}
/**
* Sets the value of the applicationName property.
*
* @param value allowed object is
* {@link String }
*/
public void setApplicationName(String value) {
this.applicationName = value;
}
/**
* Gets the value of the lineNumber property.
*
* @return possible object is
* {@link BigInteger }
*/
public BigInteger getLineNumber() {
return lineNumber;
}
/**
* Sets the value of the lineNumber property.
*
* @param value allowed object is
* {@link BigInteger }
*/
public void setLineNumber(BigInteger value) {
this.lineNumber = value;
}
/**
* Gets the value of the additionalStatus property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the Jakarta XML Binding object.
* This is why there is not a <CODE>set</CODE> method for the additionalStatus property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAdditionalStatus().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AdditionalStatus }
*/
public List<AdditionalStatus> getAdditionalStatus() {
if (additionalStatus == null) {
additionalStatus = new ArrayList<AdditionalStatus>();
}
return this.additionalStatus;
}
/**
* Gets the value of the severity property.
*
* @return possible object is
* {@link String }
*/
public String getSeverity() {
return severity;
}
/**
* Sets the value of the severity property.
*
* @param value allowed object is
* {@link String }
*/
public void setSeverity(String value) {
this.severity = value;
}
/**
* Gets the value of the statusInd property.
*
* @return possible object is
* {@link String }
*/
public String getStatusInd() {
return statusInd;
}
/**
* Sets the value of the statusInd property.
*
* @param value allowed object is
* {@link String }
*/
public void setStatusInd(String value) {
this.statusInd = value;
}
/**
* Gets the value of the logId property.
*
* @return possible object is
* {@link String }
*/
public String getLogId() {
return logId;
}
/**
* Sets the value of the logId property.
*
* @param value allowed object is
* {@link String }
*/
public void setLogId(String value) {
this.logId = value;
}
}

View File

@ -0,0 +1,77 @@
package com.banesco.infrastructure.dtos.osb;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VBProtocol", propOrder = {
"vbProtocolInd",
"transactionInd"
})
@RegisterForReflection
public class VBProtocol implements Cloneable {
@XmlElement(name = "VBProtocolInd", defaultValue = "false")
protected Boolean vbProtocolInd;
@XmlElement(name = "TransactionInd", defaultValue = "false")
protected Boolean transactionInd;
/**
* Gets the value of the vbProtocolInd property.
*
* @return possible object is
* {@link Boolean }
*/
public Boolean isVBProtocolInd() {
return vbProtocolInd;
}
/**
* Sets the value of the vbProtocolInd property.
*
* @param value allowed object is
* {@link Boolean }
*/
public void setVBProtocolInd(Boolean value) {
this.vbProtocolInd = value;
}
/* public void setVbprotocolInd(Boolean vbprotocolInd) {
this.vbProtocolInd = vbprotocolInd;
}*/
public void setVbProtocolInd(Boolean vbprotocolInd) {
this.vbProtocolInd = vbprotocolInd;
}
/**
* Gets the value of the transactionInd property.
*
* @return possible object is
* {@link Boolean }
*/
public Boolean isTransactionInd() {
return transactionInd;
}
/**
* Sets the value of the transactionInd property.
*
* @param value allowed object is
* {@link Boolean }
*/
public void setTransactionInd(Boolean value) {
this.transactionInd = value;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

View File

@ -0,0 +1,38 @@
package com.banesco.infrastructure.healthcheck;
import jakarta.enterprise.context.ApplicationScoped;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.Liveness;
@Liveness
@ApplicationScoped
@Slf4j
public class ApplicationLivenessCheck implements HealthCheck {
private final String applicationName;
private final String applicationVersion;
public ApplicationLivenessCheck(
@ConfigProperty(name = "quarkus.application.name", defaultValue = "api-application") String applicationName,
@ConfigProperty(name = "quarkus.application.version", defaultValue = "unknown") String applicationVersion) {
this.applicationName = applicationName;
this.applicationVersion = applicationVersion;
}
@Override
public HealthCheckResponse call() {
log.debug("Ejecutando liveness health check: {}", System.currentTimeMillis());
// Simplemente reportamos que la aplicación está activa
// Si este código se ejecuta, significa que la JVM está funcionando
return HealthCheckResponse.named("API")
.up()
.withData("application", applicationName)
.withData("version", applicationVersion)
.withData("timestamp", System.currentTimeMillis())
.build();
}
}

View File

@ -0,0 +1,69 @@
package com.banesco.infrastructure.healthcheck;
import com.banesco.commons.config.AppConf;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.Readiness;
import java.util.concurrent.Semaphore;
@SuppressWarnings("unused")
@Readiness
@Slf4j
@ApplicationScoped
public class ConfigHealthCheck implements HealthCheck {
// Semáforo para evitar múltiples health checks simultáneos
private final Semaphore healthCheckSemaphore = new Semaphore(1);
@Inject
public ConfigHealthCheck() {
log.info("ConfigHealthCheck inicializado");
}
@Override
public HealthCheckResponse call() {
if (!healthCheckSemaphore.tryAcquire()) {
log.debug("Health check en progreso, saltando esta invocación");
return HealthCheckResponse.builder()
.name("ApiConfig")
.withData("AppConf", "progressing")
.withData("timestamp", System.currentTimeMillis())
.build();
}
try {
AppConf.getInstance();
return buildResponse(null);
} catch (Exception e) {
return buildResponse(e.getMessage());
} finally {
healthCheckSemaphore.release();
}
}
private HealthCheckResponse buildResponse(String errorMessage) {
var responseBuilder = HealthCheckResponse.named("ApiConfig");
if (errorMessage == null) {
return responseBuilder.up()
.withData("AppConf", "configured")
.withData("timestamp", System.currentTimeMillis())
.build();
}
return responseBuilder.down()
.withData("AppConf", "wrong")
.withData("timestamp", System.currentTimeMillis())
.withData("errorMessage", errorMessage)
.build();
}
}

View File

@ -0,0 +1,34 @@
package com.banesco.infrastructure.redis;
import com.banesco.domain.ports.outbound.RedisPort;
import io.quarkus.redis.datasource.RedisDataSource;
import io.quarkus.redis.datasource.value.SetArgs;
import jakarta.enterprise.context.ApplicationScoped;
import lombok.extern.slf4j.Slf4j;
@ApplicationScoped
@Slf4j
public class RedisAdapter implements RedisPort {
private final RedisDataSource redisDataSource;
public RedisAdapter(RedisDataSource redisDataSource) {
this.redisDataSource = redisDataSource;
}
@Override
public String findValue(String key) {
String result = redisDataSource.value(String.class).get(key);
log.info("REDIS FIND key: [{}] value: [{}]", key, result);
return result;
}
@Override
public void setValue(String key, String objectStr, long expiration) {
SetArgs setArgs = new SetArgs();
setArgs.ex(expiration);
log.info("REDIS SAVE key: [{}] value: [{}]", key, objectStr);
redisDataSource.value(String.class).set(key, objectStr, setArgs);
}
}

View File

@ -0,0 +1,52 @@
package com.banesco.infrastructure.rest;
import com.banesco.common.domain.dto.bian.response.StatusResponse;
import com.banesco.common.domain.model.ApiConfig;
import com.banesco.commons.config.AppConf;
import com.banesco.domain.bian.request.BusUpdateCardStatusRequest;
import com.banesco.domain.ports.outbound.PaymentCardPort;
import com.banesco.infrastructure.rest.mappers.PaymentCardMapper;
import com.banesco.infrastructure.rest.repositories.PaymentCardRepository;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;
@ApplicationScoped
@Slf4j
public class PaymentCardAdapter implements PaymentCardPort {
private final PaymentCardRepository paymentRepository;
private final PaymentCardMapper paymentCardMapper;
private final String OPERATION_NAME = "update-card-status";
AppConf appConf;
@Inject
public PaymentCardAdapter(AppConf appConf,
PaymentCardMapper paymentCardMapper) {
this.appConf = appConf;
this.paymentCardMapper = paymentCardMapper;
ApiConfig apiConfig = appConf.loadApiConfig("api.rest-client." + OPERATION_NAME);
paymentRepository = new PaymentCardRepository(apiConfig);
}
public StatusResponse updateCardStatus(String productAccountId, BusUpdateCardStatusRequest request) {
return paymentRepository.updateCardStatus(
this.paymentCardMapper.toBusinessRequest(
appConf.getCurrentState(request.getRequestId()),
request
)
);
}
}

View File

@ -0,0 +1,73 @@
package com.banesco.infrastructure.rest;
import com.banesco.common.domain.dto.bian.device.LoggerHelper;
import com.banesco.common.domain.model.ApiConfig;
import com.banesco.commons.config.AppConf;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.rest.client.RestClientBuilder;
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
@ApplicationScoped
@Slf4j
public class RegisterSecurityAdapter implements RegisterSecurityPort {
private final RegisterSecurityRestClient restClient;
private final String registerSecuritySP;
private final String registerSecurityEventCod;
private final String registerSecurityBankCod;
private final String registerSecurityCurCOd;
@Inject
public RegisterSecurityAdapter(AppConf appConf) {
ApiConfig apiConfig = appConf.loadApiConfig("api.rest-client.register-security");
restClient = RestClientBuilder.newBuilder().baseUri(
URI.create(apiConfig.getUrl())
).
connectTimeout(apiConfig.getTimeout().getConnect(), TimeUnit.MILLISECONDS)
.readTimeout(apiConfig.getTimeout().getResponse(), TimeUnit.MILLISECONDS)
.build(RegisterSecurityRestClient.class);
registerSecuritySP = apiConfig.getConfig().get("sp");
registerSecurityEventCod = apiConfig.getConfig().get("eventCod");
registerSecurityBankCod = apiConfig.getConfig().get("bankCod");
registerSecurityCurCOd = apiConfig.getConfig().get("curCod");
}
public void writeTrace(String requestId, RegisterSecurityRq request) {
request.setSp(registerSecuritySP);
request.setCodEve(registerSecurityEventCod);
request.setCodEve2(registerSecurityEventCod);
request.setCodBan(registerSecurityBankCod);
request.setCodMon(registerSecurityCurCOd);
log.info(LoggerHelper.buildInfoPrivateRequest(requestId, "REGISTER_SECURITY", request));
CompletableFuture.supplyAsync(() -> {
// Simulate some processing
try {
Response responseHttp = restClient.invoke(request);
Object response = responseHttp.readEntity(Object.class);
log.info(LoggerHelper.buildInfoPrivateResponse(requestId, "REGISTER_SECURITY", response != null ? response.toString() : "null"));
} catch (Exception e) {
log.error(LoggerHelper.buildError("REGISTER_SECURITY - " + requestId, "Error calling API: " + e.getMessage()));
log.error("Error writing trace: {}", e.getMessage());
}
return null;
});
}
}

View File

@ -0,0 +1,22 @@
package com.banesco.infrastructure.rest.clients;
import com.banesco.infrastructure.dtos.card.UpdateCardStatusRequest;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
@RegisterForReflection
@RegisterRestClient
public interface BusUpdateCardStatusRestClient {
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response invoke(UpdateCardStatusRequest request);
}

View File

@ -0,0 +1,30 @@
package com.banesco.infrastructure.rest.mappers;
import com.banesco.domain.bian.request.BusUpdateCardStatusRequest;
import com.banesco.domain.models.CurrentState;
import com.banesco.infrastructure.dtos.card.UpdateCardStatusRequest;
import jakarta.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class PaymentCardMapper {
public UpdateCardStatusRequest toBusinessRequest(
CurrentState currentState,
BusUpdateCardStatusRequest receptionRequest
) {
UpdateCardStatusRequest request = new UpdateCardStatusRequest(
currentState.requestId(),
receptionRequest.getCustomerReferenceFintechId(),
receptionRequest.getCustomerReference(),
receptionRequest.getDevice(),
receptionRequest.getCardReference()
);
return request;
}
}

View File

@ -0,0 +1,122 @@
package com.banesco.infrastructure.rest.repositories;
import com.banesco.common.domain.dto.bian.device.JsonHelper;
import com.banesco.common.domain.dto.bian.device.LoggerHelper;
import com.banesco.common.domain.dto.bian.response.StatusResponse;
import com.banesco.common.domain.model.ApiConfig;
import com.banesco.commons.config.StatusCodes;
import com.banesco.commons.utils.ResponseUtil;
import com.banesco.infrastructure.dtos.card.UpdateCardStatusRequest;
import com.banesco.infrastructure.dtos.card.UpdateCardStatusResponse;
import com.banesco.infrastructure.dtos.osb.AdditionalStatus;
import com.banesco.infrastructure.dtos.osb.Status;
import com.banesco.infrastructure.rest.clients.BusUpdateCardStatusRestClient;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.ws.rs.ClientErrorException;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.rest.client.RestClientBuilder;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@RegisterForReflection
@Slf4j
public class PaymentCardRepository {
private final BusUpdateCardStatusRestClient restClient;
private final String OPERATION_NAME = "BUS_UPDATE_CARD_STATUS";
public PaymentCardRepository(ApiConfig apiConfig) {
restClient = RestClientBuilder.newBuilder().baseUri(
URI.create(apiConfig.getUrl())
).
connectTimeout(apiConfig.getTimeout().getConnect(), TimeUnit.MILLISECONDS)
.readTimeout(apiConfig.getTimeout().getResponse(), TimeUnit.MILLISECONDS)
.build(BusUpdateCardStatusRestClient.class);
}
public StatusResponse updateCardStatus(UpdateCardStatusRequest request) {
try {
log.info(LoggerHelper.buildInfoPrivateRequest(request.getRequestId(), OPERATION_NAME, JsonHelper.getJsonFromObject(request)));
Response responseHttp = restClient.invoke(request);
UpdateCardStatusResponse response = responseHttp.readEntity(UpdateCardStatusResponse.class);
log.info(LoggerHelper.buildInfoPrivateResponse(request.getRequestId(), OPERATION_NAME, JsonHelper.getJsonFromObject(response)));
/*
if (response.getStatus().getStatusCode() != null &&
response.getStatus().getStatusCode().equals("000")) {
return ResponseUtil.mapResponse(request.getRequestId(), StatusCodes.SUCCESS_OPERATION);
}
return validateSoapResponseStatus(request.getRequestId(), response.getStatus());
*/
return null;
} catch (ClientErrorException e) {
log.error(LoggerHelper.buildError(OPERATION_NAME + " - " + request.getRequestId(), "Error calling API: " + e.getMessage()));
return ResponseUtil.mapErrorResponse(request.getRequestId(), StatusCodes.FAILED_DEPENDENCY);
} catch (Exception e) {
log.error(LoggerHelper.buildError(OPERATION_NAME + " - " + request.getRequestId(), "Error interno callig API: " + e.getMessage()));
return ResponseUtil.mapErrorResponse(request.getRequestId(), StatusCodes.INTERNAL_ERROR);
}
}
/**
* Validate Property Status If has some error and throw Exception with Code or join(-) codes is no equals to 000
*
* @param status
*/
private StatusResponse validateSoapResponseStatus(String requestId, Status status) {
// Get Back Error
Map<String, String> errors = new HashMap<>();
AdditionalStatus additionalStatus = null;
if (status.getAdditionalStatus() != null) {
for (AdditionalStatus additionalStatusCurrent : status.getAdditionalStatus()) {
if (additionalStatusCurrent.getStatusCode().equals("000")) {
break;
} else {
errors.put(additionalStatusCurrent.getStatusCode(), additionalStatusCurrent.getStatusCode());
if (additionalStatus == null) {
additionalStatus = additionalStatusCurrent;
}
}
}
}
if (!errors.values().isEmpty()) {
/**
* Concat errors
*/
return new StatusResponse(
"error",
errors.values().stream().collect(Collectors.joining("-")).toString(),
additionalStatus.getStatusDesc(),
requestId
);
}
return ResponseUtil.mapErrorResponse(requestId, StatusCodes.INTERNAL_ERROR);
}
}

View File

@ -0,0 +1,25 @@
quarkus:
http:
port: 8080
idle-timeout: 30s
thread-pool:
max-threads: 100
core-threads: 1
redis:
hosts: redis://redis-qa.apps.desplakur3.desintra.banesco.com:32229
password: redis
# 4 minutes 60*4*1000 (MS)
timeout: 240000
api:
source-id: UCSS
rest-client:
update-card-status:
endpoint: '{"url":"http://localhost:8082/card/status/update","timeout":{"connect":20000,"response":20000},"config":{}}'
msgRqHdr: '{"networkTrnInfo":[{"bankId":"01","transactionCode":"8741"}],"applicantData":{"application":"APIMGMT"},"vbProtocol":{"vbProtocolInd":"true","transactionInd":"false"},"operatorCode":"BAN1738A02","sourceChannelCode":"INT"}'
redis:
#expiration with Zero, not apply Redis
get-evaluate-customer-product: '{"prefix":"%s%d%s","expiration":0}'
soap:
domain:
current: osbp2p

View File

@ -0,0 +1,33 @@
quarkus:
http:
non-application-root-path: actuator
log:
level: INFO
console:
enable: true
profile: dev
debug:
print-startup-times: true
reflection: false
native:
file-encoding: UTF-8
container-build: true
builder-image: quay.io/quarkus/ubi-quarkus-mandrel-builder-image:23.0.5.0-Final-java17
container-runtime: docker
additional-build-args:
- -H:InitialCollectionPolicy=com.oracle.svm.core.genscavenge.CollectionPolicy\$BySpaceAndTime
- -H:ReflectionConfigurationFiles=reflect-config.json
native-image-xmx: 6G
resources:
excludes: resources/*.yaml
# Enable OpenAPI
smallrye-openapi:
path: /openapi
enable: 'true'
swagger-ui:
path: /swagger-ui
always-include: 'true'
application:
name: bus-update-card-status
version: 1.0.0
#remove to compile

View File

@ -0,0 +1,98 @@
[
{
"backendCode": "200",
"httpCode": 200,
"statusCode": "200",
"description": "Operacion exitosa"
},
{
"backendCode": "503",
"httpCode": 503,
"statusCode": "503",
"description": "Uso interno"
},
{
"backendCode": "422",
"httpCode": 422,
"statusCode": "422",
"description": "Uso interno"
},
{
"backendCode": "SERVICE_UNAVAILABLE",
"httpCode": 500,
"statusCode": "500",
"description": "Uso interno"
},
{
"backendCode": "100",
"httpCode": 503,
"statusCode": "503",
"description": "VDR13 - OSB Disponible"
},
{
"backendCode": "OSB-382505",
"httpCode": 503,
"statusCode": "503",
"description": "VDR13 - OSB Disponible"
},
{
"backendCode": "OSB-380002",
"httpCode": 503,
"statusCode": "503",
"description": "VDR13 - OSB Disponible"
},
{
"backendCode": "ERROR",
"httpCode": 400,
"statusCode": "400",
"description": "Uso interno"
},
{
"backendCode": "400",
"httpCode": 400,
"statusCode": "400",
"description": "Uso interno"
},
{
"backendCode": "401",
"httpCode": 401,
"statusCode": "401",
"description": "Uso interno"
},
{
"backendCode": "403",
"httpCode": 403,
"statusCode": "403",
"description": "Uso interno"
},
{
"backendCode": "404",
"httpCode": 404,
"statusCode": "404",
"description": "Uso interno"
},
{
"backendCode": "default",
"httpCode": 409,
"statusCode": "409",
"description": "Conflicto"
},
{
"backendCode": "424",
"httpCode": 424,
"statusCode": "424",
"description": "Error de dependencia"
},
{
"backendCode": "VDE01",
"httpCode": 400,
"statusCode": "VDE01",
"description": "VDE01 - Error en dato de entrada obligatorio: %s"
},
{
"backendCode": "VDE02",
"httpCode": 400,
"statusCode": "VDE02",
"description": "VDE02 - Error en valor permitido para campo: %s"
}
]

View File

@ -0,0 +1,21 @@
{
"customerReference": {
"customerIdType": "V",
"customerId": "500634269"
},
"device": {
"deviceType": "Mobile",
"deviceDescription": "Xiaomi Note 11 PRO",
"deviceIp": "127.0.0.1",
"deviceSessionReference": "12345678901304"
},
"cardReference": {
"cardType": "DebitCard",
"cardNumber": "6012-8862-0791-7605",
"cardStatusCode": "52",
"cardStatusAction": "CV",
"cardStatusReason": "Bloqueo Temporal"
}
}

View File

@ -0,0 +1,21 @@
{
"customerReference": {
"customerIdType": "J",
"customerId": "500634269"
},
"device": {
"deviceType": "Mobile",
"deviceDescription": "Xiaomi Note 11 PRO",
"deviceIp": "127.0.0.1",
"deviceSessionReference": "12345678901304"
},
"cardReference": {
"cardType": "DebitCard",
"cardNumber": "6012-8862-0791-7605",
"cardStatusCode": "52",
"cardStatusAction": "CV",
"cardStatusReason": "Bloqueo Temporal"
}
}

View File

@ -0,0 +1,56 @@
[
{
"name": "com.banesco.commons.config.AppConf",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
},
{
"name": "com.banesco.common.domain.model.BackResponse",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
},
{
"name": "com.banesco.common.domain.dto.bian.device.Device",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
},
{
"name": "com.banesco.common.domain.model.RedisParam",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
},
{
"name": "com.banesco.common.domain.model.ApiConfig",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
},
{
"name": "com.banesco.common.domain.model.ApiTimeout",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
},
{
"name": "com.banesco.common.domain.dto.bian.response.StatusResponse",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
},
{
"name": "com.banesco.common.domain.dto.bian.response.MetadataResponse",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
},
{
"name": "com.banesco.common.domain.dto.bian.customer.CustomerReference",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
}
]

View File

@ -0,0 +1,27 @@
package com.banesco.tests;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestWatcher;
import java.util.Optional;
public class BanTestWatcher implements TestWatcher {
private static final String ANSI_GREEN = "\u001B[32m";
private static final String ANSI_RED = "\u001B[31m";
private static final String ANSI_RESET = "\u001B[0m";
@Override
public void testSuccessful(ExtensionContext context) {
System.out.println(ANSI_GREEN + "Test successful: " + context.getDisplayName() + ANSI_RESET);
}
@Override
public void testFailed(ExtensionContext context, Throwable cause) {
System.out.println(ANSI_RED + "Test failed: " + context.getDisplayName() + " - " + cause.getMessage() + ANSI_RESET);
}
@Override
public void testDisabled(ExtensionContext context, Optional<String> reason) {
System.out.println("Test disabled: " + context.getDisplayName() + " - " + reason.orElse("No reason given"));
}
}

38
commons-bian/.gitignore vendored Normal file
View File

@ -0,0 +1,38 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

3
commons-bian/.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

7
commons-bian/.idea/encodings.xml generated Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

14
commons-bian/.idea/misc.xml generated Normal file
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="temurin-17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

4
commons-bian/.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings" defaultProject="true" />
</project>

10
commons-bian/CHANGELOG.md Normal file
View File

@ -0,0 +1,10 @@
# Changelog
Todos los cambios notables en este proyecto se documentarán en este archivo.
El formato se basa en [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
y este proyecto se adhiere a [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [UNRELEASE]
- Base inicial commons nativo (Java)

21
commons-bian/LICENCE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Banesco Banco Universal, C.A.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

10
commons-bian/README.md Normal file
View File

@ -0,0 +1,10 @@
![Logo](https://upload.wikimedia.org/wikipedia/commons/thumb/7/74/Banesco_logo.svg/2560px-Banesco_logo.svg.png)
# Commons
Este proyecto utiliza Java nativo como librería commons
- Banesco Banco Universal &copy; Todos los Derechos Reservados.

66
commons-bian/pom.xml Normal file
View File

@ -0,0 +1,66 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.banesco</groupId>
<artifactId>commons-bian</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>commons-bian</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.4</version>
<scope>compile</scope>
</dependency>
<!--dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.13.0</version>
</dependency-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>17</source>
<target>17</target>
<release>17</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.3.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.1</version>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,8 @@
package com.banesco;
public class CommonsBian {
public static void main(String[] args) {
System.out.println("Commons BIAN...");
}
}

View File

@ -0,0 +1,33 @@
package com.banesco.common.application.exception;
public class BanBackendException extends RuntimeException {
protected String backendCode;
protected String backendDesc;
protected String target;
public BanBackendException(String backendCode, String backendDesc) {
super(backendDesc);
this.backendCode = backendCode;
this.backendDesc = backendDesc;
}
public BanBackendException(String backendCode, String backendDesc, String target) {
super(backendDesc.formatted(target) + ", Target:" + target);
this.backendCode = backendCode;
this.backendDesc = backendDesc;
this.target = target;
}
public String getBackendCode() {
return backendCode;
}
public String getBackendDesc() {
return backendDesc;
}
public String getTarget() {
return target;
}
}

View File

@ -0,0 +1,32 @@
package com.banesco.common.application.exception;
import com.banesco.common.domain.interfaces.BaseStatusCodesEnum;
public class BanRuntimeException extends RuntimeException {
protected BaseStatusCodesEnum statusCode;
protected String target;
public BanRuntimeException() {
super("Internal Error");
}
public BanRuntimeException(BaseStatusCodesEnum statusCode, String target) {
super(statusCode.getStatusDesc().formatted(target) + ", Target:" + target);
this.statusCode = statusCode;
this.target = target;
}
public BanRuntimeException(BaseStatusCodesEnum statusCode) {
super(statusCode.getStatusDesc());
this.statusCode = statusCode;
}
public BaseStatusCodesEnum getStatusCode() {
return statusCode;
}
public String getTarget() {
return target;
}
}

View File

@ -0,0 +1,51 @@
package com.banesco.common.application.helper;
import com.banesco.common.domain.dto.bian.device.Device;
import com.banesco.common.domain.dto.bian.device.DeviceTypeValues;
import com.banesco.common.domain.dto.bian.device.StringHelper;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class DeviceHelper {
private static final Logger logger = Logger.getLogger(DeviceHelper.class.getName());
public static DeviceTypeValues getDeviceTypeValue(
Device device
) {
var deviceTypeValue = DeviceTypeValues.Unknown;
if (!Objects.isNull(device) && !StringHelper.isEmpty(device.getDeviceType())) {
try {
deviceTypeValue = DeviceTypeValues.valueOf(device.getDeviceType());
} catch (Exception e) {
logger.log(Level.WARNING, "Error Mapping Device Type: %s -> %s".formatted(device.getDeviceType(), e.getMessage()));
}
}
return deviceTypeValue;
}
public static boolean isValidDeviceType(String type) {
for (DeviceTypeValues deviceType : DeviceTypeValues.values()) {
if (deviceType.name().equals(type)) {
return true;
}
}
return false;
}
public static String getDeviceTypes() {
return Stream.of(DeviceTypeValues.values()).map(Enum::name).collect(
Collectors.joining(", ")
);
}
}

View File

@ -0,0 +1,16 @@
package com.banesco.common.application.helper;
import com.banesco.common.domain.dto.bian.device.DeviceTypeValues;
import com.banesco.common.domain.dto.bian.paymentCard.CardTypeValues;
public class PaymentCardHelper {
public static boolean isValidCardType(String type) {
for (CardTypeValues cardTypeValue : CardTypeValues.values()) {
if (cardTypeValue.name().equals(type)) {
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,36 @@
package com.banesco.common.domain.dto.bian.customer;
public class CustomerReference {
String customerIdType;
String customerId;
public CustomerReference() {
}
public CustomerReference(String customerIdType, String customerId) {
this.customerIdType = customerIdType;
this.customerId = customerId;
}
public String getCustomerIdType() {
return customerIdType;
}
public void setCustomerIdType(String customerIdType) {
this.customerIdType = customerIdType;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
@Override
public String toString() {
return "{\"customerIdType\":\"%s\",\"customerId\":\"%s\"}"
.formatted(customerIdType, customerId);
}
}

View File

@ -0,0 +1,21 @@
package com.banesco.common.domain.dto.bian.device;
/**
* Clase utilitaria para operaciones relacionadas con cuentas bancarias.
* Proporciona métodos para manipular y formatear información de cuentas.
*/
public class AccountHelper {
/**
* Enmascara un número de cuenta, mostrando solo los primeros 4
* y últimos 4 Los dígitos intermedios son reemplazados por asteriscos para proteger la
* información sensible del cliente.
*
* @param clearAccountId El número de cuenta completo sin enmascarar
* @return El número de cuenta enmascarado en formato "XXXX************YYYY"
*/
public static String getMaskedAccountId(String clearAccountId) {
return clearAccountId.substring(0, 4) + "************" + clearAccountId.substring(clearAccountId.length() - 4);
}
}

View File

@ -0,0 +1,163 @@
package com.banesco.common.domain.dto.bian.device;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Clase utilitaria para operaciones relacionadas con fechas y horas.
* Proporciona métodos para validar, comparar y calcular períodos entre fechas.
*/
public class DateHelper {
private final Logger logger = Logger.getLogger(DateHelper.class.getName());
private final ZoneId currentZone = ZoneId.of("America/Caracas");
private final DateTimeFormatter DATE_YYYY_MM_DD = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private final DateTimeFormatter TIME_HH_MM_SS = DateTimeFormatter.ofPattern("HH:mm:ss");
private static class SingletonHelper {
private static final DateHelper INSTANCE = new DateHelper();
}
/**
* Constructo private to no allow other Instances
*/
private DateHelper() {
// not public instance
}
/**
* Get Instance Singleton
*
* @return
*/
public static DateHelper getInstance() {
return SingletonHelper.INSTANCE;
}
/**
* Permite obtener la Fecha Hora Actual
*
* @return
*/
public LocalDateTime getCurrentDateTime() {
return LocalDateTime.now(currentZone);
}
/**
* Permite Obtener la Hora para una FechaHora, en caso de ser null se obtiene la hora actual
*
* @param now Feha Hora Local
* @return
*/
public String getTime(LocalDateTime now) {
if (now == null) {
now = LocalDateTime.now(currentZone);
}
return now.format(TIME_HH_MM_SS);
}
/**
* Permite Obtener la Fecha para una FechaHora, en caso de ser null se obtiene la fecha actual
*
* @param now Feha Hora Local
* @return
*/
public String getDate(LocalDateTime now) {
if (now == null) {
now = LocalDateTime.now(currentZone);
}
return now.format(DATE_YYYY_MM_DD);
}
/**
* Check is Current Hour is in Hour Range passed by parameters
* if Parameters are equal then return false
*
* @param rangeHourBegin Cadena de la hora de inicio del Rango
* @param rangeHourFinish Candena de la hora de fin del Rango
* @param hourStrToCheck Hora en cadena para evaluar si se encuentra entre el rango de parametros
* @return boolean
*/
public boolean isHourInRange(String rangeHourBegin, String rangeHourFinish, String hourStrToCheck) {
return isHourInRange(Integer.parseInt(rangeHourBegin.replace(":", "")),
Integer.parseInt(rangeHourFinish.replace(":", "")),
hourStrToCheck
);
}
/**
* Check is Current Hour is in Hour Range passed by parameters
* if Parameters are equal then return false
*
* @param rangeHourBegin Numero entero de la hora de inicio del Rango
* @param rangeHourFinish Numero entero de la hora de fin del Rango
* @param hourStrToCheck Hora en cadena para evaluar si se encuentra entre el rango de parametros
* @return boolean
*/
public boolean isHourInRange(int rangeHourBegin, int rangeHourFinish, String hourStrToCheck) {
boolean mustValidateService = false;
if (rangeHourBegin == rangeHourFinish) {
return mustValidateService;
}
int currentHour = Integer.parseInt(hourStrToCheck.replace(":", ""));
if (rangeHourBegin > rangeHourFinish) { // hour end is less than hour start, => then validate next day
if (currentHour <= rangeHourFinish || currentHour >= rangeHourBegin) {
mustValidateService = true;
}
} else if (currentHour >= rangeHourBegin && currentHour <= rangeHourFinish) { // Hour the same day
mustValidateService = true;
}
logger.log(Level.INFO, "La hora (%s => %d) %sesta entre %d y %d ".formatted(
hourStrToCheck,
currentHour,
(mustValidateService ? "" : "NO "),
rangeHourBegin,
rangeHourFinish));
return mustValidateService;
}
/**
* Calcula el número de días entre dos fechas.
*
* @param startDate Fecha de inicio en formato ISO (yyyy-MM-dd)
* @param endDate Fecha de fin en formato ISO (yyyy-MM-dd)
* @return El número de días entre las fechas o -1 si ocurre un error al
* procesar las fechas
*/
public long daysBetweenTwoDates(String startDate, String endDate) {
try {
return ChronoUnit.DAYS.between(LocalDate.parse(startDate), LocalDate.parse(endDate));
} catch (DateTimeException dte) {
return -1L;
}
}
/**
* Verifica si la fecha de inicio es anterior o igual a la fecha de fin.
*
* @param startDate Fecha de inicio en formato ISO (yyyy-MM-dd)
* @param endDate Fecha de fin en formato ISO (yyyy-MM-dd)
* @return true si startDate es anterior o igual a endDate, false en caso
* contrario
*/
public boolean isStartDateBeforeEndDate(String startDate, String endDate) {
return LocalDate.parse(startDate).isBefore(LocalDate.parse(endDate))
|| LocalDate.parse(startDate).isEqual(LocalDate.parse(endDate));
}
}

View File

@ -0,0 +1,59 @@
package com.banesco.common.domain.dto.bian.device;
public class Device {
String deviceType;
String deviceDescription;
String deviceIp;
String deviceSessionReference;
public Device() {
}
public Device(String deviceType, String deviceDescription, String deviceIp, String deviceSessionReference) {
this.deviceType = deviceType;
this.deviceDescription = deviceDescription;
this.deviceIp = deviceIp;
this.deviceSessionReference = deviceSessionReference;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public String getDeviceDescription() {
return deviceDescription;
}
public void setDeviceDescription(String deviceDescription) {
this.deviceDescription = deviceDescription;
}
public String getDeviceIp() {
return deviceIp;
}
public void setDeviceIp(String deviceIp) {
this.deviceIp = deviceIp;
}
public String getDeviceSessionReference() {
return deviceSessionReference;
}
public void setDeviceSessionReference(String deviceSessionReference) {
this.deviceSessionReference = deviceSessionReference;
}
public String toString() {
return "{\"deviceType\":\"%s\",\"deviceDescription\":\"%s\",\"deviceIp\":\"%s\",\"deviceSessionReference\":\"%s\"}"
.formatted(deviceType, deviceDescription, deviceIp, deviceSessionReference);
}
}

View File

@ -0,0 +1,20 @@
package com.banesco.common.domain.dto.bian.device;
public enum DeviceTypeValues {
Mobile,
Tablet,
PersonalComputer,
SecureCardReader,
NonSecureCardReader,
OtherNational,
OtherPrivate,
Wearable,
Vehicle,
Embedded,
KeyFob,
Jewellery,
Sticker,
GamingDevice,
Watch,
Unknown
}

View File

@ -0,0 +1,93 @@
package com.banesco.common.domain.dto.bian.device;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JsonHelper {
private static final Logger logger = Logger.getLogger(JsonHelper.class.getName());
public static final ObjectMapper MAPPER = new ObjectMapper();
static {
MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
/**
* Convert Object to jsonString
*
* @param object El objeto a convertir en JSON.
* @return La cadena JSON resultante o null si ocurre un error.
*/
public static String getJsonFromObject(Object object) {
if (object == null) {
return "null";
}
try {
return MAPPER.writeValueAsString(object);
} catch (JsonProcessingException e) {
logger.log(Level.SEVERE, "Error parsing objeto a JSON: {0}", e.getMessage());
return null;
}
}
/**
* Convierte una cadena JSON en un objeto Java de la clase especificada.
*
* @param json La cadena JSON a convertir.
* @param className La clase del objeto Java resultante.
* @param <T> El tipo del objeto resultante.
* @return El objeto Java resultante, o null si ocurre un error o la cadena
* JSON está vacía.
*/
public static <T> T getObjectFromJson(String json, Class<T> className) {
if (json == null || json.isEmpty()) {
return null;
}
try {
return MAPPER.readValue(json, className);
} catch (JsonProcessingException | IllegalArgumentException e) {
logger.log(Level.WARNING, "Error parsing JSON a objeto: {0}", e.getMessage());
return null;
}
}
public static <T> List<T> getListFromJson(String json, Class<T> className) {
if (json == null || json.isEmpty()) {
return new ArrayList<>();
}
try {
return MAPPER.readValue(json,
MAPPER.getTypeFactory().constructCollectionType(List.class, className)
);
} catch (JsonProcessingException | IllegalArgumentException e) {
logger.log(Level.WARNING, "Error parsing JSON a List Object: {0}", e.getMessage());
}
return new ArrayList<>();
}
public static <T> List<T> getListFromInputStream(InputStream inputStream, Class<T> className) throws IOException {
if (inputStream == null) {
return new ArrayList<>();
}
try {
return MAPPER.readValue(inputStream,
MAPPER.getTypeFactory().constructCollectionType(List.class, className)
);
} catch (JsonProcessingException | IllegalArgumentException e) {
logger.log(Level.WARNING, "Error parsing JSON a List Object: {0}", e.getMessage());
}
return new ArrayList<>();
}
}

View File

@ -0,0 +1,118 @@
package com.banesco.common.domain.dto.bian.device;
/**
* Clase utilitaria para la generación de mensajes de registro (logging).
* Facilita la creación de cadenas formateadas para registrar información de
* solicitudes y respuestas, tanto públicas como privadas, así como mensajes de
* error. Utiliza un formato estandarizado para mejorar la legibilidad y
* facilitar el análisis de los registros del sistema.
*/
public class LoggerHelper {
/**
* Construye una cadena de información para una solicitud pública.
*
* @param requestId El ID de la solicitud.
* @param request El objeto de solicitud.
* @param <T> El tipo del objeto de solicitud.
* @return Una cadena de información formateada.
*/
public static <T> String buildInfoRequest(String requestId, T request) {
return String.format("[PUB RQ: %s] [%s]", requestId, JsonHelper.getJsonFromObject(request));
}
/**
* Construye una cadena de información para una solicitud pública.
*
* @param requestId El ID de la solicitud.
* @param request El request en cadena de la solicitud.
* @return Una cadena de información formateada.
*/
public static <T> String buildInfoRequest(String requestId, String request) {
return String.format("[PUB RQ: %s] [%s]", requestId, request);
}
/**
* Construye una cadena de información para una respuesta pública.
*
* @param requestId El ID de la solicitud.
* @param response El objeto de respuesta.
* @param <T> El tipo del objeto de respuesta.
* @return Una cadena de información formateada.
*/
public static <T> String buildInfoResponse(String requestId, T response) {
return String.format("[PUB RS: %s] [%s]", requestId, JsonHelper.getJsonFromObject(response));
}
/**
* Construye una cadena de información para una respuesta pública.
*
* @param requestId El ID de la solicitud.
* @param response El objeto en cadena de respuesta.
* @return Una cadena de información formateada.
*/
public static String buildInfoResponse(String requestId, String response) {
return String.format("[PUB RS: %s] [%s]", requestId, response);
}
/**
* Construye una cadena de información para una solicitud privada.
*
* @param requestId El ID de la solicitud.
* @param name El nombre de la solicitud privada.
* @param request El objeto de solicitud.
* @param <T> El tipo del objeto de solicitud.
* @return Una cadena de información formateada.
*/
public static <T> String buildInfoPrivateRequest(String requestId, String name, T request) {
return String.format("[PRV RQ %s: %s] [%s]", name, requestId, JsonHelper.getJsonFromObject(request));
}
/**
* Construye una cadena de información para una solicitud privada.
*
* @param requestId El ID de la solicitud.
* @param name El nombre de la solicitud privada.
* @param request El objeto en cadena de la solicitud.
* @return Una cadena de información formateada.
*/
public static String buildInfoPrivateRequest(String requestId, String name, String request) {
return String.format("[PRV RQ %s: %s] [%s]", name, requestId, request);
}
/**
* Construye una cadena de información para una respuesta privada.
*
* @param requestId El ID de la solicitud.
* @param name El nombre de la respuesta privada.
* @param response El objeto de respuesta.
* @param <T> El tipo del objeto de respuesta.
* @return Una cadena de información formateada.
*/
public static <T> String buildInfoPrivateResponse(String requestId, String name, T response) {
return String.format("[PRV RS %s: %s] [%s]", name, requestId, JsonHelper.getJsonFromObject(response));
}
/**
* Construye una cadena de información para una respuesta privada.
*
* @param requestId El ID de la solicitud.
* @param name El nombre de la respuesta privada.
* @param response El objeto en cadena de la respuesta.
* @return Una cadena de información formateada.
*/
public static String buildInfoPrivateResponse(String requestId, String name, String response) {
return String.format("[PRV RS %s: %s] [%s]", name, requestId, response);
}
/**
* Construye una cadena de error.
*
* @param requestId El ID de la solicitud asociada al error.
* @param out El mensaje de error.
* @return Una cadena de error formateada.
*/
public static String buildError(String requestId, String out) {
return String.format("[ERROR %s] [%s]", requestId, out);
}
}

View File

@ -0,0 +1,81 @@
package com.banesco.common.domain.dto.bian.device;
import java.util.concurrent.ThreadLocalRandom;
/**
* Clase utilitaria para operaciones relacionadas con solicitudes HTTP y
* generación de identificadores. Proporciona métodos para generar IDs únicos,
* obtener información del cliente y gestionar información del dispositivo.
*/
public class RequestHelper {
private final String ALPHANUMERIC_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private final int baseCharacterLen = ALPHANUMERIC_CHARACTERS.length();
/**
* Permite tener una cadena aleatoria de caracteres numericos
*
* @param len longitud de la cadena numerica a retornar
* @return
*/
public String randomNumeric(int len) {
char[] chars = new char[len];
for (int i = 0; i < len; i++) {
chars[i] = (char) ThreadLocalRandom.current().nextInt(48, 58); // ascii index number
}
return new String(chars);
}
/**
* Permite tener una cadena aleatoria de caracteres alfa-numericos
*
* @param len longitud de la cadena alfa-numerica a retornar
* @return
*/
public String randomAlphanumeric(int len) {
char[] chars = new char[len];
for (int i = 0; i < len; i++) {
chars[i] = ALPHANUMERIC_CHARACTERS.charAt(ThreadLocalRandom.current().nextInt(baseCharacterLen));
}
return new String(chars);
}
/**
* Retorna Identificador de la Instancia del Request, usando como prefijo un valor predefinido
* ejemplos: P2P, REM,
* Facilita identificar el origen de los Requests
* Deberia obtenerse una vez al inicia el Request
*
* @param apiSourceId
* @return
*/
public String getInstanceId(String apiSourceId) {
return (apiSourceId == null ? "INST" : apiSourceId).concat(randomAlphanumeric(10));
}
/**
* Retorna un Identificador del Request, se sugiere usar el getInstanceId creada como prefijo.
* Usar uno para Cada Request que implique afectacion financiera
*
* @param instanceId
* @return
*/
public String getRequestId(String instanceId) {
return instanceId.concat("REQ").concat(randomAlphanumeric(20));
}
/**
* Permite Obtener un valor Numerico de Identificador de Transaccion
*
* @param len
* @return
*/
public String getTransactionId(int len) {
return randomNumeric(len);
}
}

View File

@ -0,0 +1,106 @@
package com.banesco.common.domain.dto.bian.device;
/**
* Clase utilitaria para operaciones con cadenas de texto (strings). Proporciona
* métodos para validar, manipular y formatear cadenas de texto. Incluye
* funcionalidades como verificación de tipos numéricos, validación de cadenas
* no vacías y funciones de formato como relleno de caracteres.
*/
public class StringHelper {
/**
* Verifica si una cadena de texto representa un número entero.
*
* @param value La cadena de texto a verificar.
* @return true si la cadena es un número entero válido, false en caso
* contrario.
* @throws NumberFormatException Si el string no tiene el formato adeacuado
*/
public static boolean isNumeric(String value) {
if (value == null || value.isEmpty()) {
return false;
}
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
/**
* Verifica si una cadena de texto es nula o está vacía después de
* eliminar espacios en blanco.
*
* @param value La cadena de texto a verificar.
* @return true si la cadena está vacía, false en caso contrario.
*/
public static boolean isEmpty(String value) {
return value == null || value.trim().isEmpty();
}
/**
* Rellena una cadena de texto con un carácter específico a la izquierda
* hasta alcanzar la longitud deseada.
*
* @param inputStr La cadena de texto a rellenar.
* @param strLenOut La longitud deseada de la cadena resultante.
* @param padChar El carácter de relleno.
* @return La cadena rellenada con el carácter especificado a la izquierda.
*/
public static String leftPad(String inputStr, int strLenOut, char padChar) {
if (inputStr == null) {
inputStr = ""; // Handle null input
}
int padLength = strLenOut - inputStr.length();
if (padLength <= 0) {
return inputStr; // No padding needed
}
char[] paddedString = new char[padLength];
for (int i = 0; i < padLength; i++) {
paddedString[i] = padChar;
}
return new String(paddedString).concat(inputStr);
}
/**
* Permite convertir nombre de propiedad separada con (,-) to CamelCase
*
* @param inputStr Cadena de texto a convertir
* @param firstUpper Flag que indica si la primera letra es Mayuscula
* @return
*/
public static String convertToCamelCase(String inputStr, boolean firstUpper) {
StringBuilder result = new StringBuilder();
boolean capitalizeNext = firstUpper;
for (char ch : inputStr.toCharArray()) {
if (ch == '.' || ch == '-') {
capitalizeNext = true; // Next character should be capitalized
} else {
if (capitalizeNext) {
result.append(Character.toUpperCase(ch)); // Capitalize current character
capitalizeNext = false; // Reset flag
} else {
result.append(Character.toLowerCase(ch)); // Append in lowercase
}
}
}
return result.toString();
}
/**
* @param inputStr Cadena de texto a convertir en UpperCamelCase
* @return
*/
public static String convertToUpperCamelCase(String inputStr) {
return convertToCamelCase(inputStr, true);
}
}

View File

@ -0,0 +1,6 @@
package com.banesco.common.domain.dto.bian.paymentCard;
public enum CardTypeValues {
DebitCard,
CreditCard
}

View File

@ -0,0 +1,20 @@
package com.banesco.common.domain.dto.bian.response;
public class BaseResponse {
protected StatusResponse statusResponse;
public BaseResponse() {
}
public BaseResponse(StatusResponse statusResponse) {
this.statusResponse = statusResponse;
}
public StatusResponse getStatusResponse() {
return statusResponse;
}
public void setStatusResponse(StatusResponse statusResponse) {
this.statusResponse = statusResponse;
}
}

View File

@ -0,0 +1,10 @@
package com.banesco.common.domain.dto.bian.response;
public record MetadataResponse(String timestamp, String operationId) {
@Override
public String toString() {
return "{\"timestamp\":\"%s\",\"operationId\":\"%s\"}".formatted(timestamp, operationId);
}
}

View File

@ -0,0 +1,10 @@
package com.banesco.common.domain.dto.bian.response;
public record StatusResponse(String status,String statusCode, String message, String traceId) {
@Override
public String toString() {
return "{\"status\":\"%s\",\"statusCode\":\"%s\",\"message\":\"%s\",\"traceId\":\"%s\"}".formatted(status, statusCode, message, traceId);
}
}

View File

@ -0,0 +1,6 @@
package com.banesco.common.domain.interfaces;
public interface BaseStatusCodesEnum {
String getStatusCode();
String getStatusDesc();
}

View File

@ -0,0 +1,54 @@
package com.banesco.common.domain.model;
import java.util.Map;
/**
* Clase de configuración para APIs. Almacena la información necesaria para
* conectarse a un servicio API externo, incluyendo URL, configuración de
* timeout y parámetros adicionales. Diseñada para ser utilizada como objeto de
* configuración en clientes de API y servicios de integración.
*/
public class ApiConfig {
String url;
ApiTimeout timeout;
Map<String, String> config;
public ApiConfig(){
}
public ApiConfig(String url,
ApiTimeout timeout,
Map<String, String> config) {
this.url = url;
this.timeout = timeout;
this.config = config;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public ApiTimeout getTimeout() {
return timeout;
}
public void setTimeout(ApiTimeout timeout) {
this.timeout = timeout;
}
public Map<String, String> getConfig() {
return config;
}
public void setConfig(Map<String, String> config) {
this.config = config;
}
}

View File

@ -0,0 +1,37 @@
package com.banesco.common.domain.model;
/**
* Clase interna que representa la configuración de tiempos de espera
* (timeout) para conexiones a APIs. Define los tiempos máximos de espera
* para establecer la conexión y para recibir una respuesta, especificados
* en milisegundos.
*/
public class ApiTimeout{
private int connect;
private int response;
public ApiTimeout() {
}
public ApiTimeout(int connect, int response) {
this.connect = connect;
this.response = response;
}
public int getConnect() {
return connect;
}
public void setConnect(int connect) {
this.connect = connect;
}
public int getResponse() {
return response;
}
public void setResponse(int response) {
this.response = response;
}
}

View File

@ -0,0 +1,63 @@
package com.banesco.common.domain.model;
/**
* Clase para obtener los codigos y mensajes de salida
*/
public class BackResponse {
private String backendCode;
private int httpCode;
private String statusCode;
private String description;
public BackResponse() {
}
public BackResponse(String backendCode,
int httpCode,
String statusCode,
String description) {
this.backendCode = backendCode;
this.httpCode = httpCode;
this.statusCode = statusCode;
this.description = backendCode;
}
public String getBackendCode() {
return backendCode;
}
public int getHttpCode() {
return httpCode;
}
public String getStatusCode() {
return statusCode;
}
public String getDescription() {
return description;
}
public void setBackendCode(String backendCode) {
this.backendCode = backendCode;
}
public void setHttpCode(int httpCode) {
this.httpCode = httpCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "{\"backendCode\":\"%s\",\"httpCode\":%d,\"statusCode\":\"%s\",\"description\":\"%s\"}"
.formatted(backendCode, httpCode, statusCode, description);
}
}

View File

@ -0,0 +1,31 @@
package com.banesco.common.domain.model;
public class RedisParam {
private String prefix;
private long expiration;
public RedisParam() {
}
public RedisParam(String prefix, long expiration) {
this.prefix = prefix;
this.expiration = expiration;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public long getExpiration() {
return expiration;
}
public void setExpiration(long expiration) {
this.expiration = expiration;
}
}

View File

@ -0,0 +1,111 @@
package com.banesco.common.infraestructure.repository;
import com.banesco.common.domain.model.BackResponse;
import com.banesco.common.domain.dto.bian.device.JsonHelper;
import com.banesco.common.domain.dto.bian.device.StringHelper;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MessageRepository {
private static final Logger logger = Logger.getLogger(MessageRepository.class.getName());
/**
* Respuesta de error por defecto que se utiliza cuando no se encuentra un
* error específico.
*/
/**
* Mapa que almacena múltiples mapas de códigos de error, donde la clave
* principal es el nombre del archivo de mensajes.
*/
public final Map<String, Map<String, BackResponse>> mapErrorsMultiple = new HashMap<>();
/**
* Carga los mensajes de error desde un InputStream y los almacena en un
* mapa.
*
* @param inputStream El InputStream que contiene los datos JSON de los
* mensajes de error.
* @param messageFileKey La clave del archivo de mensajes, utilizada para
* almacenar el mapa en mapErrorsMultiple.
* @return Un mapa que contiene los códigos de error como claves y los
* objetos BackResponse como valores.
* @throws IOException Si ocurre un error de entrada/salida al leer el
* InputStream.
*/
private Map<String, BackResponse> loadFile(InputStream inputStream, String messageFileKey) throws IOException {
Map<String, BackResponse> mapStatusCodes = new HashMap<>();
Arrays.stream(JsonHelper.MAPPER.readValue(inputStream, BackResponse[].class)).forEach(o -> {
mapStatusCodes.put(o.getBackendCode(), o);
});
mapErrorsMultiple.put(messageFileKey, mapStatusCodes);
return mapStatusCodes;
}
/**
* Carga los mensajes de error desde una cadena JSON y los almacena en un
* mapa.
*
* @param messageFileKey La clave del archivo de mensajes, utilizada para
* almacenar el mapa en mapErrorsMultiple.
* @param jsonString La cadena JSON que contiene los datos de los mensajes
* de error.
* @throws IOException Si ocurre un error al procesar la cadena JSON.
*/
public void loadMessagesFromString(String messageFileKey, String jsonString) throws IOException {
Map<String, BackResponse> mapStatusCodes = new HashMap<>();
Arrays.stream(JsonHelper.MAPPER.readValue(jsonString, BackResponse[].class)).forEach(o -> {
mapStatusCodes.put(o.getBackendCode(), o);
});
mapErrorsMultiple.put(messageFileKey, mapStatusCodes);
}
/**
* Obtiene el mapa de códigos de error para un archivo de respuesta
* específico.
*
* @param responseFile El nombre del archivo de respuesta para el cual se
* desea obtener el mapa de errores.
* @return Un mapa que contiene los códigos de error como claves y los
* objetos BackResponse como valores, o null si no se encuentra el mapa.
*/
public Map<String, BackResponse> getErrorMap(String responseFile, boolean insideProperties) {
Map<String, BackResponse> errorMap = mapErrorsMultiple.get(responseFile);
if (insideProperties || (errorMap != null && !errorMap.isEmpty())) {
return errorMap;
}
String fileName = (StringHelper.isNumeric(responseFile) ? "vb".concat(responseFile) : responseFile).concat(".json");
try {
try {
// Intenta cargar el archivo desde el directorio /config/.
return loadFile(new FileInputStream("/config/".concat(fileName)), responseFile);
} catch (IOException e) {
// Si no se encuentra el archivo en /config/, intenta cargarlo desde el classpath.
logger.log(Level.WARNING, "Path /config/" + fileName + " not found. Loading local from errors-mapping/" + fileName);
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("errors-mapping/" + fileName);
if (inputStream == null) {
// Si no se encuentra el archivo en el classpath, registra un error y devuelve null.
logger.log(Level.SEVERE, "Resource errors-mapping/" + fileName + " not found.");
return null;
}
return loadFile(inputStream, responseFile);
}
} catch (IOException e) {
// Si ocurre un error al cargar el archivo desde cualquier ubicación, registra un error y devuelve null.
logger.log(Level.SEVERE, "Error getting Service Messages to /config/".concat(fileName) + ": " + e.getMessage());
return null;
}
}
}

View File

@ -0,0 +1,90 @@
package com.banesco.common.infraestructure.repository;
import com.banesco.common.domain.model.ApiConfig;
import com.banesco.common.domain.dto.bian.device.JsonHelper;
import com.banesco.common.domain.dto.bian.device.LoggerHelper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RegisterSecurityRepository {
private static final Logger logger = Logger.getLogger(RegisterSecurityRepository.class.getName());
private final LoggerHelper loggerHelper;
private final ApiConfig registerSecurityAPI;
private final ExecutorService executor = Executors.newCachedThreadPool();
public RegisterSecurityRepository(LoggerHelper loggerHelper, ApiConfig registerSecurityAPI) {
this.loggerHelper = loggerHelper;
this.registerSecurityAPI = registerSecurityAPI;
}
public <T> void writeTrice(String requestId, T registerSecurityRq) {
logger.info(loggerHelper.buildInfoPrivateRequest(requestId, "RegisterSecurityRq", registerSecurityRq));
CompletableFuture.runAsync(() -> {
try {
URL url = new URL(registerSecurityAPI.getUrl());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(registerSecurityAPI.getTimeout().getConnect());
connection.setReadTimeout(registerSecurityAPI.getTimeout().getResponse());
connection.setDoOutput(true);
String jsonInputString = JsonHelper.getJsonFromObject(registerSecurityRq);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
logger.info(loggerHelper.buildInfoPrivateResponse(requestId, "RegisterSecurityRs", response.toString()));
}
} else {
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
logger.info(loggerHelper.buildInfoPrivateResponse(requestId, "RegisterSecurityRs", response.toString()));
}
}
connection.disconnect();
} catch (IOException e) {
logger.log(Level.SEVERE, String.format("Error interno writeTrice: %s", e.getMessage()));
logger.info(loggerHelper.buildInfoPrivateResponse(requestId, "RegisterSecurityRs", e.getMessage()));
}
}, executor).exceptionally(ex -> {
logger.log(Level.SEVERE, String.format("Async Error interno writeTrice: %s", ex.getMessage()));
logger.info(loggerHelper.buildInfoPrivateResponse(requestId, "RegisterSecurityRs", ex.getMessage()));
return null;
});
}
public void shutdown() {
executor.shutdown();
}
}

View File

@ -0,0 +1,104 @@
package com.banesco.common.infraestructure.service;
import com.banesco.common.domain.model.BackResponse;
import com.banesco.common.domain.dto.bian.response.StatusResponse;
import com.banesco.common.infraestructure.repository.MessageRepository;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MessageService {
private static final Logger logger = Logger.getLogger(MessageService.class.getName());
private final MessageRepository messageRepository;
private final String CONFLICT = "CONFLICT";
private final BackResponse DEFAULT_ERROR = new BackResponse(
CONFLICT,
409,
CONFLICT,
CONFLICT
);
private boolean messagesInsideProperties = false;
/**
* Constructor de MessageService.
*
* @param messageRepository El repositorio de mensajes que se utilizará para
* cargar y obtener mensajes de error.
*/
public MessageService(MessageRepository messageRepository) {
this.messageRepository = messageRepository;
}
/**
* Carga mensajes desde una cadena JSON en el repositorio de mensajes.
*
* @param responseFileName El nombre del archivo de respuesta asociado con
* los mensajes.
* @param jsonResponse La cadena JSON que contiene los mensajes.
*/
public void loadMessageFromJson(String responseFileName, String jsonResponse) {
messagesInsideProperties = true;
try {
messageRepository.loadMessagesFromString(responseFileName, jsonResponse);
} catch (Exception ex) {
logger.log(Level.SEVERE, "Error loading messages from JSON: %s".formatted(ex.getMessage()), ex);
}
}
/**
* Obtiene una respuesta de estado (BackResponse) basada en el código de
* backend y el nombre del archivo de respuesta.
*
* @param responseFileName El nombre del archivo de respuesta.
* @param backendCode El código de backend para buscar la respuesta.
* @return La respuesta de estado (BackResponse) correspondiente al código
* de backend, la respuesta por defecto si no se encuentra, o null si hay un
* error.
*/
public BackResponse geStatusResponse(String responseFileName, String backendCode) {
logger.log(Level.INFO, "Finding backendCode: \"%s\" in File: \"%s\"".formatted(backendCode, responseFileName));
Map<String, BackResponse> errors = messageRepository.getErrorMap(responseFileName, messagesInsideProperties);
if (errors == null || errors.isEmpty()) {
logger.log(Level.WARNING, "Error map for %s is empty or null.".formatted(responseFileName));
return DEFAULT_ERROR;
}
BackResponse backResponse = null;
try {
backResponse = errors.get(backendCode);
if (backResponse == null) {
backResponse = errors.get("default");
}
} catch (Exception e) {
logger.log(Level.WARNING, "Error code: %s not found in %s. Using default.".formatted(backendCode, responseFileName), e);
try {
backResponse = errors.get("default");
} catch (Exception e2) {
logger.log(Level.SEVERE, "Error getting default code.", e2);
}
}
if (backResponse == null) {
logger.log(Level.WARNING, "Error code: %s and default not found in %s.".formatted(backendCode, responseFileName));
return DEFAULT_ERROR;
}
return backResponse;
}
public StatusResponse backToStatusResponse(String traceId, BackResponse backResponse, String target) {
return new StatusResponse(
backResponse.getHttpCode()>=200 && backResponse.getHttpCode()<300?"ok":"error",
backResponse.getStatusCode(),
target == null ? backResponse.getDescription() :
backResponse.getDescription().formatted(target),
traceId
);
}
}

View File

@ -0,0 +1,90 @@
package com.banesco.common.infraestructure.utils;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/**
* Clase para validación de fechas con configuración flexible. Permite validar
* fechas en diferentes formatos, comprobar rangos de años y verificar la
* correcta formación de componentes de fecha (año, mes, día). Implementa el
* patrón Builder para facilitar la configuración personalizada de los
* parámetros de validación.
*/
public class DateValidator {
private final DateTimeFormatter dateFormatter;
private final PatternValidator datePattern;
private final int minYear;
private final int maxYear;
private DateValidator(Builder builder) {
this.dateFormatter = builder.dateFormatter;
this.datePattern = new PatternValidator(builder.dateFormatRegex);
this.minYear = builder.minYear;
this.maxYear = builder.maxYear;
}
public static class Builder {
private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
private String dateFormatRegex = "(\\d{4})/(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])";
private int minYear = 1900;
private int maxYear = 2100;
public Builder withDateFormatter(String dateFormatterPattern) {
this.dateFormatter = DateTimeFormatter.ofPattern(dateFormatterPattern);
return this;
}
public Builder withDateFormatRegex(String dateFormatRegex) {
this.dateFormatRegex = dateFormatRegex;
return this;
}
public Builder withMinYear(int minYear) {
this.minYear = minYear;
return this;
}
public Builder withMaxYear(int maxYear) {
this.maxYear = maxYear;
return this;
}
public DateValidator build() {
return new DateValidator(this);
}
}
public boolean isValidDateFormat(String date) {
return datePattern.isValid(date);
}
public boolean isValidDate(String date) {
if (!isValidDateFormat(date)) {
return false;
}
try {
LocalDate parsedDate = LocalDate.parse(date, dateFormatter);
String formattedDate = parsedDate.format(dateFormatter);
return date.equals(formattedDate);
} catch (DateTimeException e) {
return false;
}
}
public boolean isValidDate(int year, int month, int day) {
return year >= minYear && year <= maxYear && month >= 1 && month <= 12 && isValidDayOfMonth(year, month, day);
}
private boolean isValidDayOfMonth(int year, int month, int day) {
try {
LocalDate.of(year, month, day);
return true;
} catch (DateTimeException e) {
return false;
}
}
}

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