diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..6930896 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,14 @@ +{ + "configurations": [ + { + "type": "java", + "name": "Spring Boot-BackendTestArguetaApplication", + "request": "launch", + "cwd": "${workspaceFolder}", + "mainClass": "com.github.wilberargueta.backend.backend_test_argueta.BackendTestArguetaApplication", + "projectName": "backend-test-argueta", + "args": "", + "envFile": "${workspaceFolder}/.env" + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..5b198df --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "java.configuration.updateBuildConfiguration": "interactive", + "java.dependency.packagePresentation": "hierarchical" +} \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index 0ef43ea..0000000 --- a/README.md +++ /dev/null @@ -1 +0,0 @@ -# tesffullstack diff --git a/backend_argueta/.gitattributes b/backend_argueta/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/backend_argueta/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/backend_argueta/.gitignore b/backend_argueta/.gitignore new file mode 100644 index 0000000..667aaef --- /dev/null +++ b/backend_argueta/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/backend_argueta/.mvn/wrapper/maven-wrapper.properties b/backend_argueta/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..216df05 --- /dev/null +++ b/backend_argueta/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip diff --git a/backend_argueta/README.md b/backend_argueta/README.md new file mode 100644 index 0000000..c2f8501 --- /dev/null +++ b/backend_argueta/README.md @@ -0,0 +1,86 @@ +# Requerimientos + +* Java JDK 8 instalado. +* Maven 3.6 o superior instalado. +* MySQL instalado en su sistema. Desarrollado y probado con **MySQL Server 8.0.31**. +* Acceso de administrador a MySQL. +* Git instalado para clonar el repositorio. + + + +# Despliegue y Ejecución + +## 1. Clonar el repositorio + +```bash +git clone https://github.com/tonysoft2018/tesffullstack +``` + +## 2. Ingresar al directorio del proyecto + +```bash +cd tesffullstack +``` +# Configuración Inicial (Obligatoria) + +Antes de compilar o ejecutar la aplicación, debe configurar correctamente el archivo de propiedades del proyecto. +> **Importante:** Verifique que la base de datos, el usuario y la contraseña configurados existan en su servidor MySQL antes de iniciar la aplicación. +Ubique el archivo: + +```text +/backend_argueta/src/main/resources/application.properties +``` + +Configure los siguientes valores según su entorno para la base de datos: + +```properties +server.port=8080 +spring.application.name=backend-test-argueta + +spring.jpa.hibernate.ddl-auto=update + +spring.datasource.url=jdbc:mysql://localhost:3306/bd_argueta +spring.datasource.username=conexion +spring.datasource.password=password123 +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +spring.jpa.show-sql=true +``` + +# Compilación del Proyecto + +Una vez configurado correctamente el archivo `application.properties`, compile el proyecto ejecutando: + +```bash +mvn clean install +``` + +Si la compilación finaliza sin errores, se generará el artefacto correspondiente en la carpeta: + +```text +target/ +``` + +# Ejecución de la Aplicación + +Después de una compilación exitosa, inicie la aplicación con el siguiente comando: + +```bash +mvn spring-boot:run +``` + +O ejecutando el archivo JAR generado: + +```bash +java -jar target/backend-test-argueta.jar +``` + +# Verificación + +Una vez iniciada la aplicación, verifique que el servicio se encuentre disponible en: + +```text +http://localhost:8080 +``` + +Revise la consola de ejecución para confirmar que la conexión a la base de datos fue establecida correctamente y que la aplicación inició sin errores. diff --git a/backend_argueta/mvnw b/backend_argueta/mvnw new file mode 100644 index 0000000..bd8896b --- /dev/null +++ b/backend_argueta/mvnw @@ -0,0 +1,295 @@ +#!/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 +# +# http://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.4 +# +# 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:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# 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 <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.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${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/backend_argueta/mvnw.cmd b/backend_argueta/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/backend_argueta/mvnw.cmd @@ -0,0 +1,189 @@ +<# : 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 http://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.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/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_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::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 + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/backend_argueta/pom.xml b/backend_argueta/pom.xml new file mode 100644 index 0000000..a9443a9 --- /dev/null +++ b/backend_argueta/pom.xml @@ -0,0 +1,138 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.9 + + + com.github.wilberargueta.backend + backend-test-argueta + 0.0.1-SNAPSHOT + backend-test-argueta + + + + + + + + + + + + + + + + 1.8 + 1.2.0.Final + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + com.mysql + mysql-connector-j + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-validation + + + org.mapstruct + mapstruct-jdk8 + ${org.mapstruct.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + compile + + compile + + + + + org.projectlombok + lombok + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + + + + + default-testCompile + test-compile + + testCompile + + + + + org.projectlombok + lombok + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + + + + + + + + + diff --git a/backend_argueta/postman_argueta/argueta_postman.postman_collection.json b/backend_argueta/postman_argueta/argueta_postman.postman_collection.json new file mode 100644 index 0000000..9d20699 --- /dev/null +++ b/backend_argueta/postman_argueta/argueta_postman.postman_collection.json @@ -0,0 +1,186 @@ +{ + "info": { + "_postman_id": "eef18e9d-a891-4447-87af-37aa685bb557", + "name": "argueta_postman", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "7500078" + }, + "item": [ + { + "name": "Crear Person", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\r\n \"nombre\":\"Juan\",\r\n \"apellido\":\"Perez\",\r\n \"fechaNacimiento\":\"1993-01-01\",\r\n \"puesto\":\"Sub-Gerente\",\r\n \"sueldo\": 2000\r\n}\r\n", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "http://localhost:8080/person", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "person" + ] + } + }, + "response": [] + }, + { + "name": "Actualizar persona", + "request": { + "method": "PUT", + "header": [ + { + "key": "Content-Type", + "value": "application/json", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\r\n\r\n \"id\":1,\r\n \"nombre\":\"Juan\",\r\n \"apellido\":\"Perez\",\r\n \"fechaNacimiento\":\"1993-01-01\",\r\n \"puesto\":\"Sub-Gerente\",\r\n \"sueldo\": 2001\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "http://localhost:8080/person", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "person" + ] + } + }, + "response": [] + }, + { + "name": "Consultar Persona", + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "auth": { + "type": "noauth" + }, + "method": "GET", + "header": [ + { + "key": "Content-Type", + "value": "application/json", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\r\n\r\n \"id\":1,\r\n \"nombre\":\"Juan\",\r\n \"apellido\":\"Perez\",\r\n \"fechaNacimiento\":\"1993-01-01\",\r\n \"puesto\":\"Sub-Gerente\",\r\n \"sueldo\": 2001\r\n}" + }, + "url": { + "raw": "http://localhost:8080/person/2", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "person", + "2" + ] + } + }, + "response": [] + }, + { + "name": "Consultar todas las personas", + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "method": "GET", + "header": [ + { + "key": "Content-Type", + "value": "application/json", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\r\n\r\n \"id\":1,\r\n \"nombre\":\"Juan\",\r\n \"apellido\":\"Perez\",\r\n \"fechaNacimiento\":\"1993-01-01\",\r\n \"puesto\":\"Sub-Gerente\",\r\n \"sueldo\": 2001\r\n}" + }, + "url": { + "raw": "http://localhost:8080/person?page=0&size=10", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "person" + ], + "query": [ + { + "key": "page", + "value": "0" + }, + { + "key": "size", + "value": "10" + } + ] + } + }, + "response": [] + }, + { + "name": "Eliminar Persona", + "request": { + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "value": "application/json", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\r\n\r\n \"id\":1,\r\n \"nombre\":\"Juan\",\r\n \"apellido\":\"Perez\",\r\n \"fechaNacimiento\":\"1993-01-01\",\r\n \"puesto\":\"Sub-Gerente\",\r\n \"sueldo\": 2001\r\n}" + }, + "url": { + "raw": "http://localhost:8080/person/1", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "person", + "1" + ] + } + }, + "response": [] + } + ] +} \ No newline at end of file diff --git a/backend_argueta/postman_argueta/captura_pruebas/actualizacion.png b/backend_argueta/postman_argueta/captura_pruebas/actualizacion.png new file mode 100644 index 0000000..fe2f4be Binary files /dev/null and b/backend_argueta/postman_argueta/captura_pruebas/actualizacion.png differ diff --git a/backend_argueta/postman_argueta/captura_pruebas/consulta_con_paginacion.png b/backend_argueta/postman_argueta/captura_pruebas/consulta_con_paginacion.png new file mode 100644 index 0000000..8adbce9 Binary files /dev/null and b/backend_argueta/postman_argueta/captura_pruebas/consulta_con_paginacion.png differ diff --git a/backend_argueta/postman_argueta/captura_pruebas/consulta_por_id.png b/backend_argueta/postman_argueta/captura_pruebas/consulta_por_id.png new file mode 100644 index 0000000..1791015 Binary files /dev/null and b/backend_argueta/postman_argueta/captura_pruebas/consulta_por_id.png differ diff --git a/backend_argueta/postman_argueta/captura_pruebas/creacion.png b/backend_argueta/postman_argueta/captura_pruebas/creacion.png new file mode 100644 index 0000000..5bc2fc6 Binary files /dev/null and b/backend_argueta/postman_argueta/captura_pruebas/creacion.png differ diff --git a/backend_argueta/postman_argueta/captura_pruebas/eliminacion.png b/backend_argueta/postman_argueta/captura_pruebas/eliminacion.png new file mode 100644 index 0000000..3d93125 Binary files /dev/null and b/backend_argueta/postman_argueta/captura_pruebas/eliminacion.png differ diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/BackendTestArguetaApplication.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/BackendTestArguetaApplication.java new file mode 100644 index 0000000..c4113a1 --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/BackendTestArguetaApplication.java @@ -0,0 +1,13 @@ +package com.github.wilberargueta.backend.backend_test_argueta; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BackendTestArguetaApplication { + + public static void main(String[] args) { + SpringApplication.run(BackendTestArguetaApplication.class, args); + } + +} diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/config/ExceptionController.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/config/ExceptionController.java new file mode 100644 index 0000000..f41a775 --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/config/ExceptionController.java @@ -0,0 +1,40 @@ +package com.github.wilberargueta.backend.backend_test_argueta.config; + +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import com.github.wilberargueta.backend.backend_test_argueta.dto.response.GenericResponse; +import com.github.wilberargueta.backend.backend_test_argueta.exceptions.NotFoundException; + +@RestControllerAdvice +public class ExceptionController { + private final Logger log = LoggerFactory.getLogger(getClass()); + + @ExceptionHandler(NotFoundException.class) + public ResponseEntity> general(NotFoundException ex) { + + return ResponseEntity.ok(GenericResponse.builder().message(ex.getMessage()).status(false).build()); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> general(MethodArgumentNotValidException ex) { + + String collectDefaultMessage = ex.getAllErrors().stream().map(err -> err.getDefaultMessage()).collect(Collectors.joining("\n-")); + + return ResponseEntity.ok(GenericResponse.builder().message(collectDefaultMessage).status(false).build()); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity> general(Exception ex) { + log.error(ex.getMessage(), ex); + + return ResponseEntity.ok(GenericResponse.builder().message(ex.getMessage()).status(false).build()); + } + +} diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/config/ResponseInterceptor.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/config/ResponseInterceptor.java new file mode 100644 index 0000000..ef89bfd --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/config/ResponseInterceptor.java @@ -0,0 +1,21 @@ +package com.github.wilberargueta.backend.backend_test_argueta.config; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.lang.Nullable; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +@Component +public class ResponseInterceptor implements HandlerInterceptor { + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, + @Nullable ModelAndView modelAndView) throws Exception { + response.setHeader("Access-Control-Allow-Origin", "*"); + response.setHeader("Access-Control-Allow-Methods", "*"); + response.setHeader("Access-Control-Allow-Headers", "*"); + HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); + } +} diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/config/WebConfig.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/config/WebConfig.java new file mode 100644 index 0000000..54b3f28 --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/config/WebConfig.java @@ -0,0 +1,26 @@ +package com.github.wilberargueta.backend.backend_test_argueta.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import lombok.RequiredArgsConstructor; + +@Configuration +@RequiredArgsConstructor +public class WebConfig implements WebMvcConfigurer { + private final ResponseInterceptor responseInterceptor; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(responseInterceptor).addPathPatterns("/**"); + } + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*").allowedMethods("*"); + WebMvcConfigurer.super.addCorsMappings(registry); + } + +} \ No newline at end of file diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/controller/PersonController.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/controller/PersonController.java new file mode 100644 index 0000000..7ec071f --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/controller/PersonController.java @@ -0,0 +1,61 @@ +package com.github.wilberargueta.backend.backend_test_argueta.controller; + +import javax.validation.Valid; + +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.github.wilberargueta.backend.backend_test_argueta.dto.request.person.PersonCreateDto; +import com.github.wilberargueta.backend.backend_test_argueta.dto.request.person.PersonUpdateDto; +import com.github.wilberargueta.backend.backend_test_argueta.dto.response.GenericResponse; +import com.github.wilberargueta.backend.backend_test_argueta.dto.response.PaginatedResponse; +import com.github.wilberargueta.backend.backend_test_argueta.dto.response.person.PersonResponseDto; +import com.github.wilberargueta.backend.backend_test_argueta.service.PersonService; + +import lombok.RequiredArgsConstructor; + +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; + +@RestController +@RequestMapping("/person") +@RequiredArgsConstructor +public class PersonController { + + private final PersonService personService; + + @PostMapping + public ResponseEntity> createPerson( + @Valid @RequestBody PersonCreateDto createDto) { + return ResponseEntity.ok(GenericResponse.ok(this.personService.createPerson(createDto))); + } + + @PutMapping + public ResponseEntity> updatePerson( + @Valid @RequestBody PersonUpdateDto createDto) { + return ResponseEntity.ok(GenericResponse.ok(this.personService.updatePerson(createDto))); + } + + @DeleteMapping("/{id}") + public ResponseEntity> deletePerson(@PathVariable Long id) { + Boolean deletePerson = this.personService.deletePerson(id); + return ResponseEntity.ok(GenericResponse.ok(deletePerson)); + } + + @GetMapping("/{id}") + public ResponseEntity> getPerson(@PathVariable Long id) { + return ResponseEntity.ok(GenericResponse.ok(this.personService.getPerson(id))); + } + + @GetMapping + public ResponseEntity>> getPerson(Pageable pageable) { + return ResponseEntity.ok(GenericResponse.ok(this.personService.getPerson(pageable))); + } + +} diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/request/person/PersonCreateDto.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/request/person/PersonCreateDto.java new file mode 100644 index 0000000..e0bcf16 --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/request/person/PersonCreateDto.java @@ -0,0 +1,29 @@ +package com.github.wilberargueta.backend.backend_test_argueta.dto.request.person; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Min; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +@Data +@AllArgsConstructor +@Builder +public class PersonCreateDto { + + @NotBlank(message = "Nombre es requerido") + private String nombre; + @NotBlank(message = "Apellido es requerido") + private String apellido; + @NotNull(message = "Fecha de nacimiento es requerido") + private LocalDate fechaNacimiento; + @NotBlank(message = "Puesto es requerido") + private String puesto; + @Min(value = 1, message = "Sueldo es requerido") + private BigDecimal sueldo; +} diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/request/person/PersonUpdateDto.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/request/person/PersonUpdateDto.java new file mode 100644 index 0000000..9f11757 --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/request/person/PersonUpdateDto.java @@ -0,0 +1,28 @@ +package com.github.wilberargueta.backend.backend_test_argueta.dto.request.person; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +import lombok.Data; + +@Data +public class PersonUpdateDto { + + @NotNull(message = "Se debe especificar un id") + private Long id; + @NotBlank(message = "Nombre es requerido") + private String nombre; + @NotBlank(message = "Apellido es requerido") + private String apellido; + @NotNull(message = "Fecha de nacimiento es requerido") + private LocalDate fechaNacimiento; + @NotBlank(message = "Puesto es requerido") + private String puesto; + @Min(value = 1, message = "Sueldo es requerido") + private BigDecimal sueldo; + +} diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/response/GenericResponse.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/response/GenericResponse.java new file mode 100644 index 0000000..5ce997f --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/response/GenericResponse.java @@ -0,0 +1,18 @@ +package com.github.wilberargueta.backend.backend_test_argueta.dto.response; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class GenericResponse { + private Boolean status; + private String message; + private D data; + + public static GenericResponse ok(D data) { + + return GenericResponse.builder().data(data).status(true).message("Petición exitosa").build(); + } + +} diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/response/PaginatedResponse.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/response/PaginatedResponse.java new file mode 100644 index 0000000..3f46f9d --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/response/PaginatedResponse.java @@ -0,0 +1,17 @@ +package com.github.wilberargueta.backend.backend_test_argueta.dto.response; + +import java.util.List; + +import lombok.Data; + +@Data +public class PaginatedResponse { + private List data; + private int currentPage; + private int totalPages; + private long totalItems; + private int pageSize; + private boolean hasNext; + private boolean hasPrevious; + +} \ No newline at end of file diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/response/person/PersonResponseDto.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/response/person/PersonResponseDto.java new file mode 100644 index 0000000..120c87d --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/dto/response/person/PersonResponseDto.java @@ -0,0 +1,18 @@ +package com.github.wilberargueta.backend.backend_test_argueta.dto.response.person; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import lombok.Data; + +@Data +public class PersonResponseDto { + + private Long id; + private String nombre; + private String apellido; + private LocalDate fechaNacimiento; + private String puesto; + private BigDecimal sueldo; + +} diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/exceptions/NotFoundException.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/exceptions/NotFoundException.java new file mode 100644 index 0000000..54d1ea2 --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/exceptions/NotFoundException.java @@ -0,0 +1,16 @@ +package com.github.wilberargueta.backend.backend_test_argueta.exceptions; + +import lombok.Getter; + +@Getter +public class NotFoundException extends RuntimeException{ + + private String message; + + public NotFoundException(String message) { + super(message); + this.message = message; + } + + +} diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/mapper/PersonMapper.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/mapper/PersonMapper.java new file mode 100644 index 0000000..862f2d4 --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/mapper/PersonMapper.java @@ -0,0 +1,21 @@ +package com.github.wilberargueta.backend.backend_test_argueta.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +import com.github.wilberargueta.backend.backend_test_argueta.dto.request.person.PersonCreateDto; +import com.github.wilberargueta.backend.backend_test_argueta.dto.request.person.PersonUpdateDto; +import com.github.wilberargueta.backend.backend_test_argueta.dto.response.person.PersonResponseDto; +import com.github.wilberargueta.backend.backend_test_argueta.repository.entity.PersonEntity; + +@Mapper(componentModel = "spring") +public interface PersonMapper { + + PersonResponseDto entityToResponse(PersonEntity entity); + + @Mapping(target="id", ignore = true) + PersonEntity requestToeEntity(PersonCreateDto dto); + + PersonEntity requestToeEntity(PersonUpdateDto dto); + +} diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/repository/PersonRepository.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/repository/PersonRepository.java new file mode 100644 index 0000000..3e06df9 --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/repository/PersonRepository.java @@ -0,0 +1,9 @@ +package com.github.wilberargueta.backend.backend_test_argueta.repository; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.github.wilberargueta.backend.backend_test_argueta.repository.entity.PersonEntity; + +public interface PersonRepository extends JpaRepository { + +} diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/repository/entity/PersonEntity.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/repository/entity/PersonEntity.java new file mode 100644 index 0000000..c48db22 --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/repository/entity/PersonEntity.java @@ -0,0 +1,30 @@ +package com.github.wilberargueta.backend.backend_test_argueta.repository.entity; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import javax.persistence.*; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Table(name = "person") +@Entity +@Getter +@Setter +@ToString +public class PersonEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; + + private String nombre; + private String apellido; + private LocalDate fechaNacimiento; + private String puesto; + private BigDecimal sueldo; + +} diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/service/PersonService.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/service/PersonService.java new file mode 100644 index 0000000..dd91189 --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/service/PersonService.java @@ -0,0 +1,22 @@ +package com.github.wilberargueta.backend.backend_test_argueta.service; + +import org.springframework.data.domain.Pageable; + +import com.github.wilberargueta.backend.backend_test_argueta.dto.request.person.PersonCreateDto; +import com.github.wilberargueta.backend.backend_test_argueta.dto.request.person.PersonUpdateDto; +import com.github.wilberargueta.backend.backend_test_argueta.dto.response.PaginatedResponse; +import com.github.wilberargueta.backend.backend_test_argueta.dto.response.person.PersonResponseDto; + +public interface PersonService { + + PersonResponseDto createPerson(PersonCreateDto createDto); + + PersonResponseDto updatePerson(PersonUpdateDto createDto); + + Boolean deletePerson(Long id); + + PersonResponseDto getPerson(Long id); + + PaginatedResponse getPerson(Pageable pageable); + +} diff --git a/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/service/impl/PersonServiceImplement.java b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/service/impl/PersonServiceImplement.java new file mode 100644 index 0000000..992a224 --- /dev/null +++ b/backend_argueta/src/main/java/com/github/wilberargueta/backend/backend_test_argueta/service/impl/PersonServiceImplement.java @@ -0,0 +1,102 @@ +package com.github.wilberargueta.backend.backend_test_argueta.service.impl; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import com.github.wilberargueta.backend.backend_test_argueta.dto.request.person.PersonCreateDto; +import com.github.wilberargueta.backend.backend_test_argueta.dto.request.person.PersonUpdateDto; +import com.github.wilberargueta.backend.backend_test_argueta.dto.response.PaginatedResponse; +import com.github.wilberargueta.backend.backend_test_argueta.dto.response.person.PersonResponseDto; +import com.github.wilberargueta.backend.backend_test_argueta.exceptions.NotFoundException; +import com.github.wilberargueta.backend.backend_test_argueta.mapper.PersonMapper; +import com.github.wilberargueta.backend.backend_test_argueta.repository.PersonRepository; +import com.github.wilberargueta.backend.backend_test_argueta.repository.entity.PersonEntity; +import com.github.wilberargueta.backend.backend_test_argueta.service.PersonService; + +import lombok.RequiredArgsConstructor; + +@Service +@RequiredArgsConstructor +public class PersonServiceImplement implements PersonService { + + private final Logger log = LoggerFactory.getLogger(getClass()); + private final PersonRepository personRepository; + private final PersonMapper personMapper; + + @Override + public PersonResponseDto createPerson(PersonCreateDto createDto) { + log.info("Saving person"); + PersonEntity savedPersonResult = this.personRepository.save(this.personMapper.requestToeEntity(createDto)); + log.info("Saved person: {}", savedPersonResult.getId()); + + return this.personMapper.entityToResponse(savedPersonResult); + } + + @Override + public PersonResponseDto updatePerson(PersonUpdateDto updateDto) { + Optional byIdOptional = this.personRepository.findById(updateDto.getId()); + if (!byIdOptional.isPresent()) { + log.info("Person not found: {}", updateDto.getId()); + throw new NotFoundException("No se encontró a la persona a actualizar"); + } + + log.info("Updating person"); + PersonEntity savedPersonResult = this.personRepository.save(this.personMapper.requestToeEntity(updateDto)); + log.info("Updated person: {}", savedPersonResult.getId()); + + return this.personMapper.entityToResponse(savedPersonResult); + } + + @Override + public Boolean deletePerson(Long id) { + Optional byIdOptional = this.personRepository.findById(id); + if (!byIdOptional.isPresent()) { + log.info("Person not found: {}", id); + throw new NotFoundException("No se encontró a la persona a eliminar"); + } + + log.info("Deleting person"); + this.personRepository.deleteById(id); + log.info("Deleted person: {}", id); + + return true; + } + + @Override + public PersonResponseDto getPerson(Long id) { + Optional byIdOptional = this.personRepository.findById(id); + if (!byIdOptional.isPresent()) { + log.info("Person not found: {}", id); + throw new NotFoundException("No se encontró a la persona a consultar"); + } + + return this.personMapper.entityToResponse(byIdOptional.get()); + } + + @Override + public PaginatedResponse getPerson(Pageable pageable) { + Page all = this.personRepository.findAll(pageable); + log.info("People found size: {}", all.getSize()); + + List collect = all.getContent().stream().map(this.personMapper::entityToResponse) + .collect(Collectors.toList()); + PaginatedResponse response = new PaginatedResponse<>(); + response.setData(collect); + response.setCurrentPage(all.getNumber()); + response.setTotalPages(all.getTotalPages()); + response.setTotalItems(all.getTotalElements()); + response.setPageSize(all.getSize()); + response.setHasNext(all.hasNext()); + response.setHasPrevious(all.hasPrevious()); + + return response; + } + +} diff --git a/backend_argueta/src/main/resources/application.properties b/backend_argueta/src/main/resources/application.properties new file mode 100644 index 0000000..187c767 --- /dev/null +++ b/backend_argueta/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.port=8080 +spring.application.name=backend-test-argueta +spring.jpa.hibernate.ddl-auto=update +spring.datasource.url=jdbc:mysql://localhost:3306/bd_argueta +spring.datasource.username=conexion +spring.datasource.password=password123 +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +spring.jpa.show-sql=true \ No newline at end of file diff --git a/backend_argueta/src/test/java/com/github/wilberargueta/backend/backend_test_argueta/BackendTestArguetaApplicationTests.java b/backend_argueta/src/test/java/com/github/wilberargueta/backend/backend_test_argueta/BackendTestArguetaApplicationTests.java new file mode 100644 index 0000000..005ada3 --- /dev/null +++ b/backend_argueta/src/test/java/com/github/wilberargueta/backend/backend_test_argueta/BackendTestArguetaApplicationTests.java @@ -0,0 +1,13 @@ +package com.github.wilberargueta.backend.backend_test_argueta; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class BackendTestArguetaApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/bd/README.md b/bd/README.md deleted file mode 100644 index 0ad162f..0000000 --- a/bd/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# Requerimientos - -- MySQL instalado en su sistema. Desarrollado con Ver 8.0.31 for Win64 on x86_64 (MySQL Community Server - GPL). -- Acceso de administrador a MySQL. - -# Despliegue y Ejecución - -1. Clonar este repositorio: - ``` - git clone https://github.com/usuario/repositorio.git - ``` - -2. Iniciar sesión en MySQL como usuario root: - ``` - mysql -u root -p - ``` - -3. Cargar el script de creación de la base de datos: - ``` - source ruta_del_script_creacion_bd.sql - ``` - Ejemplo: `D:\SRC\GitHub\tonysoft2018\tesffullstack\bd\script_creacion_bd.sql` - -4. Cambiar a la base de datos recién creada: - ``` - USE bd_garcia; - ``` - -5. Ejecutar la consulta para verificar los datos en la tabla person: - ``` - SELECT * FROM person; - ``` - -6. Crear un nuevo usuario para la conexión del backend y otorgarle privilegios: - ``` - CREATE USER 'conexion'@'localhost' IDENTIFIED BY 'Wk2!rT8s@6w'; - GRANT ALL PRIVILEGES ON bd_garcia.* TO 'conexion'@'localhost'; - FLUSH PRIVILEGES; - ``` - -7. Salir de MySQL: - ``` - exit; - ``` \ No newline at end of file diff --git a/bd/script_creacion_bd.sql b/bd/script_creacion_bd.sql deleted file mode 100644 index 89a9fbc..0000000 --- a/bd/script_creacion_bd.sql +++ /dev/null @@ -1,12 +0,0 @@ -CREATE DATABASE IF NOT EXISTS bd_garcia; - -USE bd_garcia; - -CREATE TABLE IF NOT EXISTS person ( - id INT AUTO_INCREMENT PRIMARY KEY, - nombre VARCHAR(255), - apellido VARCHAR(255), - fechaNacimiento DATE, - puesto VARCHAR(255), - sueldo DECIMAL(10, 2) -);