diff --git a/README.luis.md b/README.luis.md new file mode 100644 index 0000000..c44ab43 --- /dev/null +++ b/README.luis.md @@ -0,0 +1,39 @@ +# Proyecto Spring Boot con Gradle + +Este es un proyecto Spring Boot desarrollado con Gradle y alojado en GitHub. +El proyecto proporciona servicios para la gestión de usuarios y autenticación utilizando tokens JWT. + +## Enlaces Relevantes + +- [Repositorio del proyecto en GitHub](https://github.com/universeflow/java-recruiting-hsa.git) +- [Rama del proyecto] master + + + +## Endpoints + + +- `Get /api/`: Consulta un top 5 de categorias + +## Documentación + +- `{server}/swagger-ui.html` en esta ruta pueden probar y consultar documentación de los endpoint + +## Instrucciones de Uso + +1. Clona el repositorio desde la [rama develop](https://github.com/universeflow/java-recruiting-hsa.git). +2. Abre el proyecto en tu entorno de desarrollo favorito (por ejemplo, IntelliJ IDEA o Eclipse). +3. Java 8 . +4. Configura la base de datos y las propiedades de la aplicación según sea necesario. +5. Ejecuta la aplicación Spring Boot. + ## Levantar el proyecto en windows + + - ./gradlew clean build + - ./gradlew bootRun + + +6. Utiliza las URL y los métodos de los endpoints para interactuar con la aplicación. + +## Requisitos + +- Java 8 o superior \ No newline at end of file diff --git a/demo/proyect/HELP.md b/demo/proyect/HELP.md new file mode 100644 index 0000000..d091621 --- /dev/null +++ b/demo/proyect/HELP.md @@ -0,0 +1,14 @@ +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Gradle documentation](https://docs.gradle.org) +* [Spring Boot Gradle Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/3.2.0/gradle-plugin/reference/html/) +* [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.2.0/gradle-plugin/reference/html/#build-image) + +### Additional Links +These additional references should also help you: + +* [Gradle Build Scans – insights for your project's build](https://scans.gradle.com#gradle) + diff --git a/demo/proyect/build.gradle b/demo/proyect/build.gradle new file mode 100644 index 0000000..c4f5051 --- /dev/null +++ b/demo/proyect/build.gradle @@ -0,0 +1,43 @@ +plugins { + id 'java' + id 'groovy' + id 'org.springframework.boot' version '2.7.17' + id 'io.spring.dependency-management' version '1.0.15.RELEASE' +} + +group = 'com.example.demo' +version = '0.0.1-SNAPSHOT' +description = 'Evaluacion java integracion' + +java { + sourceCompatibility = '1.8' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-devtools' + implementation 'com.h2database:h2' + implementation 'org.projectlombok:lombok' + implementation 'org.junit.jupiter:junit-jupiter:5.8.1' + compileOnly 'org.projectlombok:lombok:1.18.30' + annotationProcessor 'org.projectlombok:lombok:1.18.30' + implementation 'org.spockframework:spock-core:2.3-groovy-4.0' + implementation 'io.springfox:springfox-swagger2:2.9.2' + implementation 'io.springfox:springfox-swagger-ui:2.9.2' + implementation 'org.jetbrains:annotations:24.0.1' + testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' + testImplementation 'org.mockito:mockito-core:4.11.0' + testImplementation 'org.mockito:mockito-junit-jupiter:4.11.0' + + implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.3' + implementation 'org.springframework.cloud:spring-cloud-starter-openfeign:3.1.3' + + implementation platform('org.springframework.cloud:spring-cloud-dependencies:2021.0.3') +} diff --git a/demo/proyect/gradle/wrapper/gradle-wrapper.jar b/demo/proyect/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/demo/proyect/gradle/wrapper/gradle-wrapper.jar differ diff --git a/demo/proyect/gradle/wrapper/gradle-wrapper.properties b/demo/proyect/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..1af9e09 --- /dev/null +++ b/demo/proyect/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/demo/proyect/gradlew b/demo/proyect/gradlew new file mode 100644 index 0000000..1aa94a4 --- /dev/null +++ b/demo/proyect/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed 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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/demo/proyect/gradlew.bat b/demo/proyect/gradlew.bat new file mode 100644 index 0000000..6689b85 --- /dev/null +++ b/demo/proyect/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem 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, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/demo/proyect/settings.gradle b/demo/proyect/settings.gradle new file mode 100644 index 0000000..0a383dd --- /dev/null +++ b/demo/proyect/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'demo' diff --git a/demo/proyect/src/main/java/com/example/demo/DemoApplication.java b/demo/proyect/src/main/java/com/example/demo/DemoApplication.java new file mode 100644 index 0000000..e76392d --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/DemoApplication.java @@ -0,0 +1,16 @@ +package com.example.demo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.openfeign.EnableFeignClients; + +@SpringBootApplication + (scanBasePackages = { "com.example.demo"}) +@EnableFeignClients(basePackages = {"com.example.demo.feign"}) +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } + +} diff --git a/demo/proyect/src/main/java/com/example/demo/config/ClientConfiguration.java b/demo/proyect/src/main/java/com/example/demo/config/ClientConfiguration.java new file mode 100644 index 0000000..43752b5 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/config/ClientConfiguration.java @@ -0,0 +1,18 @@ +package com.example.demo.config; + + +import com.example.demo.controller.handler.CustomErrorDecoder; +import com.example.demo.properties.PropertiesFeign; +import feign.codec.ErrorDecoder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ClientConfiguration { + + @Bean + public ErrorDecoder errorDecoder() { + return new CustomErrorDecoder(new PropertiesFeign()); + } + +} diff --git a/demo/proyect/src/main/java/com/example/demo/config/SwaggerConfig.java b/demo/proyect/src/main/java/com/example/demo/config/SwaggerConfig.java new file mode 100644 index 0000000..acccaa9 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/config/SwaggerConfig.java @@ -0,0 +1,43 @@ +package com.example.demo.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import java.util.Collections; + +@Configuration +@EnableSwagger2 +public class SwaggerConfig { + + + @Bean + public Docket apiDocket() { + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) + .paths(PathSelectors.any()) + .build() + .apiInfo(getApiInfo()) + ; + } + + private ApiInfo getApiInfo() { + return new ApiInfo( + "Category Service API", + " Service API Category test", + "1.0", + "", + new Contact("Luis Martinez", "", "l.martinezm22@gmail.com"), + "", + "", + Collections.emptyList() + ); + } +} diff --git a/demo/proyect/src/main/java/com/example/demo/controller/IndicatorController.java b/demo/proyect/src/main/java/com/example/demo/controller/IndicatorController.java new file mode 100644 index 0000000..0b3fe15 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/controller/IndicatorController.java @@ -0,0 +1,35 @@ +package com.example.demo.controller; + + +import com.example.demo.dto.ResponseDTO; +import com.example.demo.service.CategoryService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api") +public class IndicatorController { + + private final CategoryService categoryService; + + @Autowired + public IndicatorController(CategoryService categoryService) { + + this.categoryService = categoryService; + } + + @GetMapping + public ResponseEntity getAll() { + + ResponseDTO indicator = categoryService.getAll(); + return new ResponseEntity<>(indicator, HttpStatus.OK); + + } + + + +} diff --git a/demo/proyect/src/main/java/com/example/demo/controller/handler/Controller.java b/demo/proyect/src/main/java/com/example/demo/controller/handler/Controller.java new file mode 100644 index 0000000..daa28c1 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/controller/handler/Controller.java @@ -0,0 +1,38 @@ +package com.example.demo.controller.handler; + + +import com.example.demo.exception.DomainException; +import com.example.demo.exception.ErrorResponse; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + + +@RestControllerAdvice +public class Controller { + + + @ExceptionHandler(NullPointerException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + @ResponseBody + public ResponseEntity handleNotFoundException(DomainException ex) { + return buildResponse(ex); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity generalError(Exception exception) { + + return buildResponse(exception); + } + + private ResponseEntity buildResponse( Object detail) { + + ErrorResponse errorResponse = ErrorResponse.builder() + .message(detail.toString()) + .build(); + return new ResponseEntity<>(errorResponse,HttpStatus.NOT_IMPLEMENTED); + } +} diff --git a/demo/proyect/src/main/java/com/example/demo/controller/handler/CustomErrorDecoder.java b/demo/proyect/src/main/java/com/example/demo/controller/handler/CustomErrorDecoder.java new file mode 100644 index 0000000..be8d478 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/controller/handler/CustomErrorDecoder.java @@ -0,0 +1,94 @@ +package com.example.demo.controller.handler; + + +import com.example.demo.exception.BadRequestException; +import com.example.demo.exception.DomainException; +import com.example.demo.exception.NotFoundException; +import com.example.demo.exception.NotImplementedException; +import com.example.demo.properties.PropertiesFeign; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import feign.Response; +import feign.codec.ErrorDecoder; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.naming.ServiceUnavailableException; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.util.stream.Collectors; + + +@Slf4j +public class CustomErrorDecoder implements ErrorDecoder { + + + private final PropertiesFeign propertiesFeign; + + + @Autowired + public CustomErrorDecoder(PropertiesFeign propertiesFeign){ + this.propertiesFeign=propertiesFeign; + } + + @Override + public Exception decode(String methodKey, Response response) { + + String reader = null; + try { + reader = extractErrorMessage(readFromReader(response.body().asReader(StandardCharsets.UTF_8))); + } catch (IOException e) { + throw new DomainException(propertiesFeign.getGenericError()); + } + + switch (response.status()){ + case 400 : + return new BadRequestException(reader); + case 404: + return new NotFoundException(reader); + case 500: + return new NotImplementedException(reader); + default: + return new ServiceUnavailableException(propertiesFeign.getGenericError()); + } + + } + + private String readFromReader(Reader reader) { + + try (BufferedReader bufferedReader = new BufferedReader(reader)) { + return bufferedReader.lines() + .collect(Collectors.joining()); + } + catch (IOException e) { + throw new DomainException(propertiesFeign.getGenericError()); + } + + } + + private String extractErrorMessage(String jsonResponse) { + try { + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.readTree(jsonResponse); + + if (jsonNode.has(propertiesFeign.getMessage())) { + String message = jsonNode.get(propertiesFeign.getMessage()).asText(); + if (message != null && message.startsWith("{") && message.endsWith("}")) { + JsonNode internalMessageNode = objectMapper.readTree(message); + if (internalMessageNode.has(propertiesFeign.getMessage())) { + return internalMessageNode.get(propertiesFeign.getMessage()).asText(); + } + } else { + return message; + } + } + } catch (Exception e) { + log.error(" error en método extractErrorMessage {}",e.getMessage()); + } + + return null; + } +} + diff --git a/demo/proyect/src/main/java/com/example/demo/dto/CategoryBase.java b/demo/proyect/src/main/java/com/example/demo/dto/CategoryBase.java new file mode 100644 index 0000000..d17b778 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/dto/CategoryBase.java @@ -0,0 +1,16 @@ +package com.example.demo.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.List; + +@JsonPropertyOrder({ "id", "name", "relevance", "subcategories" }) +@EqualsAndHashCode(callSuper = true) +@Data +public class CategoryBase extends CategoryBaseExtends{ + @JsonProperty("subcategories") + private List subcategories; +} diff --git a/demo/proyect/src/main/java/com/example/demo/dto/CategoryBaseExtends.java b/demo/proyect/src/main/java/com/example/demo/dto/CategoryBaseExtends.java new file mode 100644 index 0000000..3339a97 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/dto/CategoryBaseExtends.java @@ -0,0 +1,18 @@ +package com.example.demo.dto; + + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.Data; +import lombok.EqualsAndHashCode; + + + +@JsonPropertyOrder({ "id", "name", "relevance" }) +@EqualsAndHashCode +@Data +public class CategoryBaseExtends { + private String id; + private String name; + private int relevance; +} + diff --git a/demo/proyect/src/main/java/com/example/demo/dto/ResponseDTO.java b/demo/proyect/src/main/java/com/example/demo/dto/ResponseDTO.java new file mode 100644 index 0000000..a6ce5e0 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/dto/ResponseDTO.java @@ -0,0 +1,19 @@ +package com.example.demo.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.List; + + +@JsonPropertyOrder({ "id", "name", "relevance", "subcategories" }) +@EqualsAndHashCode(callSuper = true) +@Data +public class ResponseDTO extends CategoryBaseExtends { + + @JsonProperty("subcategories") + private List subcategories; + +} diff --git a/demo/proyect/src/main/java/com/example/demo/dto/SubcategoryDTO.java b/demo/proyect/src/main/java/com/example/demo/dto/SubcategoryDTO.java new file mode 100644 index 0000000..1aea782 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/dto/SubcategoryDTO.java @@ -0,0 +1,34 @@ +package com.example.demo.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import java.util.List; + + + +@JsonPropertyOrder({ "id", "name", "relevance", "subcategories","iconImageUrl" }) +@EqualsAndHashCode(callSuper = true) +@Data +public class SubcategoryDTO extends CategoryBaseExtends{ + + + @JsonProperty("subcategories") + private List subcategories; + private String iconImageUrl; + + @EqualsAndHashCode(callSuper = true) + @JsonPropertyOrder({ "id", "name", "relevance", "subcategories","mediumImageUrl","mediumImageUrl","smallImageUrl" }) + @Data + static class SubLastCategory extends CategoryBaseExtends{ + + @JsonProperty("subcategories") + private List subcategories; + + private String largeImageUrl; + private String mediumImageUrl; + private String smallImageUrl; + + } +} diff --git a/demo/proyect/src/main/java/com/example/demo/exception/BadRequestException.java b/demo/proyect/src/main/java/com/example/demo/exception/BadRequestException.java new file mode 100644 index 0000000..4d4ebed --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/exception/BadRequestException.java @@ -0,0 +1,14 @@ +package com.example.demo.exception; + +public class BadRequestException extends RuntimeException { + + public BadRequestException(String str) { + + super(str); + } + + @Override + public String toString() { + return getMessage(); + } +} diff --git a/demo/proyect/src/main/java/com/example/demo/exception/DomainException.java b/demo/proyect/src/main/java/com/example/demo/exception/DomainException.java new file mode 100644 index 0000000..26cd37c --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/exception/DomainException.java @@ -0,0 +1,15 @@ +package com.example.demo.exception; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class DomainException extends RuntimeException{ + + private final String code; + + public DomainException(String arg) { + this.code = arg; + } +} diff --git a/demo/proyect/src/main/java/com/example/demo/exception/ErrorResponse.java b/demo/proyect/src/main/java/com/example/demo/exception/ErrorResponse.java new file mode 100644 index 0000000..8e0baf5 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/exception/ErrorResponse.java @@ -0,0 +1,17 @@ +package com.example.demo.exception; + +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@Builder +public class ErrorResponse { + + private String message; + + public ErrorResponse(String message) { + this.message = message; + } +} diff --git a/demo/proyect/src/main/java/com/example/demo/exception/NotFoundException.java b/demo/proyect/src/main/java/com/example/demo/exception/NotFoundException.java new file mode 100644 index 0000000..dcf9baf --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/exception/NotFoundException.java @@ -0,0 +1,14 @@ +package com.example.demo.exception; + +public class NotFoundException extends RuntimeException { + + public NotFoundException(String str) { + + super(str); + } + + @Override + public String toString() { + return getMessage(); + } +} diff --git a/demo/proyect/src/main/java/com/example/demo/exception/NotImplementedException.java b/demo/proyect/src/main/java/com/example/demo/exception/NotImplementedException.java new file mode 100644 index 0000000..ca40c83 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/exception/NotImplementedException.java @@ -0,0 +1,14 @@ +package com.example.demo.exception; + +public class NotImplementedException extends RuntimeException { + + public NotImplementedException(String str) { + + super(str); + } + + @Override + public String toString() { + return getMessage(); + } +} diff --git a/demo/proyect/src/main/java/com/example/demo/feign/CategoryFeignClient.java b/demo/proyect/src/main/java/com/example/demo/feign/CategoryFeignClient.java new file mode 100644 index 0000000..1228654 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/feign/CategoryFeignClient.java @@ -0,0 +1,14 @@ +package com.example.demo.feign; + +import com.example.demo.dto.ResponseDTO; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; + +@FeignClient(name = "indicatorClient", url = "${demo.feign.externalServer.url}") +public interface CategoryFeignClient { + + @GetMapping("/categories") + ResponseDTO getAll(); + + +} \ No newline at end of file diff --git a/demo/proyect/src/main/java/com/example/demo/properties/PropertiesFeign.java b/demo/proyect/src/main/java/com/example/demo/properties/PropertiesFeign.java new file mode 100644 index 0000000..36322e6 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/properties/PropertiesFeign.java @@ -0,0 +1,16 @@ +package com.example.demo.properties; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@Data +@ConfigurationProperties(prefix = "demo.feign") +public class PropertiesFeign { + + + private String message; + + private String genericError; +} diff --git a/demo/proyect/src/main/java/com/example/demo/service/CategoryService.java b/demo/proyect/src/main/java/com/example/demo/service/CategoryService.java new file mode 100644 index 0000000..826bc18 --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/service/CategoryService.java @@ -0,0 +1,9 @@ +package com.example.demo.service; + + +import com.example.demo.dto.ResponseDTO; + +public interface CategoryService { + ResponseDTO getAll(); + +} diff --git a/demo/proyect/src/main/java/com/example/demo/service/CategoryServiceImpl.java b/demo/proyect/src/main/java/com/example/demo/service/CategoryServiceImpl.java new file mode 100644 index 0000000..e75b5ef --- /dev/null +++ b/demo/proyect/src/main/java/com/example/demo/service/CategoryServiceImpl.java @@ -0,0 +1,61 @@ +package com.example.demo.service; + + +import com.example.demo.dto.CategoryBase; +import com.example.demo.dto.ResponseDTO; +import com.example.demo.dto.SubcategoryDTO; +import com.example.demo.feign.CategoryFeignClient; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Comparator; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +@Service +@Slf4j +public class CategoryServiceImpl implements CategoryService { + + + private final CategoryFeignClient categoryFeignClient; + + @Autowired + public CategoryServiceImpl(CategoryFeignClient categoryFeignClient) { + this.categoryFeignClient = categoryFeignClient; + } + + @Override + public ResponseDTO getAll() { + log.info(" Método getAll "); + + ResponseDTO responseDTO = categoryFeignClient.getAll(); + List topSubcategories = getTopSubcategories(responseDTO.getSubcategories()); + + responseDTO.getSubcategories().stream() + .findFirst() + .ifPresent(subcategoryDTO -> subcategoryDTO.setSubcategories(topSubcategories)); + + return responseDTO; + + } + + + private List getTopSubcategories(List categories) { + + + Predicate hasSubcategories = subcategory -> subcategory.getSubcategories() != null; + Comparator byRelevanceDesc = Comparator.comparingInt(SubcategoryDTO::getRelevance).reversed(); + + + return categories.stream() + .flatMap(category -> category.getSubcategories().stream()) + .filter(hasSubcategories) + .sorted(byRelevanceDesc) + .limit(5) + .collect(Collectors.toList()); + + } + +} diff --git a/demo/proyect/src/main/resources/application.properties b/demo/proyect/src/main/resources/application.properties new file mode 100644 index 0000000..56bc954 --- /dev/null +++ b/demo/proyect/src/main/resources/application.properties @@ -0,0 +1,8 @@ +# ************* SWAGGER ######### +spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER + +demo.feign.externalServer.url = https://cs-hsa-api-categories-rest.herokuapp.com/ + + + +demo.feign.generic.error =Generic error