diff --git a/.classpath b/.classpath new file mode 100644 index 00000000..79126acf --- /dev/null +++ b/.classpath @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..a0e65a8a --- /dev/null +++ b/.gitignore @@ -0,0 +1,93 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath +.recommenders + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# PyDev specific (Python IDE for Eclipse) +*.pydevproject + +# CDT-specific (C/C++ Development Tooling) +.cproject + +# CDT- autotools +.autotools + +# Java annotation processor (APT) +.factorypath + +# PDT-specific (PHP Development Tools) +.buildpath + +# sbteclipse plugin +.target + +# Tern plugin +.tern-project + +# TeXlipse plugin +.texlipse + +# STS (Spring Tool Suite) +.springBeans + +# Code Recommenders +.recommenders/ + +# Annotation Processing +.apt_generated/ +.apt_generated_test/ + +# Scala IDE specific (Scala & Java development for Eclipse) +.cache-main +.scala_dependencies +.worksheet + +# Gradle +.gradle/ +!gradle/wrapper/gradle-wrapper.jar + +# Uncomment this line if you wish to ignore the project description file. +# Typically, this file would be tracked if it contains build/dependency configurations: +#.project + +## ignoring target file +target/ + +# End of https://mrkandreev.name/snippets/gitignore-generator/#Java,Eclipse,Java-Web \ No newline at end of file diff --git a/.project b/.project new file mode 100644 index 00000000..5c7ad3ea --- /dev/null +++ b/.project @@ -0,0 +1,28 @@ + + + java-recruiting-hsa + Project java-recruiting-hsa created by Buildship. + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.buildship.core.gradleprojectbuilder + + + + + org.springframework.ide.eclipse.boot.validation.springbootbuilder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.buildship.core.gradleprojectnature + + diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..c99cff9b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,4 @@ +FROM amazoncorretto:11 +EXPOSE 8080 +COPY build/libs/java-recruiting-hsa-0.0.1-SNAPSHOT.jar java-recruiting-hsa-0.0.1-SNAPSHOT.jar +ENTRYPOINT ["java","-jar","/java-recruiting-hsa-0.0.1-SNAPSHOT.jar"] \ No newline at end of file diff --git a/HELP.md b/HELP.md new file mode 100644 index 00000000..626251cc --- /dev/null +++ b/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/2.7.5/gradle-plugin/reference/html/) +* [Create an OCI image](https://docs.spring.io/spring-boot/docs/2.7.5/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/README.md b/README.md index ccc33de5..e511d94d 100644 --- a/README.md +++ b/README.md @@ -1,76 +1,87 @@ -# Desafio Java Concrete - -Desafio técnico para evaluar el conocimiento de los aspirantes a unirse al equipo de **Backend**. - -## Contenido -- [El Desafio](#el-desafio) - - [Escenario](#escenario) - - [APIs](#apis) - - [Features](#features) - - [Puntos a Considerar](#puntos-a-considerar) -- [¿Qué nos Gustaría Ver?](#qué-nos-gustaría-ver) - - [Deseables](#deseables) - - [Stack/Pool de Tecnologías](#stackpool-de-tecnologías) -- [Forma de Entrega](#forma-de-entrega) -- [Importante](#importante) - -## El Desafio - -### Escenario -Recientemente te has unido a un equipo que esta desarrollando una aplicación mobile para una gran compañía de e-commerce. -Esta aplicación esta dirigida a dispositivos de **bajo rendimiento** hasta dispositivos con **gran poder de procesamiento**. -El cliente ya cuenta con un backend establecido que contiene todas las reglas e información de negocio, pero algunos sistemas dependen de **tecnologías legadas** que pueden ser **inestables**. -**Tu** eres responsable de construir la **API** que integrará con estos servicios y proveerá todas las informaciones que Mobile necesita. -Para las próximas iteraciones, el equipo va a trabajar en la **Pantalla de Início** y tu debes construir todo(s) los **endpoint(s)** que se requieran para integrar con los servicios y proveer la información para la pantalla. - -### APIs -Necesitarás consumir los siguientes servicios: -- **Categorias**: [https://cs-hsa-api-categories-rest.herokuapp.com/docs](https://cs-hsa-api-categories-rest.herokuapp.com/docs) -- **Cupones**: [https://cs-hsa-api-coupons-rest.herokuapp.com/docs](https://cs-hsa-api-coupons-rest.herokuapp.com/docs) - -### Features -El equipo Mobile necesita construir una pantalla de inicio que debe mostrar: - -- Carrusel con **Top 5** categorias. -- Carrusel con cupones que no han expirado. -- Tabla (Grid) con las categorias **restantes**. -- Mobile **no** necesita de todas las imagenes del modelo de subcategorías, solamente la **imagen más pequeña**. Tu podrías tener que filtrar la respuesta, si tu quieres. - -### Puntos a Considerar -- La API de Cupones es **inestable** y a veces demora en responder. ¿Qué podemos hacer para que este problema no se replique en otras capas? ¿Habrá algún patrón que nos ayude? -- La API de Categorias responde un modelo complejo de manejar. ¿Qué podríamos hacer para simplificar este modelo y que las integraciones con su aplicación sean más sencillas? - -## ¿Qué nos Gustaría Ver? -Eres libre para implementar la solución de la forma que consideres mejor, -pero debes considerar el escenario, objetivo, implicaciones de performance y stack/pool de tecnología propuesta abajo. -- Nos enfocamos mucho en la **calidad** de nuestros proyectos y nos gustaría ver alguna estrategia aplicada. Puedes usar, por ejemplo, **Pruebas Unitárias**. -- No queremos que la experiencia de usuario se vea afectada por el rendimiento de los servicios; -- **Usted tiene 1 semana para completar el desafio**. Si necesitas mas tiempo, no hay problema, puede hablar con nosotros y veremos que podemos hacer :) -- Documentación de como configurar y ejecutar el proyecto. Puede sobrescribir el **README.md** para eso. - -### Deseables -- Podría ser bueno una documentación de API. Sugerencia: [Swagger](https://swagger.io/). -- Ejecutando con [Docker](https://www.docker.com/). - -### Stack/Pool de Tecnologías -- **Java 8** o **superiores**. -- Cualquier Framework Web. Sugerencia: [Spring Boot](https://spring.io/projects/spring-boot). -- Cualquier API Client. Sugerencia: [Feign](https://github.com/OpenFeign/feign). -- De preferencia [Gradle](https://gradle.org/) como sistema de compilación. -- Tu eres libre para escoger librerias y frameworks de pruebas que mas te guste. Nuestra sugerencia es: [JUnit](https://junit.org/junit5/), [Mockito](https://site.mockito.org/). - ---- - -## Forma de Entrega -Siga los siguientes pasos para implementar y enviar este desafío: -- Haga un **Fork** a este repositorio. Puedes mirar esta guía para mayores informaciones: [Como hacer fork de un repositorio](https://help.github.com/en/articles/fork-a-repo). -- Implemente el desafío. -- Después de completar el desafío, realice un **Pull Request** a este repositorio, utilizando la interface de **Github**. [Creando un Pull Request](https://help.github.com/en/articles/creating-a-pull-request-from-a-fork). -- Si es posible, deja tu repositorio publico para hacer la revisión de código más sencilla. - -## Importante -**No** intente hacer un PUSH directo a ESTE repositorio! - ---- +# Desafio Java Concrete - Javier Vergara + +Api Rest para backend aplicación ecommerce + +### Tecnologías utilizadas + +- Java 11 +- Spring Boot +- Swagger +- Feign +- Lombok +- Docker + +### Instrucciones + +- Se requiere Java 11+. + +- Ingresar a ruta base del proyecto y ejecutar lo siguiente por terminal, en el mismo orden en que aparecen: + +```sh + +./gradlew clean + +./gradlew build + +./gradlew bootRun +``` +- Una vez ejecutada la instrucción anterior la API ya estará inicializada. + +- Se incluye documentación gráfica por medio de Swagger en la ruta: + +``` +http://localhost:8080/swagger-ecommerce-app.html + +``` + +- Para listar cupones no expirados (fecha de expiración mayor a la actual) realizar llamada GET a endpoint: + +``` +http://localhost:8080/coupons +``` + +- Para listar Top 5 categorías según su relevancia realizar llamada GET a endpoint: + +``` +http://localhost:8080/categories/top +``` + +- Para listar las categorías no Top 5 según su relevancia realizar llamada GET a endpoint: + +``` +http://localhost:8080/categories/notop +``` + +### Ejecutar test del proyecto + +- Ingresar a ruta base del proyecto y ejecutar lo siguiente por terminal + +```bash +./gradlew cleanTest test -i +``` +Luego revisar el siguiente archivo para ver los resultados : + +- java-recruiting-hsa/build/reports/tests/test/index.html + +### Instrucciones Docker + + Para construir la imagen Docker + + ``` +docker build -t "ecommerce_backend" . + ``` + + Para levantar contenedor de imagen Docker creada + + ``` +docker run -p 9090:8080 --name ecommerce_backend ecommerce_backend:latest + ``` + + - Se incluye documentación gráfica por medio de Swagger en la ruta: + +``` +http://localhost:9090/swagger-ecommerce-app.html + +``` \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..dfbfa7f5 --- /dev/null +++ b/build.gradle @@ -0,0 +1,33 @@ +plugins { + id 'org.springframework.boot' version '2.7.5' + id 'io.spring.dependency-management' version '1.0.15.RELEASE' + id 'java' +} + +group = 'com.ecommerce' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '11' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + + compileOnly 'org.projectlombok:lombok:1.18.24' + annotationProcessor 'org.projectlombok:lombok:1.18.24' + + testCompileOnly 'org.projectlombok:lombok:1.18.24' + testAnnotationProcessor 'org.projectlombok:lombok:1.18.24' + + implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.5.12' + + implementation 'org.springframework.cloud:spring-cloud-starter-openfeign:3.1.5' + +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/build/bootJarMainClassName b/build/bootJarMainClassName new file mode 100644 index 00000000..cd11ea4b --- /dev/null +++ b/build/bootJarMainClassName @@ -0,0 +1 @@ +com.ecommerce.JavaRecruitingHsaApplication \ No newline at end of file diff --git a/build/bootRunMainClassName b/build/bootRunMainClassName new file mode 100644 index 00000000..cd11ea4b --- /dev/null +++ b/build/bootRunMainClassName @@ -0,0 +1 @@ +com.ecommerce.JavaRecruitingHsaApplication \ No newline at end of file diff --git a/build/reports/tests/test/classes/com.ecommerce.JavaRecruitingHsaApplicationTests.html b/build/reports/tests/test/classes/com.ecommerce.JavaRecruitingHsaApplicationTests.html new file mode 100644 index 00000000..f22f513a --- /dev/null +++ b/build/reports/tests/test/classes/com.ecommerce.JavaRecruitingHsaApplicationTests.html @@ -0,0 +1,111 @@ + + + + + +Test results - JavaRecruitingHsaApplicationTests + + + + + +
+

JavaRecruitingHsaApplicationTests

+ +
+ + + + + +
+
+ + + + + + + +
+
+
1
+

tests

+
+
+
+
0
+

failures

+
+
+
+
0
+

ignored

+
+
+
+
0.010s
+

duration

+
+
+
+
+
+
100%
+

successful

+
+
+
+
+ +
+

Tests

+ + + + + + + + + + + + + +
TestDurationResult
contextLoads()0.010spassed
+
+
+

Standard output

+ +
2022-11-12 19:43:03.476  INFO 83620 --- [    Test worker] .b.t.c.SpringBootTestContextBootstrapper : Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.ecommerce.JavaRecruitingHsaApplicationTests], using SpringBootContextLoader
+2022-11-12 19:43:03.480  INFO 83620 --- [    Test worker] o.s.t.c.support.AbstractContextLoader    : Could not detect default resource locations for test class [com.ecommerce.JavaRecruitingHsaApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
+2022-11-12 19:43:03.480  INFO 83620 --- [    Test worker] t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default configuration classes for test class [com.ecommerce.JavaRecruitingHsaApplicationTests]: JavaRecruitingHsaApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
+2022-11-12 19:43:03.502  INFO 83620 --- [    Test worker] .b.t.c.SpringBootTestContextBootstrapper : Found @SpringBootConfiguration com.ecommerce.JavaRecruitingHsaApplication for test class com.ecommerce.JavaRecruitingHsaApplicationTests
+2022-11-12 19:43:03.514  INFO 83620 --- [    Test worker] .b.t.c.SpringBootTestContextBootstrapper : Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
+2022-11-12 19:43:03.516  INFO 83620 --- [    Test worker] .b.t.c.SpringBootTestContextBootstrapper : Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@42d0e41, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@50f05307, org.springframework.test.context.event.ApplicationEventsTestExecutionListener@9cc0505, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@645d4639, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@8ee03f5, org.springframework.test.context.support.DirtiesContextTestExecutionListener@5ad40184, org.springframework.test.context.event.EventPublishingTestExecutionListener@3359c3f6, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@3d3b272a, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@45b27ad3, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@3f908bc0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@422ba9b7, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@26cdd4af, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@707f4647]
+
+
+
+
+ +
+ + diff --git a/build/reports/tests/test/classes/com.ecommerce.controller.CategoriesControllerTest.html b/build/reports/tests/test/classes/com.ecommerce.controller.CategoriesControllerTest.html new file mode 100644 index 00000000..fec7a51c --- /dev/null +++ b/build/reports/tests/test/classes/com.ecommerce.controller.CategoriesControllerTest.html @@ -0,0 +1,116 @@ + + + + + +Test results - CategoriesControllerTest + + + + + +
+

CategoriesControllerTest

+ +
+ + + + + +
+
+ + + + + + + +
+
+
2
+

tests

+
+
+
+
0
+

failures

+
+
+
+
0
+

ignored

+
+
+
+
1.730s
+

duration

+
+
+
+
+
+
100%
+

successful

+
+
+
+
+ +
+

Tests

+ + + + + + + + + + + + + + + + + + +
TestDurationResult
testGetExceptTopFive()0.693spassed
testGetTopFive()1.037spassed
+
+
+

Standard output

+ +
2022-11-12 19:43:03.553  INFO 83620 --- [    Test worker] .b.t.c.SpringBootTestContextBootstrapper : Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.ecommerce.controller.CategoriesControllerTest], using SpringBootContextLoader
+2022-11-12 19:43:03.554  INFO 83620 --- [    Test worker] o.s.t.c.support.AbstractContextLoader    : Could not detect default resource locations for test class [com.ecommerce.controller.CategoriesControllerTest]: no resource found for suffixes {-context.xml, Context.groovy}.
+2022-11-12 19:43:03.554  INFO 83620 --- [    Test worker] t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default configuration classes for test class [com.ecommerce.controller.CategoriesControllerTest]: CategoriesControllerTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
+2022-11-12 19:43:03.558  INFO 83620 --- [    Test worker] .b.t.c.SpringBootTestContextBootstrapper : Found @SpringBootConfiguration com.ecommerce.JavaRecruitingHsaApplication for test class com.ecommerce.controller.CategoriesControllerTest
+2022-11-12 19:43:03.563  INFO 83620 --- [    Test worker] .b.t.c.SpringBootTestContextBootstrapper : Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
+2022-11-12 19:43:03.564  INFO 83620 --- [    Test worker] .b.t.c.SpringBootTestContextBootstrapper : Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@4b8a0d03, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@54f373d4, org.springframework.test.context.event.ApplicationEventsTestExecutionListener@1c53bd49, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@16949dfa, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@d6d683e, org.springframework.test.context.support.DirtiesContextTestExecutionListener@42cfd794, org.springframework.test.context.event.EventPublishingTestExecutionListener@43778371, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@71beada8, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@17f41739, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@2b3b1124, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@54286339, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@507f47f9, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@6785df10]
+
+
+
+
+ +
+ + diff --git a/build/reports/tests/test/classes/com.ecommerce.controller.CouponsControllerTest.html b/build/reports/tests/test/classes/com.ecommerce.controller.CouponsControllerTest.html new file mode 100644 index 00000000..ac1ce700 --- /dev/null +++ b/build/reports/tests/test/classes/com.ecommerce.controller.CouponsControllerTest.html @@ -0,0 +1,135 @@ + + + + + +Test results - CouponsControllerTest + + + + + +
+

CouponsControllerTest

+ +
+ + + + + +
+
+ + + + + + + +
+
+
1
+

tests

+
+
+
+
0
+

failures

+
+
+
+
0
+

ignored

+
+
+
+
1.791s
+

duration

+
+
+
+
+
+
100%
+

successful

+
+
+
+
+ +
+

Tests

+ + + + + + + + + + + + + +
TestDurationResult
testGetCouponsNotExpired()1.791spassed
+
+
+

Standard output

+ +
19:42:55.890 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
+19:42:55.901 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
+19:42:55.946 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.ecommerce.controller.CouponsControllerTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
+19:42:55.956 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.ecommerce.controller.CouponsControllerTest], using SpringBootContextLoader
+19:42:55.959 [Test worker] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.ecommerce.controller.CouponsControllerTest]: class path resource [com/ecommerce/controller/CouponsControllerTest-context.xml] does not exist
+19:42:55.959 [Test worker] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.ecommerce.controller.CouponsControllerTest]: class path resource [com/ecommerce/controller/CouponsControllerTestContext.groovy] does not exist
+19:42:55.959 [Test worker] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.ecommerce.controller.CouponsControllerTest]: no resource found for suffixes {-context.xml, Context.groovy}.
+19:42:55.960 [Test worker] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.ecommerce.controller.CouponsControllerTest]: CouponsControllerTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
+19:42:56.011 [Test worker] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.ecommerce.controller.CouponsControllerTest]
+19:42:56.187 [Test worker] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [/Users/javiervergara/Downloads/Codigo/java-recruiting-hsa/build/classes/java/main/com/ecommerce/JavaRecruitingHsaApplication.class]
+19:42:56.192 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.ecommerce.JavaRecruitingHsaApplication for test class com.ecommerce.controller.CouponsControllerTest
+19:42:56.280 [Test worker] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.ecommerce.controller.CouponsControllerTest]: using defaults.
+19:42:56.280 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
+19:42:56.291 [Test worker] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
+19:42:56.292 [Test worker] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
+19:42:56.293 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@293d0107, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@2692b61e, org.springframework.test.context.event.ApplicationEventsTestExecutionListener@7b64240d, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@62fad19, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@47dbb1e2, org.springframework.test.context.support.DirtiesContextTestExecutionListener@74cadd41, org.springframework.test.context.event.EventPublishingTestExecutionListener@2e54db99, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@55e8ec2f, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@4f2613d1, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@6d24ffa1, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@65a4798f, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@773f7880, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@878452d]
+19:42:56.296 [Test worker] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@5ddabb18 testClass = CouponsControllerTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@3e8f7922 testClass = CouponsControllerTest, locations = '{}', classes = '{class com.ecommerce.JavaRecruitingHsaApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@17d88132, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@1339e7aa, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@12359a82, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@5be46f9d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@15713d56, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@399c4be1], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].
+
+  .   ____          _            __ _ _
+ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
+( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
+ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
+  '  |____| .__|_| |_|_| |_\__, | / / / /
+ =========|_|==============|___/=/_/_/_/
+ :: Spring Boot ::                (v2.7.5)
+
+2022-11-12 19:42:56.828  INFO 83620 --- [    Test worker] c.e.controller.CouponsControllerTest     : Starting CouponsControllerTest using Java 17.0.3 on MacBook-Air-de-Javier.local with PID 83620 (started by javiervergara in /Users/javiervergara/Downloads/Codigo/java-recruiting-hsa)
+2022-11-12 19:42:56.830  INFO 83620 --- [    Test worker] c.e.controller.CouponsControllerTest     : No active profile set, falling back to 1 default profile: "default"
+2022-11-12 19:42:58.047  INFO 83620 --- [    Test worker] o.s.cloud.context.scope.GenericScope     : BeanFactory id=edc87954-e58d-317a-91be-36f00454a58a
+2022-11-12 19:43:01.638  INFO 83620 --- [    Test worker] c.e.controller.CouponsControllerTest     : Started CouponsControllerTest in 5.276 seconds (JVM running for 6.733)
+
+
+
+
+ +
+ + diff --git a/build/reports/tests/test/css/base-style.css b/build/reports/tests/test/css/base-style.css new file mode 100644 index 00000000..4afa73e3 --- /dev/null +++ b/build/reports/tests/test/css/base-style.css @@ -0,0 +1,179 @@ + +body { + margin: 0; + padding: 0; + font-family: sans-serif; + font-size: 12pt; +} + +body, a, a:visited { + color: #303030; +} + +#content { + padding-left: 50px; + padding-right: 50px; + padding-top: 30px; + padding-bottom: 30px; +} + +#content h1 { + font-size: 160%; + margin-bottom: 10px; +} + +#footer { + margin-top: 100px; + font-size: 80%; + white-space: nowrap; +} + +#footer, #footer a { + color: #a0a0a0; +} + +#line-wrapping-toggle { + vertical-align: middle; +} + +#label-for-line-wrapping-toggle { + vertical-align: middle; +} + +ul { + margin-left: 0; +} + +h1, h2, h3 { + white-space: nowrap; +} + +h2 { + font-size: 120%; +} + +ul.tabLinks { + padding-left: 0; + padding-top: 10px; + padding-bottom: 10px; + overflow: auto; + min-width: 800px; + width: auto !important; + width: 800px; +} + +ul.tabLinks li { + float: left; + height: 100%; + list-style: none; + padding-left: 10px; + padding-right: 10px; + padding-top: 5px; + padding-bottom: 5px; + margin-bottom: 0; + -moz-border-radius: 7px; + border-radius: 7px; + margin-right: 25px; + border: solid 1px #d4d4d4; + background-color: #f0f0f0; +} + +ul.tabLinks li:hover { + background-color: #fafafa; +} + +ul.tabLinks li.selected { + background-color: #c5f0f5; + border-color: #c5f0f5; +} + +ul.tabLinks a { + font-size: 120%; + display: block; + outline: none; + text-decoration: none; + margin: 0; + padding: 0; +} + +ul.tabLinks li h2 { + margin: 0; + padding: 0; +} + +div.tab { +} + +div.selected { + display: block; +} + +div.deselected { + display: none; +} + +div.tab table { + min-width: 350px; + width: auto !important; + width: 350px; + border-collapse: collapse; +} + +div.tab th, div.tab table { + border-bottom: solid #d0d0d0 1px; +} + +div.tab th { + text-align: left; + white-space: nowrap; + padding-left: 6em; +} + +div.tab th:first-child { + padding-left: 0; +} + +div.tab td { + white-space: nowrap; + padding-left: 6em; + padding-top: 5px; + padding-bottom: 5px; +} + +div.tab td:first-child { + padding-left: 0; +} + +div.tab td.numeric, div.tab th.numeric { + text-align: right; +} + +span.code { + display: inline-block; + margin-top: 0em; + margin-bottom: 1em; +} + +span.code pre { + font-size: 11pt; + padding-top: 10px; + padding-bottom: 10px; + padding-left: 10px; + padding-right: 10px; + margin: 0; + background-color: #f7f7f7; + border: solid 1px #d0d0d0; + min-width: 700px; + width: auto !important; + width: 700px; +} + +span.wrapped pre { + word-wrap: break-word; + white-space: pre-wrap; + word-break: break-all; +} + +label.hidden { + display: none; +} \ No newline at end of file diff --git a/build/reports/tests/test/css/style.css b/build/reports/tests/test/css/style.css new file mode 100644 index 00000000..3dc4913e --- /dev/null +++ b/build/reports/tests/test/css/style.css @@ -0,0 +1,84 @@ + +#summary { + margin-top: 30px; + margin-bottom: 40px; +} + +#summary table { + border-collapse: collapse; +} + +#summary td { + vertical-align: top; +} + +.breadcrumbs, .breadcrumbs a { + color: #606060; +} + +.infoBox { + width: 110px; + padding-top: 15px; + padding-bottom: 15px; + text-align: center; +} + +.infoBox p { + margin: 0; +} + +.counter, .percent { + font-size: 120%; + font-weight: bold; + margin-bottom: 8px; +} + +#duration { + width: 125px; +} + +#successRate, .summaryGroup { + border: solid 2px #d0d0d0; + -moz-border-radius: 10px; + border-radius: 10px; +} + +#successRate { + width: 140px; + margin-left: 35px; +} + +#successRate .percent { + font-size: 180%; +} + +.success, .success a { + color: #008000; +} + +div.success, #successRate.success { + background-color: #bbd9bb; + border-color: #008000; +} + +.failures, .failures a { + color: #b60808; +} + +.skipped, .skipped a { + color: #c09853; +} + +div.failures, #successRate.failures { + background-color: #ecdada; + border-color: #b60808; +} + +ul.linkList { + padding-left: 0; +} + +ul.linkList li { + list-style: none; + margin-bottom: 5px; +} diff --git a/build/reports/tests/test/index.html b/build/reports/tests/test/index.html new file mode 100644 index 00000000..420b5318 --- /dev/null +++ b/build/reports/tests/test/index.html @@ -0,0 +1,163 @@ + + + + + +Test results - Test Summary + + + + + +
+

Test Summary

+
+ + + + + +
+
+ + + + + + + +
+
+
4
+

tests

+
+
+
+
0
+

failures

+
+
+
+
0
+

ignored

+
+
+
+
3.531s
+

duration

+
+
+
+
+
+
100%
+

successful

+
+
+
+
+ +
+

Packages

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PackageTestsFailuresIgnoredDurationSuccess rate
+com.ecommerce +1000.010s100%
+com.ecommerce.controller +3003.521s100%
+
+
+

Classes

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ClassTestsFailuresIgnoredDurationSuccess rate
+com.ecommerce.JavaRecruitingHsaApplicationTests +1000.010s100%
+com.ecommerce.controller.CategoriesControllerTest +2001.730s100%
+com.ecommerce.controller.CouponsControllerTest +1001.791s100%
+
+
+ +
+ + diff --git a/build/reports/tests/test/js/report.js b/build/reports/tests/test/js/report.js new file mode 100644 index 00000000..83bab4a1 --- /dev/null +++ b/build/reports/tests/test/js/report.js @@ -0,0 +1,194 @@ +(function (window, document) { + "use strict"; + + var tabs = {}; + + function changeElementClass(element, classValue) { + if (element.getAttribute("className")) { + element.setAttribute("className", classValue); + } else { + element.setAttribute("class", classValue); + } + } + + function getClassAttribute(element) { + if (element.getAttribute("className")) { + return element.getAttribute("className"); + } else { + return element.getAttribute("class"); + } + } + + function addClass(element, classValue) { + changeElementClass(element, getClassAttribute(element) + " " + classValue); + } + + function removeClass(element, classValue) { + changeElementClass(element, getClassAttribute(element).replace(classValue, "")); + } + + function initTabs() { + var container = document.getElementById("tabs"); + + tabs.tabs = findTabs(container); + tabs.titles = findTitles(tabs.tabs); + tabs.headers = findHeaders(container); + tabs.select = select; + tabs.deselectAll = deselectAll; + tabs.select(0); + + return true; + } + + function getCheckBox() { + return document.getElementById("line-wrapping-toggle"); + } + + function getLabelForCheckBox() { + return document.getElementById("label-for-line-wrapping-toggle"); + } + + function findCodeBlocks() { + var spans = document.getElementById("tabs").getElementsByTagName("span"); + var codeBlocks = []; + for (var i = 0; i < spans.length; ++i) { + if (spans[i].className.indexOf("code") >= 0) { + codeBlocks.push(spans[i]); + } + } + return codeBlocks; + } + + function forAllCodeBlocks(operation) { + var codeBlocks = findCodeBlocks(); + + for (var i = 0; i < codeBlocks.length; ++i) { + operation(codeBlocks[i], "wrapped"); + } + } + + function toggleLineWrapping() { + var checkBox = getCheckBox(); + + if (checkBox.checked) { + forAllCodeBlocks(addClass); + } else { + forAllCodeBlocks(removeClass); + } + } + + function initControls() { + if (findCodeBlocks().length > 0) { + var checkBox = getCheckBox(); + var label = getLabelForCheckBox(); + + checkBox.onclick = toggleLineWrapping; + checkBox.checked = false; + + removeClass(label, "hidden"); + } + } + + function switchTab() { + var id = this.id.substr(1); + + for (var i = 0; i < tabs.tabs.length; i++) { + if (tabs.tabs[i].id === id) { + tabs.select(i); + break; + } + } + + return false; + } + + function select(i) { + this.deselectAll(); + + changeElementClass(this.tabs[i], "tab selected"); + changeElementClass(this.headers[i], "selected"); + + while (this.headers[i].firstChild) { + this.headers[i].removeChild(this.headers[i].firstChild); + } + + var h2 = document.createElement("H2"); + + h2.appendChild(document.createTextNode(this.titles[i])); + this.headers[i].appendChild(h2); + } + + function deselectAll() { + for (var i = 0; i < this.tabs.length; i++) { + changeElementClass(this.tabs[i], "tab deselected"); + changeElementClass(this.headers[i], "deselected"); + + while (this.headers[i].firstChild) { + this.headers[i].removeChild(this.headers[i].firstChild); + } + + var a = document.createElement("A"); + + a.setAttribute("id", "ltab" + i); + a.setAttribute("href", "#tab" + i); + a.onclick = switchTab; + a.appendChild(document.createTextNode(this.titles[i])); + + this.headers[i].appendChild(a); + } + } + + function findTabs(container) { + return findChildElements(container, "DIV", "tab"); + } + + function findHeaders(container) { + var owner = findChildElements(container, "UL", "tabLinks"); + return findChildElements(owner[0], "LI", null); + } + + function findTitles(tabs) { + var titles = []; + + for (var i = 0; i < tabs.length; i++) { + var tab = tabs[i]; + var header = findChildElements(tab, "H2", null)[0]; + + header.parentNode.removeChild(header); + + if (header.innerText) { + titles.push(header.innerText); + } else { + titles.push(header.textContent); + } + } + + return titles; + } + + function findChildElements(container, name, targetClass) { + var elements = []; + var children = container.childNodes; + + for (var i = 0; i < children.length; i++) { + var child = children.item(i); + + if (child.nodeType === 1 && child.nodeName === name) { + if (targetClass && child.className.indexOf(targetClass) < 0) { + continue; + } + + elements.push(child); + } + } + + return elements; + } + + // Entry point. + + window.onload = function() { + initTabs(); + initControls(); + }; +} (window, window.document)); \ No newline at end of file diff --git a/build/reports/tests/test/packages/com.ecommerce.controller.html b/build/reports/tests/test/packages/com.ecommerce.controller.html new file mode 100644 index 00000000..0993577d --- /dev/null +++ b/build/reports/tests/test/packages/com.ecommerce.controller.html @@ -0,0 +1,113 @@ + + + + + +Test results - Package com.ecommerce.controller + + + + + +
+

Package com.ecommerce.controller

+ +
+ + + + + +
+
+ + + + + + + +
+
+
3
+

tests

+
+
+
+
0
+

failures

+
+
+
+
0
+

ignored

+
+
+
+
3.521s
+

duration

+
+
+
+
+
+
100%
+

successful

+
+
+
+
+ +
+

Classes

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
ClassTestsFailuresIgnoredDurationSuccess rate
+CategoriesControllerTest +2001.730s100%
+CouponsControllerTest +1001.791s100%
+
+
+ +
+ + diff --git a/build/reports/tests/test/packages/com.ecommerce.html b/build/reports/tests/test/packages/com.ecommerce.html new file mode 100644 index 00000000..ae2e2d64 --- /dev/null +++ b/build/reports/tests/test/packages/com.ecommerce.html @@ -0,0 +1,103 @@ + + + + + +Test results - Package com.ecommerce + + + + + +
+

Package com.ecommerce

+ +
+ + + + + +
+
+ + + + + + + +
+
+
1
+

tests

+
+
+
+
0
+

failures

+
+
+
+
0
+

ignored

+
+
+
+
0.010s
+

duration

+
+
+
+
+
+
100%
+

successful

+
+
+
+
+ +
+

Classes

+ + + + + + + + + + + + + + + + + + + +
ClassTestsFailuresIgnoredDurationSuccess rate
+JavaRecruitingHsaApplicationTests +1000.010s100%
+
+
+ +
+ + diff --git a/build/resources/main/application.properties b/build/resources/main/application.properties new file mode 100644 index 00000000..7d263e3b --- /dev/null +++ b/build/resources/main/application.properties @@ -0,0 +1,11 @@ +categories.api.url=https://cs-hsa-api-categories-rest.herokuapp.com +categories.api.name=categories +coupons.api.url=https://cs-hsa-api-coupons-rest.herokuapp.com +coupons.api.name=coupons +springdoc.swagger-ui.path=/swagger-ecommerce-app.html +feign.client.config.default.connectTimeout=5000 +feign.client.config.default.readTimeout=5000 +feign.client.config.default.loggerLevel=basic +feign.hystrix.enabled=true +feign.httpclient.enabled: true +server.error.include-message=always \ No newline at end of file diff --git a/build/test-results/test/TEST-com.ecommerce.JavaRecruitingHsaApplicationTests.xml b/build/test-results/test/TEST-com.ecommerce.JavaRecruitingHsaApplicationTests.xml new file mode 100644 index 00000000..a1f5d55b --- /dev/null +++ b/build/test-results/test/TEST-com.ecommerce.JavaRecruitingHsaApplicationTests.xml @@ -0,0 +1,13 @@ + + + + + + + diff --git a/build/test-results/test/TEST-com.ecommerce.controller.CategoriesControllerTest.xml b/build/test-results/test/TEST-com.ecommerce.controller.CategoriesControllerTest.xml new file mode 100644 index 00000000..fbc7cc1c --- /dev/null +++ b/build/test-results/test/TEST-com.ecommerce.controller.CategoriesControllerTest.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/build/test-results/test/TEST-com.ecommerce.controller.CouponsControllerTest.xml b/build/test-results/test/TEST-com.ecommerce.controller.CouponsControllerTest.xml new file mode 100644 index 00000000..84f53756 --- /dev/null +++ b/build/test-results/test/TEST-com.ecommerce.controller.CouponsControllerTest.xml @@ -0,0 +1,37 @@ + + + + + true]], class annotated with @DirtiesContext [false] with mode [null]. + + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: (v2.7.5) + +2022-11-12 19:42:56.828 INFO 83620 --- [ Test worker] c.e.controller.CouponsControllerTest : Starting CouponsControllerTest using Java 17.0.3 on MacBook-Air-de-Javier.local with PID 83620 (started by javiervergara in /Users/javiervergara/Downloads/Codigo/java-recruiting-hsa) +2022-11-12 19:42:56.830 INFO 83620 --- [ Test worker] c.e.controller.CouponsControllerTest : No active profile set, falling back to 1 default profile: "default" +2022-11-12 19:42:58.047 INFO 83620 --- [ Test worker] o.s.cloud.context.scope.GenericScope : BeanFactory id=edc87954-e58d-317a-91be-36f00454a58a +2022-11-12 19:43:01.638 INFO 83620 --- [ Test worker] c.e.controller.CouponsControllerTest : Started CouponsControllerTest in 5.276 seconds (JVM running for 6.733) +]]> + + diff --git a/build/test-results/test/binary/output.bin b/build/test-results/test/binary/output.bin new file mode 100644 index 00000000..e1a85d03 Binary files /dev/null and b/build/test-results/test/binary/output.bin differ diff --git a/build/test-results/test/binary/output.bin.idx b/build/test-results/test/binary/output.bin.idx new file mode 100644 index 00000000..09b913fe Binary files /dev/null and b/build/test-results/test/binary/output.bin.idx differ diff --git a/build/test-results/test/binary/results.bin b/build/test-results/test/binary/results.bin new file mode 100644 index 00000000..d6e396a8 Binary files /dev/null and b/build/test-results/test/binary/results.bin differ diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..249e5832 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..ae04661e --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..a69d9cb6 --- /dev/null +++ b/gradlew @@ -0,0 +1,240 @@ +#!/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/master/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# 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 + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +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/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..53a6b238 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,91 @@ +@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=. +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/settings.gradle b/settings.gradle new file mode 100644 index 00000000..479137bb --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'java-recruiting-hsa' diff --git a/src/main/java/com/ecommerce/JavaRecruitingHsaApplication.java b/src/main/java/com/ecommerce/JavaRecruitingHsaApplication.java new file mode 100644 index 00000000..80106787 --- /dev/null +++ b/src/main/java/com/ecommerce/JavaRecruitingHsaApplication.java @@ -0,0 +1,20 @@ +package com.ecommerce; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.openfeign.EnableFeignClients; + +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.info.Info; + +@SpringBootApplication +@EnableFeignClients +@OpenAPIDefinition(info = @Info(title = "Ecommerce API", version = "1.0", description = "Backend app ecommerce")) + +public class JavaRecruitingHsaApplication { + + public static void main(String[] args) { + SpringApplication.run(JavaRecruitingHsaApplication.class, args); + } + +} diff --git a/src/main/java/com/ecommerce/controller/CategoriesController.java b/src/main/java/com/ecommerce/controller/CategoriesController.java new file mode 100644 index 00000000..5090f2f0 --- /dev/null +++ b/src/main/java/com/ecommerce/controller/CategoriesController.java @@ -0,0 +1,48 @@ +package com.ecommerce.controller; + +import java.util.List; + +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.RestController; +import org.springframework.web.server.ResponseStatusException; + +import com.ecommerce.dto.CategoriesDto; +import com.ecommerce.service.CategoriesService; +import com.ecommerce.utils.ConstantesUtils; + +import io.swagger.v3.oas.annotations.Operation; + +@RestController +public class CategoriesController { + + @Autowired + private CategoriesService service; + + @GetMapping("categories/top") + @Operation(summary = "Get top 5 categories") + public ResponseEntity> getTopFive() { + try { + List topFiveCategories = service.getTopFive(); + return ResponseEntity.status(HttpStatus.OK).body(topFiveCategories); + } catch (Exception e) { + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, + ConstantesUtils.ERROR_OBTENER_TOP_CATEGORIAS, e); + } + } + + @GetMapping("categories/notop") + @Operation(summary = "Get categories except top 5") + public ResponseEntity> getExceptTopFive() { + try { + List topFiveCategories = service.getExceptTopFive(); + return ResponseEntity.status(HttpStatus.OK).body(topFiveCategories); + } catch (Exception e) { + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, + ConstantesUtils.ERROR_OBTENER_TOP_CATEGORIAS, e); + } + } + +} diff --git a/src/main/java/com/ecommerce/controller/ControllerAdvice.java b/src/main/java/com/ecommerce/controller/ControllerAdvice.java new file mode 100644 index 00000000..92b5bc91 --- /dev/null +++ b/src/main/java/com/ecommerce/controller/ControllerAdvice.java @@ -0,0 +1,20 @@ +package com.ecommerce.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import com.ecommerce.dto.ErrorDto; + +@RestControllerAdvice +public class ControllerAdvice { + + @ExceptionHandler(value = RuntimeException.class) + public ResponseEntity runtimeExceptionHandler(RuntimeException ex) { + + ErrorDto error = ErrorDto.builder().code("500").message(ex.getMessage()).build(); + return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); + } + +} diff --git a/src/main/java/com/ecommerce/controller/CouponsController.java b/src/main/java/com/ecommerce/controller/CouponsController.java new file mode 100644 index 00000000..bbc4d0fd --- /dev/null +++ b/src/main/java/com/ecommerce/controller/CouponsController.java @@ -0,0 +1,37 @@ +package com.ecommerce.controller; + +import java.util.List; + +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.RestController; +import org.springframework.web.server.ResponseStatusException; + +import com.ecommerce.dto.CouponsDto; +import com.ecommerce.service.CouponsService; +import com.ecommerce.utils.ConstantesUtils; + +import io.swagger.v3.oas.annotations.Operation; + +@RestController +public class CouponsController { + + @Autowired + private CouponsService service; + + @GetMapping("coupons") + @Operation(summary = "Get all coupons") + public ResponseEntity> getCouponsNotExpired() { + + try { + List couponsList = service.getCouponsNotExpired(); + return ResponseEntity.status(HttpStatus.OK).body(couponsList); + } catch (Exception e) { + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, ConstantesUtils.ERROR_OBTENER_CUPONES, + e); + } + } + +} diff --git a/src/main/java/com/ecommerce/dto/CategoriesDto.java b/src/main/java/com/ecommerce/dto/CategoriesDto.java new file mode 100644 index 00000000..9a6b4356 --- /dev/null +++ b/src/main/java/com/ecommerce/dto/CategoriesDto.java @@ -0,0 +1,19 @@ +package com.ecommerce.dto; + +import java.io.Serializable; +import java.util.List; + +import lombok.Data; + +@Data +public class CategoriesDto implements Serializable { + + private static final long serialVersionUID = -1859040533319404780L; + private String id; + private String name; + private int relevance; + private String smallImageUrl; + private String iconImageUrl; + private List subcategories; + +} diff --git a/src/main/java/com/ecommerce/dto/CouponsDto.java b/src/main/java/com/ecommerce/dto/CouponsDto.java new file mode 100644 index 00000000..ac5695dd --- /dev/null +++ b/src/main/java/com/ecommerce/dto/CouponsDto.java @@ -0,0 +1,12 @@ +package com.ecommerce.dto; + +import lombok.Data; + +@Data +public class CouponsDto { + private String id; + private String description; + private String seller; + private String image; + private String expiresAt; +} diff --git a/src/main/java/com/ecommerce/dto/ErrorDto.java b/src/main/java/com/ecommerce/dto/ErrorDto.java new file mode 100644 index 00000000..aa6540ab --- /dev/null +++ b/src/main/java/com/ecommerce/dto/ErrorDto.java @@ -0,0 +1,12 @@ +package com.ecommerce.dto; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class ErrorDto { + + private String code; + private String message; +} diff --git a/src/main/java/com/ecommerce/feign/CategoriesClient.java b/src/main/java/com/ecommerce/feign/CategoriesClient.java new file mode 100644 index 00000000..a6d6861c --- /dev/null +++ b/src/main/java/com/ecommerce/feign/CategoriesClient.java @@ -0,0 +1,18 @@ +package com.ecommerce.feign; + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; + +import com.ecommerce.dto.CategoriesDto; +import com.ecommerce.feign.fallback.CategoriesClientFallback; + +import feign.Headers; + +@FeignClient(name = "${categories.api.name}", url = "${categories.api.url}", fallback = CategoriesClientFallback.class) +@Headers("accept: application/json") +public interface CategoriesClient { + + @GetMapping("/categories") + CategoriesDto getAll(); + +} diff --git a/src/main/java/com/ecommerce/feign/CouponsClient.java b/src/main/java/com/ecommerce/feign/CouponsClient.java new file mode 100644 index 00000000..ad844472 --- /dev/null +++ b/src/main/java/com/ecommerce/feign/CouponsClient.java @@ -0,0 +1,20 @@ +package com.ecommerce.feign; + +import java.util.List; + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; + +import com.ecommerce.dto.CouponsDto; +import com.ecommerce.feign.fallback.CouponsClientFallback; + +import feign.Headers; + +@FeignClient(name = "${coupons.api.name}", url = "${coupons.api.url}", fallback = CouponsClientFallback.class) +public interface CouponsClient { + + @GetMapping("/coupons") + @Headers("accept: application/json") + List getAll(); + +} diff --git a/src/main/java/com/ecommerce/feign/fallback/CategoriesClientFallback.java b/src/main/java/com/ecommerce/feign/fallback/CategoriesClientFallback.java new file mode 100644 index 00000000..96015bf9 --- /dev/null +++ b/src/main/java/com/ecommerce/feign/fallback/CategoriesClientFallback.java @@ -0,0 +1,19 @@ +package com.ecommerce.feign.fallback; + + +import org.springframework.stereotype.Component; + +import com.ecommerce.dto.CategoriesDto; +import com.ecommerce.feign.CategoriesClient; +import com.ecommerce.utils.ConstantesUtils; + +@Component +public class CategoriesClientFallback implements CategoriesClient { + + @Override + public CategoriesDto getAll() { + throw new RuntimeException(ConstantesUtils.ERROR_CONEXION_API_CATEGORIAS); + } + + +} diff --git a/src/main/java/com/ecommerce/feign/fallback/CouponsClientFallback.java b/src/main/java/com/ecommerce/feign/fallback/CouponsClientFallback.java new file mode 100644 index 00000000..6acce5a5 --- /dev/null +++ b/src/main/java/com/ecommerce/feign/fallback/CouponsClientFallback.java @@ -0,0 +1,17 @@ +package com.ecommerce.feign.fallback; + +import java.util.List; + +import org.springframework.stereotype.Component; + +import com.ecommerce.dto.CouponsDto; +import com.ecommerce.feign.CouponsClient; +import com.ecommerce.utils.ConstantesUtils; + +@Component +public class CouponsClientFallback implements CouponsClient { + public List getAll() { + throw new RuntimeException(ConstantesUtils.ERROR_CONEXION_API_CUPONES); + } + +} diff --git a/src/main/java/com/ecommerce/service/CategoriesService.java b/src/main/java/com/ecommerce/service/CategoriesService.java new file mode 100644 index 00000000..55e256f5 --- /dev/null +++ b/src/main/java/com/ecommerce/service/CategoriesService.java @@ -0,0 +1,18 @@ +package com.ecommerce.service; + +import java.util.List; + +import org.springframework.stereotype.Service; + +import com.ecommerce.dto.CategoriesDto; + +@Service +public interface CategoriesService { + + CategoriesDto getAll(); + + List getTopFive(); + + List getExceptTopFive(); + +} diff --git a/src/main/java/com/ecommerce/service/CouponsService.java b/src/main/java/com/ecommerce/service/CouponsService.java new file mode 100644 index 00000000..9b89da00 --- /dev/null +++ b/src/main/java/com/ecommerce/service/CouponsService.java @@ -0,0 +1,14 @@ +package com.ecommerce.service; + +import java.util.List; + +import org.springframework.stereotype.Service; + +import com.ecommerce.dto.CouponsDto; + +@Service +public interface CouponsService { + + List getCouponsNotExpired(); + +} diff --git a/src/main/java/com/ecommerce/service/impl/CategoriesServiceImpl.java b/src/main/java/com/ecommerce/service/impl/CategoriesServiceImpl.java new file mode 100644 index 00000000..96de74a6 --- /dev/null +++ b/src/main/java/com/ecommerce/service/impl/CategoriesServiceImpl.java @@ -0,0 +1,47 @@ +package com.ecommerce.service.impl; + +import java.util.Collection; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.ecommerce.dto.CategoriesDto; +import com.ecommerce.feign.CategoriesClient; +import com.ecommerce.service.CategoriesService; + +@Service +public class CategoriesServiceImpl implements CategoriesService { + + @Autowired + private CategoriesClient client; + + @Override + public CategoriesDto getAll() { + return client.getAll(); + } + + @Override + public List getTopFive() { + + CategoriesDto dto = this.getAll(); + + return dto.getSubcategories().stream().map(CategoriesDto::getSubcategories).flatMap(Collection::stream) + .sorted(Comparator.comparing(CategoriesDto::getRelevance).reversed()).limit(5) + .collect(Collectors.toList()); + } + + @Override + public List getExceptTopFive(){ + + CategoriesDto dto = this.getAll(); + + return dto.getSubcategories().stream().map(CategoriesDto::getSubcategories).flatMap(Collection::stream) + .sorted(Comparator.comparing(CategoriesDto::getRelevance).reversed()).skip(5) + .collect(Collectors.toList()); + + } + +} diff --git a/src/main/java/com/ecommerce/service/impl/CouponsServiceImpl.java b/src/main/java/com/ecommerce/service/impl/CouponsServiceImpl.java new file mode 100644 index 00000000..d02d2037 --- /dev/null +++ b/src/main/java/com/ecommerce/service/impl/CouponsServiceImpl.java @@ -0,0 +1,32 @@ +package com.ecommerce.service.impl; + +import java.time.LocalDate; +import java.util.List; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.ecommerce.dto.CouponsDto; +import com.ecommerce.feign.CouponsClient; +import com.ecommerce.service.CouponsService; + +@Service +public class CouponsServiceImpl implements CouponsService { + + @Autowired + private CouponsClient client; + + @Override + public List getCouponsNotExpired() { + + List list = client.getAll().stream() + .filter(n -> LocalDate.parse(n.getExpiresAt()).isAfter(LocalDate.now())) + .collect(Collectors.toList()); + + return list; + } + + + +} diff --git a/src/main/java/com/ecommerce/utils/ConstantesUtils.java b/src/main/java/com/ecommerce/utils/ConstantesUtils.java new file mode 100644 index 00000000..0e5fa6c0 --- /dev/null +++ b/src/main/java/com/ecommerce/utils/ConstantesUtils.java @@ -0,0 +1,12 @@ +package com.ecommerce.utils; + +public class ConstantesUtils { + + public static final String ERROR_OBTENER_CATEGORIAS = "Error al obtener categorías"; + public static final String ERROR_OBTENER_TOP_CATEGORIAS = "Error al obtener el top de categorías"; + public static final String ERROR_OBTENER_NO_TOP_CATEGORIAS = "Error al obtener el categorías excepto el top"; + public static final String ERROR_OBTENER_CUPONES= "Error al obtener cupones"; + public static final String ERROR_CONEXION_API_CUPONES= "Error al intentar conectar a la API de Cupones"; + public static final String ERROR_CONEXION_API_CATEGORIAS= "Error al intentar conectar a la API de Categoías"; + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 00000000..7d263e3b --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,11 @@ +categories.api.url=https://cs-hsa-api-categories-rest.herokuapp.com +categories.api.name=categories +coupons.api.url=https://cs-hsa-api-coupons-rest.herokuapp.com +coupons.api.name=coupons +springdoc.swagger-ui.path=/swagger-ecommerce-app.html +feign.client.config.default.connectTimeout=5000 +feign.client.config.default.readTimeout=5000 +feign.client.config.default.loggerLevel=basic +feign.hystrix.enabled=true +feign.httpclient.enabled: true +server.error.include-message=always \ No newline at end of file diff --git a/src/test/java/com/ecommerce/JavaRecruitingHsaApplicationTests.java b/src/test/java/com/ecommerce/JavaRecruitingHsaApplicationTests.java new file mode 100644 index 00000000..16449c31 --- /dev/null +++ b/src/test/java/com/ecommerce/JavaRecruitingHsaApplicationTests.java @@ -0,0 +1,13 @@ +package com.ecommerce; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class JavaRecruitingHsaApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/ecommerce/controller/CategoriesControllerTest.java b/src/test/java/com/ecommerce/controller/CategoriesControllerTest.java new file mode 100644 index 00000000..ac10a18c --- /dev/null +++ b/src/test/java/com/ecommerce/controller/CategoriesControllerTest.java @@ -0,0 +1,27 @@ +package com.ecommerce.controller; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import com.ecommerce.service.CategoriesService; + +@SpringBootTest +class CategoriesControllerTest { + + @Autowired + private CategoriesService service; + + @Test + void testGetTopFive() { + assertThat(service.getTopFive()).isNotNull(); + } + + @Test + void testGetExceptTopFive() { + assertThat(service.getExceptTopFive()).isNotNull(); + } + +} diff --git a/src/test/java/com/ecommerce/controller/CouponsControllerTest.java b/src/test/java/com/ecommerce/controller/CouponsControllerTest.java new file mode 100644 index 00000000..69077a15 --- /dev/null +++ b/src/test/java/com/ecommerce/controller/CouponsControllerTest.java @@ -0,0 +1,22 @@ +package com.ecommerce.controller; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import com.ecommerce.service.CouponsService; + +@SpringBootTest +class CouponsControllerTest { + + @Autowired + private CouponsService service; + + @Test + void testGetCouponsNotExpired() { + assertThat(service.getCouponsNotExpired()).isNotNull(); + } + +}