From 721f1188f265bd26ce8641698502d625085cfc92 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 15:29:52 -0300 Subject: [PATCH 01/55] created new branch and added project maven to project --- .idea/.gitignore | 8 ++++++++ pom.xml | 12 ++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 pom.xml diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..7dd5e7d --- /dev/null +++ b/pom.xml @@ -0,0 +1,12 @@ + + + 4.0.0 + + groupId + dorotech_teste + 1.0-SNAPSHOT + + + \ No newline at end of file From 288e95e24d4c22f23479206e9af8c4a54e962418 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 15:47:55 -0300 Subject: [PATCH 02/55] added springboot to project --- pom.xml | 46 +++++++++++++++++++ .../java/com/br/dorotech/app/DorotechApp.java | 13 ++++++ src/main/resources/application.properties | 1 + 3 files changed, 60 insertions(+) create mode 100644 src/main/java/com/br/dorotech/app/DorotechApp.java create mode 100644 src/main/resources/application.properties diff --git a/pom.xml b/pom.xml index 7dd5e7d..4883fcc 100644 --- a/pom.xml +++ b/pom.xml @@ -8,5 +8,51 @@ dorotech_teste 1.0-SNAPSHOT + + org.springframework.boot + spring-boot-starter-parent + 2.7.4 + + + + + 11 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/br/dorotech/app/DorotechApp.java b/src/main/java/com/br/dorotech/app/DorotechApp.java new file mode 100644 index 0000000..1c8f388 --- /dev/null +++ b/src/main/java/com/br/dorotech/app/DorotechApp.java @@ -0,0 +1,13 @@ +package com.br.dorotech.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DorotechApp { + + public static void main(String[] args) { + SpringApplication.run(DorotechApp.class, args); + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..bafddce --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8081 \ No newline at end of file From ea6b1afe4161f7355da44e6907a490908f242720 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 16:06:51 -0300 Subject: [PATCH 03/55] created entity products and also added H2 database dependency --- pom.xml | 9 ++++ .../br/dorotech/app/controllers/Products.java | 42 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 src/main/java/com/br/dorotech/app/controllers/Products.java diff --git a/pom.xml b/pom.xml index 4883fcc..46a3d5e 100644 --- a/pom.xml +++ b/pom.xml @@ -35,6 +35,15 @@ spring-boot-starter-test test + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + runtime + diff --git a/src/main/java/com/br/dorotech/app/controllers/Products.java b/src/main/java/com/br/dorotech/app/controllers/Products.java new file mode 100644 index 0000000..2f56a99 --- /dev/null +++ b/src/main/java/com/br/dorotech/app/controllers/Products.java @@ -0,0 +1,42 @@ +package com.br.dorotech.app.controllers; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "tb_products") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class Products { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; + + @Column + private String name; + + @Column + private String description; + + @Column + private Double price; + + @Column + private Double amount; + +} From 43a0f10a8b348aa73bdaeddb98676ba5e06d94f5 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:05:24 -0300 Subject: [PATCH 04/55] created service classes for products --- .../com/br/dorotech/app/services/ProductService.java | 7 +++++++ .../dorotech/app/services/impl/ProductServiceImpl.java | 9 +++++++++ 2 files changed, 16 insertions(+) create mode 100644 src/main/java/com/br/dorotech/app/services/ProductService.java create mode 100644 src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java diff --git a/src/main/java/com/br/dorotech/app/services/ProductService.java b/src/main/java/com/br/dorotech/app/services/ProductService.java new file mode 100644 index 0000000..62d710d --- /dev/null +++ b/src/main/java/com/br/dorotech/app/services/ProductService.java @@ -0,0 +1,7 @@ +package com.br.dorotech.app.services; + +public interface ProductService { + + + +} diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java new file mode 100644 index 0000000..84a8815 --- /dev/null +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -0,0 +1,9 @@ +package com.br.dorotech.app.services.impl; + +import com.br.dorotech.app.services.ProductService; + +public class ProductServiceImpl implements ProductService { + + + +} From 303d6fbd5d576e5f73ac4cb9467a4f36819b4e7a Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:05:51 -0300 Subject: [PATCH 05/55] refactor product class added space --- src/main/java/com/br/dorotech/app/controllers/Products.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/br/dorotech/app/controllers/Products.java b/src/main/java/com/br/dorotech/app/controllers/Products.java index 2f56a99..a9e7f7e 100644 --- a/src/main/java/com/br/dorotech/app/controllers/Products.java +++ b/src/main/java/com/br/dorotech/app/controllers/Products.java @@ -21,7 +21,7 @@ @AllArgsConstructor @Builder public class Products { - + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) From a1c2a6eb26be09200e1c80df7d672549e3be1998 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:06:34 -0300 Subject: [PATCH 06/55] created class product repository --- .../br/dorotech/app/repositories/ProductRepository.java | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 src/main/java/com/br/dorotech/app/repositories/ProductRepository.java diff --git a/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java b/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java new file mode 100644 index 0000000..7f17ad3 --- /dev/null +++ b/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java @@ -0,0 +1,9 @@ +package com.br.dorotech.app.repositories; + +import com.br.dorotech.app.controllers.Products; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ProductRepository extends JpaRepository { + + +} From 7116b2ac6363088cce965ccd3b2742e8a5d56ce3 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:09:51 -0300 Subject: [PATCH 07/55] refactor moved entity products from package controller to package entities --- .../dorotech/app/{controllers => models/entities}/Products.java | 2 +- .../com/br/dorotech/app/repositories/ProductRepository.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename src/main/java/com/br/dorotech/app/{controllers => models/entities}/Products.java (94%) diff --git a/src/main/java/com/br/dorotech/app/controllers/Products.java b/src/main/java/com/br/dorotech/app/models/entities/Products.java similarity index 94% rename from src/main/java/com/br/dorotech/app/controllers/Products.java rename to src/main/java/com/br/dorotech/app/models/entities/Products.java index a9e7f7e..d09b81c 100644 --- a/src/main/java/com/br/dorotech/app/controllers/Products.java +++ b/src/main/java/com/br/dorotech/app/models/entities/Products.java @@ -1,4 +1,4 @@ -package com.br.dorotech.app.controllers; +package com.br.dorotech.app.models.entities; import lombok.AllArgsConstructor; import lombok.Builder; diff --git a/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java b/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java index 7f17ad3..20d2ff1 100644 --- a/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java +++ b/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java @@ -1,6 +1,6 @@ package com.br.dorotech.app.repositories; -import com.br.dorotech.app.controllers.Products; +import com.br.dorotech.app.models.entities.Products; import org.springframework.data.jpa.repository.JpaRepository; public interface ProductRepository extends JpaRepository { From 2bd71bcaf374ea689588fc4014735930d2be279f Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:11:47 -0300 Subject: [PATCH 08/55] created class product controller --- .../dorotech/app/controllers/ProductController.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 src/main/java/com/br/dorotech/app/controllers/ProductController.java diff --git a/src/main/java/com/br/dorotech/app/controllers/ProductController.java b/src/main/java/com/br/dorotech/app/controllers/ProductController.java new file mode 100644 index 0000000..b6ce6fc --- /dev/null +++ b/src/main/java/com/br/dorotech/app/controllers/ProductController.java @@ -0,0 +1,12 @@ +package com.br.dorotech.app.controllers; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(value = "/products") +public class ProductController { + + + +} From 5795116b65ab007ae0168d58c78d8092d8ce5d85 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:15:02 -0300 Subject: [PATCH 09/55] created classes for customized exceptions --- .../app/exceptions/ResourceNotFoundException.java | 11 +++++++++++ .../app/exceptions/RestBusinessException.java | 11 +++++++++++ 2 files changed, 22 insertions(+) create mode 100644 src/main/java/com/br/dorotech/app/exceptions/ResourceNotFoundException.java create mode 100644 src/main/java/com/br/dorotech/app/exceptions/RestBusinessException.java diff --git a/src/main/java/com/br/dorotech/app/exceptions/ResourceNotFoundException.java b/src/main/java/com/br/dorotech/app/exceptions/ResourceNotFoundException.java new file mode 100644 index 0000000..ac9faa0 --- /dev/null +++ b/src/main/java/com/br/dorotech/app/exceptions/ResourceNotFoundException.java @@ -0,0 +1,11 @@ +package com.br.dorotech.app.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +public class ResourceNotFoundException extends ResponseStatusException { + + public ResourceNotFoundException(HttpStatus status, String reason) { + super(status, reason); + } +} diff --git a/src/main/java/com/br/dorotech/app/exceptions/RestBusinessException.java b/src/main/java/com/br/dorotech/app/exceptions/RestBusinessException.java new file mode 100644 index 0000000..0ace4b4 --- /dev/null +++ b/src/main/java/com/br/dorotech/app/exceptions/RestBusinessException.java @@ -0,0 +1,11 @@ +package com.br.dorotech.app.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +public class RestBusinessException extends ResponseStatusException { + + public RestBusinessException(HttpStatus status, String reason) { + super(status, reason); + } +} From 0160cdb372e9ab14451d550b91c526b93b96f13d Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:19:05 -0300 Subject: [PATCH 10/55] added dependencies for swagger --- pom.xml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/pom.xml b/pom.xml index 46a3d5e..2712e88 100644 --- a/pom.xml +++ b/pom.xml @@ -44,6 +44,18 @@ h2 runtime + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + io.springfox + springfox-swagger2 + 2.9.2 + From 1bbd497a9a7be56bf8b398396dda18b91f2e07de Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:21:27 -0300 Subject: [PATCH 11/55] created class and implemented swagger configs --- .../dorotech/app/configs/SwaggerConfig.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/main/java/com/br/dorotech/app/configs/SwaggerConfig.java diff --git a/src/main/java/com/br/dorotech/app/configs/SwaggerConfig.java b/src/main/java/com/br/dorotech/app/configs/SwaggerConfig.java new file mode 100644 index 0000000..a6f4fe0 --- /dev/null +++ b/src/main/java/com/br/dorotech/app/configs/SwaggerConfig.java @@ -0,0 +1,47 @@ +package com.br.dorotech.app.configs; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Configuration +@EnableSwagger2 +public class SwaggerConfig extends WebMvcConfigurationSupport { + + @Bean + public Docket DorotechApi() { + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build() + .apiInfo(metaData()); + } + + private ApiInfo metaData() { + return new ApiInfoBuilder() + .title("Spring Boot REST API - Dorotech") + .description("\"Spring Boot REST API Attendance\"") + .version("1.0.0") + .license("Apache License Version 2.0") + .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"") + .build(); + } + + @Override + protected void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("swagger-ui.html") + .addResourceLocations("classpath:/META-INF/resources/"); + + registry.addResourceHandler("/webjars/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/"); + } +} \ No newline at end of file From ad13e648d30aebd2810039b5ebef46314914efe1 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:23:53 -0300 Subject: [PATCH 12/55] created and implemented class product dto --- .../dorotech/app/models/dtos/ProductDTO.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java diff --git a/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java b/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java new file mode 100644 index 0000000..d8064ed --- /dev/null +++ b/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java @@ -0,0 +1,18 @@ +package com.br.dorotech.app.models.dtos; + +import lombok.Data; + +import javax.persistence.Column; + +@Data +public class ProductDTO { + + private String name; + + private String description; + + private Double price; + + private Double amount; + +} From d2742f509a252724bd6663438d3d1526379044e0 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:24:24 -0300 Subject: [PATCH 13/55] refactor excluded unused import --- src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java b/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java index d8064ed..935311f 100644 --- a/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java +++ b/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java @@ -2,8 +2,6 @@ import lombok.Data; -import javax.persistence.Column; - @Data public class ProductDTO { From 229d3093082ba7e6e9bf37c808675d5cfd93ca60 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:28:16 -0300 Subject: [PATCH 14/55] created service methods in services and implemented empty methods in service impl --- .../dorotech/app/services/ProductService.java | 10 ++++++++ .../app/services/impl/ProductServiceImpl.java | 24 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/main/java/com/br/dorotech/app/services/ProductService.java b/src/main/java/com/br/dorotech/app/services/ProductService.java index 62d710d..db59d49 100644 --- a/src/main/java/com/br/dorotech/app/services/ProductService.java +++ b/src/main/java/com/br/dorotech/app/services/ProductService.java @@ -1,7 +1,17 @@ package com.br.dorotech.app.services; +import com.br.dorotech.app.models.dtos.ProductDTO; + public interface ProductService { + ProductDTO createNewProduct(ProductDTO productDTO); + + ProductDTO findAllProducts(); + + ProductDTO findProductById(Long id); + + void deleteProduct(Long id); + void updateProduct(Long id); } diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index 84a8815..8f2f07d 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -1,9 +1,33 @@ package com.br.dorotech.app.services.impl; +import com.br.dorotech.app.models.dtos.ProductDTO; import com.br.dorotech.app.services.ProductService; public class ProductServiceImpl implements ProductService { + @Override + public ProductDTO createNewProduct(ProductDTO productDTO) { + return null; + } + @Override + public ProductDTO findAllProducts() { + return null; + } + + @Override + public ProductDTO findProductById(Long id) { + return null; + } + + @Override + public void deleteProduct(Long id) { + + } + + @Override + public void updateProduct(Long id) { + + } } From 729965b7ff9e7ecb79a228907cf5c8d662e43537 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:31:55 -0300 Subject: [PATCH 15/55] added annotations @Service and @Repository to service and repository classes --- .../com/br/dorotech/app/repositories/ProductRepository.java | 2 ++ .../com/br/dorotech/app/services/impl/ProductServiceImpl.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java b/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java index 20d2ff1..c5fe1ea 100644 --- a/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java +++ b/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java @@ -2,7 +2,9 @@ import com.br.dorotech.app.models.entities.Products; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +@Repository public interface ProductRepository extends JpaRepository { diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index 8f2f07d..8a2f382 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -2,7 +2,9 @@ import com.br.dorotech.app.models.dtos.ProductDTO; import com.br.dorotech.app.services.ProductService; +import org.springframework.stereotype.Service; +@Service public class ProductServiceImpl implements ProductService { From cc0d9f02ffe112e499490bc062ce2f9fea32ad5c Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:39:00 -0300 Subject: [PATCH 16/55] refactor changed parameter order in JpaRepository extension --- .../com/br/dorotech/app/repositories/ProductRepository.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java b/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java index c5fe1ea..e24f573 100644 --- a/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java +++ b/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java @@ -5,7 +5,7 @@ import org.springframework.stereotype.Repository; @Repository -public interface ProductRepository extends JpaRepository { +public interface ProductRepository extends JpaRepository { } From 402b637f269522ecb0058831cc3a80723f81b2dd Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 17:44:43 -0300 Subject: [PATCH 17/55] implemented method create new product in product services --- .../app/services/impl/ProductServiceImpl.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index 8a2f382..a24777a 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -1,20 +1,34 @@ package com.br.dorotech.app.services.impl; import com.br.dorotech.app.models.dtos.ProductDTO; +import com.br.dorotech.app.models.entities.Products; +import com.br.dorotech.app.repositories.ProductRepository; import com.br.dorotech.app.services.ProductService; +import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; +import java.util.List; + @Service +@RequiredArgsConstructor public class ProductServiceImpl implements ProductService { + private final ProductRepository productRepository; @Override public ProductDTO createNewProduct(ProductDTO productDTO) { - return null; + Products product = new Products(); + product.setName(productDTO.getName()); + product.setAmount(productDTO.getAmount()); + product.setDescription(productDTO.getDescription()); + product.setPrice(productDTO.getPrice()); + productRepository.save(product); + return productDTO; } @Override public ProductDTO findAllProducts() { + List productsList = productRepository.findAll(); return null; } From b7ca5d3d5b12bca69a7e8b52a7b011f90ff70385 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:07:45 -0300 Subject: [PATCH 18/55] implemented method find all products --- .../br/dorotech/app/helper/ProductsHelper.java | 17 +++++++++++++++++ .../br/dorotech/app/models/dtos/ProductDTO.java | 2 ++ .../dorotech/app/services/ProductService.java | 4 +++- .../app/services/impl/ProductServiceImpl.java | 10 ++++++++-- 4 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/br/dorotech/app/helper/ProductsHelper.java diff --git a/src/main/java/com/br/dorotech/app/helper/ProductsHelper.java b/src/main/java/com/br/dorotech/app/helper/ProductsHelper.java new file mode 100644 index 0000000..8c46f40 --- /dev/null +++ b/src/main/java/com/br/dorotech/app/helper/ProductsHelper.java @@ -0,0 +1,17 @@ +package com.br.dorotech.app.helper; + +import com.br.dorotech.app.models.dtos.ProductDTO; +import com.br.dorotech.app.models.entities.Products; + +public class ProductsHelper { + + public static ProductDTO productsDTOBuilder(Products products){ + return ProductDTO.builder() + .amount(products.getAmount()) + .price(products.getPrice()) + .name(products.getName()) + .description(products.getDescription()) + .build(); + } + +} diff --git a/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java b/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java index 935311f..40bff27 100644 --- a/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java +++ b/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java @@ -1,8 +1,10 @@ package com.br.dorotech.app.models.dtos; +import lombok.Builder; import lombok.Data; @Data +@Builder public class ProductDTO { private String name; diff --git a/src/main/java/com/br/dorotech/app/services/ProductService.java b/src/main/java/com/br/dorotech/app/services/ProductService.java index db59d49..966a12b 100644 --- a/src/main/java/com/br/dorotech/app/services/ProductService.java +++ b/src/main/java/com/br/dorotech/app/services/ProductService.java @@ -2,11 +2,13 @@ import com.br.dorotech.app.models.dtos.ProductDTO; +import java.util.List; + public interface ProductService { ProductDTO createNewProduct(ProductDTO productDTO); - ProductDTO findAllProducts(); + List findAllProducts(); ProductDTO findProductById(Long id); diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index a24777a..689a40a 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -1,19 +1,23 @@ package com.br.dorotech.app.services.impl; +import com.br.dorotech.app.helper.ProductsHelper; import com.br.dorotech.app.models.dtos.ProductDTO; import com.br.dorotech.app.models.entities.Products; import com.br.dorotech.app.repositories.ProductRepository; import com.br.dorotech.app.services.ProductService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; +import springfox.documentation.swagger2.mappers.ModelMapper; import java.util.List; +import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class ProductServiceImpl implements ProductService { private final ProductRepository productRepository; + private final ModelMapper modelMapper; @Override public ProductDTO createNewProduct(ProductDTO productDTO) { @@ -27,9 +31,11 @@ public ProductDTO createNewProduct(ProductDTO productDTO) { } @Override - public ProductDTO findAllProducts() { + public List findAllProducts() { List productsList = productRepository.findAll(); - return null; + return productsList.stream() + .map(ProductsHelper::productsDTOBuilder) + .collect(Collectors.toList()); } @Override From 33e6f3091175efe4e0938ba0d6be290107acbf64 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:12:30 -0300 Subject: [PATCH 19/55] implemented get method in product controller --- .../app/controllers/ProductController.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/main/java/com/br/dorotech/app/controllers/ProductController.java b/src/main/java/com/br/dorotech/app/controllers/ProductController.java index b6ce6fc..26de535 100644 --- a/src/main/java/com/br/dorotech/app/controllers/ProductController.java +++ b/src/main/java/com/br/dorotech/app/controllers/ProductController.java @@ -1,12 +1,29 @@ package com.br.dorotech.app.controllers; +import com.br.dorotech.app.models.dtos.ProductDTO; +import com.br.dorotech.app.services.ProductService; +import lombok.RequiredArgsConstructor; +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; +import java.util.List; + @RestController @RequestMapping(value = "/products") +@RequiredArgsConstructor public class ProductController { + private final ProductService productService; + + @GetMapping(value = "/getAllProducts") + public ResponseEntity> getAllFarms() { + final List productDTOS = productService.findAllProducts(); + return new ResponseEntity<>(productDTOS, HttpStatus.OK); + } + } From 94cd8d82e49b3ce80fbec88b15e1fa59c78898f7 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:15:52 -0300 Subject: [PATCH 20/55] implemented post method create product in product controller --- .../br/dorotech/app/controllers/ProductController.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/br/dorotech/app/controllers/ProductController.java b/src/main/java/com/br/dorotech/app/controllers/ProductController.java index 26de535..301b38b 100644 --- a/src/main/java/com/br/dorotech/app/controllers/ProductController.java +++ b/src/main/java/com/br/dorotech/app/controllers/ProductController.java @@ -6,6 +6,8 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -24,6 +26,10 @@ public ResponseEntity> getAllFarms() { return new ResponseEntity<>(productDTOS, HttpStatus.OK); } - + @PostMapping(value = "/createProduct") + public ResponseEntity createProduct(@RequestBody ProductDTO productDTO) { + final ProductDTO createProductDTO = productService.createNewProduct(productDTO); + return new ResponseEntity<>(createProductDTO, HttpStatus.CREATED); + } } From 62534cf3eb656ef61c4eb02c3e3338222f464010 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:18:13 -0300 Subject: [PATCH 21/55] added configs in application properties --- src/main/resources/application.properties | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index bafddce..6aaf256 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1 +1,18 @@ -server.port=8081 \ No newline at end of file +# DATASOURCE +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password=sa +spring.h2.console.enabled=true + +# JPA +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.defer-datasource-initialization=true + + +# PORT CONFIG +server.port=8081 + +# CONFIG +server.error.include-message=always +server.error.include-binding-errors=always \ No newline at end of file From e2bb8142d7268f4e44d5db08e01cb998285d85f2 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:19:59 -0300 Subject: [PATCH 22/55] refactor excluded unused variable --- .../com/br/dorotech/app/services/impl/ProductServiceImpl.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index 689a40a..4954482 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -17,7 +17,6 @@ public class ProductServiceImpl implements ProductService { private final ProductRepository productRepository; - private final ModelMapper modelMapper; @Override public ProductDTO createNewProduct(ProductDTO productDTO) { From 284a13b676b695cc0ac2da8f9ade3af319bf4e23 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:22:14 -0300 Subject: [PATCH 23/55] refactor changed Product DTO class --- .../com/br/dorotech/app/models/dtos/ProductDTO.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java b/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java index 40bff27..4e900f1 100644 --- a/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java +++ b/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java @@ -1,18 +1,21 @@ package com.br.dorotech.app.models.dtos; +import lombok.AllArgsConstructor; import lombok.Builder; -import lombok.Data; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; -@Data @Builder +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor public class ProductDTO { private String name; - private String description; - private Double price; - private Double amount; } From 0bb4d959aa253ccf54b688861b2ae9ca8c46f59d Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:27:11 -0300 Subject: [PATCH 24/55] refactor created builder for products creation --- .../java/com/br/dorotech/app/helper/ProductsHelper.java | 9 +++++++++ .../dorotech/app/services/impl/ProductServiceImpl.java | 9 +++------ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/br/dorotech/app/helper/ProductsHelper.java b/src/main/java/com/br/dorotech/app/helper/ProductsHelper.java index 8c46f40..ac0e894 100644 --- a/src/main/java/com/br/dorotech/app/helper/ProductsHelper.java +++ b/src/main/java/com/br/dorotech/app/helper/ProductsHelper.java @@ -14,4 +14,13 @@ public static ProductDTO productsDTOBuilder(Products products){ .build(); } + public static Products productsBuilder(ProductDTO productDTO){ + return Products.builder() + .amount(productDTO.getAmount()) + .price(productDTO.getPrice()) + .name(productDTO.getName()) + .description(productDTO.getDescription()) + .build(); + } + } diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index 4954482..175b750 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -12,6 +12,8 @@ import java.util.List; import java.util.stream.Collectors; +import static com.br.dorotech.app.helper.ProductsHelper.productsBuilder; + @Service @RequiredArgsConstructor public class ProductServiceImpl implements ProductService { @@ -20,12 +22,7 @@ public class ProductServiceImpl implements ProductService { @Override public ProductDTO createNewProduct(ProductDTO productDTO) { - Products product = new Products(); - product.setName(productDTO.getName()); - product.setAmount(productDTO.getAmount()); - product.setDescription(productDTO.getDescription()); - product.setPrice(productDTO.getPrice()); - productRepository.save(product); + productsBuilder(productDTO); return productDTO; } From 885ed025279d748cf9c866ab68c59c1e9d9eb9de Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:28:07 -0300 Subject: [PATCH 25/55] refactor method name --- .../java/com/br/dorotech/app/controllers/ProductController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/br/dorotech/app/controllers/ProductController.java b/src/main/java/com/br/dorotech/app/controllers/ProductController.java index 301b38b..a6685b4 100644 --- a/src/main/java/com/br/dorotech/app/controllers/ProductController.java +++ b/src/main/java/com/br/dorotech/app/controllers/ProductController.java @@ -21,7 +21,7 @@ public class ProductController { private final ProductService productService; @GetMapping(value = "/getAllProducts") - public ResponseEntity> getAllFarms() { + public ResponseEntity> getAllProducts() { final List productDTOS = productService.findAllProducts(); return new ResponseEntity<>(productDTOS, HttpStatus.OK); } From c5f43d963e42857203309c48dcbbee46c85cd934 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:31:12 -0300 Subject: [PATCH 26/55] refactor service method it was missing to save in the repository --- .../com/br/dorotech/app/services/impl/ProductServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index 175b750..7bfb61a 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -22,7 +22,7 @@ public class ProductServiceImpl implements ProductService { @Override public ProductDTO createNewProduct(ProductDTO productDTO) { - productsBuilder(productDTO); + productRepository.save(productsBuilder(productDTO)); return productDTO; } From c8f9b6edb20dc1f93d44476656111172b03e4952 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:37:33 -0300 Subject: [PATCH 27/55] implementhed method find by id in services --- .../br/dorotech/app/services/impl/ProductServiceImpl.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index 7bfb61a..1c7c090 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -1,11 +1,13 @@ package com.br.dorotech.app.services.impl; +import com.br.dorotech.app.exceptions.ResourceNotFoundException; import com.br.dorotech.app.helper.ProductsHelper; import com.br.dorotech.app.models.dtos.ProductDTO; import com.br.dorotech.app.models.entities.Products; import com.br.dorotech.app.repositories.ProductRepository; import com.br.dorotech.app.services.ProductService; import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import springfox.documentation.swagger2.mappers.ModelMapper; @@ -13,6 +15,7 @@ import java.util.stream.Collectors; import static com.br.dorotech.app.helper.ProductsHelper.productsBuilder; +import static com.br.dorotech.app.helper.ProductsHelper.productsDTOBuilder; @Service @RequiredArgsConstructor @@ -36,7 +39,8 @@ public List findAllProducts() { @Override public ProductDTO findProductById(Long id) { - return null; + Products products = productRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(HttpStatus.NOT_FOUND, "Id not found!")); + return productsDTOBuilder(products); } @Override From 673cb6cf69126645fbd11d489ae51684a37a265d Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:46:24 -0300 Subject: [PATCH 28/55] implementhed method find by id in controller --- .../br/dorotech/app/controllers/ProductController.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/java/com/br/dorotech/app/controllers/ProductController.java b/src/main/java/com/br/dorotech/app/controllers/ProductController.java index a6685b4..d4c6dbe 100644 --- a/src/main/java/com/br/dorotech/app/controllers/ProductController.java +++ b/src/main/java/com/br/dorotech/app/controllers/ProductController.java @@ -6,6 +6,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -32,4 +33,12 @@ public ResponseEntity createProduct(@RequestBody ProductDTO productD return new ResponseEntity<>(createProductDTO, HttpStatus.CREATED); } + @GetMapping(value = "/getProductById/{id}") + public ResponseEntity getFarmById(@PathVariable Long id){ + final ProductDTO productDTO = productService.findProductById(id); + return new ResponseEntity<>(productDTO, HttpStatus.OK); + } + + + } From 0d1c3ecccb4befab21b645f688afb4682bbd4f68 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:46:51 -0300 Subject: [PATCH 29/55] implementhed method delete in product services --- .../com/br/dorotech/app/services/impl/ProductServiceImpl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index 1c7c090..dec1d51 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -45,7 +45,8 @@ public ProductDTO findProductById(Long id) { @Override public void deleteProduct(Long id) { - + Products products = productRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(HttpStatus.NOT_FOUND, "Id not found!")); + productRepository.delete(products); } @Override From 38e20042881e01376f5969ca3b375b481090a1b9 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:50:03 -0300 Subject: [PATCH 30/55] implementhed method delete in product controller --- .../dorotech/app/controllers/ProductController.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/br/dorotech/app/controllers/ProductController.java b/src/main/java/com/br/dorotech/app/controllers/ProductController.java index d4c6dbe..be81162 100644 --- a/src/main/java/com/br/dorotech/app/controllers/ProductController.java +++ b/src/main/java/com/br/dorotech/app/controllers/ProductController.java @@ -5,6 +5,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -34,11 +35,19 @@ public ResponseEntity createProduct(@RequestBody ProductDTO productD } @GetMapping(value = "/getProductById/{id}") - public ResponseEntity getFarmById(@PathVariable Long id){ + public ResponseEntity getProductById(@PathVariable Long id){ final ProductDTO productDTO = productService.findProductById(id); return new ResponseEntity<>(productDTO, HttpStatus.OK); } + @DeleteMapping(value = "/deleteProduct/{id}") + public ResponseEntity deleteProduct(@PathVariable Long id) { + final String msg = "Product Id " + id + " deleted!"; + productService.deleteProduct(id); + return new ResponseEntity<>(msg, HttpStatus.OK); + } + + } From 99243abbf31407c56fb299fbdeda68d390a42108 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 18:56:07 -0300 Subject: [PATCH 31/55] implementhed method update in product services --- .../br/dorotech/app/controllers/ProductController.java | 2 +- .../com/br/dorotech/app/helper/ProductsHelper.java | 10 ++++++++++ .../com/br/dorotech/app/services/ProductService.java | 2 +- .../dorotech/app/services/impl/ProductServiceImpl.java | 7 +++++-- 4 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/br/dorotech/app/controllers/ProductController.java b/src/main/java/com/br/dorotech/app/controllers/ProductController.java index be81162..0cfc186 100644 --- a/src/main/java/com/br/dorotech/app/controllers/ProductController.java +++ b/src/main/java/com/br/dorotech/app/controllers/ProductController.java @@ -47,7 +47,7 @@ public ResponseEntity deleteProduct(@PathVariable Long id) { return new ResponseEntity<>(msg, HttpStatus.OK); } - + } diff --git a/src/main/java/com/br/dorotech/app/helper/ProductsHelper.java b/src/main/java/com/br/dorotech/app/helper/ProductsHelper.java index ac0e894..bb6660a 100644 --- a/src/main/java/com/br/dorotech/app/helper/ProductsHelper.java +++ b/src/main/java/com/br/dorotech/app/helper/ProductsHelper.java @@ -23,4 +23,14 @@ public static Products productsBuilder(ProductDTO productDTO){ .build(); } + public static Products productsUpdateBuilder(Products products, ProductDTO productDTO){ + return Products.builder() + .id(products.getId()) + .amount(productDTO.getAmount()) + .price(productDTO.getPrice()) + .name(productDTO.getName()) + .description(productDTO.getDescription()) + .build(); + } + } diff --git a/src/main/java/com/br/dorotech/app/services/ProductService.java b/src/main/java/com/br/dorotech/app/services/ProductService.java index 966a12b..0e5285e 100644 --- a/src/main/java/com/br/dorotech/app/services/ProductService.java +++ b/src/main/java/com/br/dorotech/app/services/ProductService.java @@ -14,6 +14,6 @@ public interface ProductService { void deleteProduct(Long id); - void updateProduct(Long id); + void updateProduct(Long id, ProductDTO productDTO); } diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index dec1d51..b4765a0 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -16,6 +16,7 @@ import static com.br.dorotech.app.helper.ProductsHelper.productsBuilder; import static com.br.dorotech.app.helper.ProductsHelper.productsDTOBuilder; +import static com.br.dorotech.app.helper.ProductsHelper.productsUpdateBuilder; @Service @RequiredArgsConstructor @@ -50,7 +51,9 @@ public void deleteProduct(Long id) { } @Override - public void updateProduct(Long id) { - + public void updateProduct(Long id, ProductDTO productDTO) { + Products products = productRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(HttpStatus.NOT_FOUND, "Id not found!")); + Products productsUpdated = productsUpdateBuilder(products, productDTO); + productRepository.save(productsUpdated); } } From de44aa911b05a6b0481bc9f5ea50f3d969f638d6 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 19:02:30 -0300 Subject: [PATCH 32/55] implementhed method update in product controller --- .../br/dorotech/app/controllers/ProductController.java | 8 ++++++-- .../java/com/br/dorotech/app/services/ProductService.java | 2 +- .../br/dorotech/app/services/impl/ProductServiceImpl.java | 3 ++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/br/dorotech/app/controllers/ProductController.java b/src/main/java/com/br/dorotech/app/controllers/ProductController.java index 0cfc186..b2a2b9d 100644 --- a/src/main/java/com/br/dorotech/app/controllers/ProductController.java +++ b/src/main/java/com/br/dorotech/app/controllers/ProductController.java @@ -9,6 +9,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -47,7 +48,10 @@ public ResponseEntity deleteProduct(@PathVariable Long id) { return new ResponseEntity<>(msg, HttpStatus.OK); } - - + @PutMapping(value = "/updateProduct/{id}") + public ResponseEntity updateProduct(@PathVariable Long id, @RequestBody ProductDTO productDTO) { + final ProductDTO productUpdateDTO = productService.updateProduct(id, productDTO); + return new ResponseEntity<>(productUpdateDTO, HttpStatus.OK); + } } diff --git a/src/main/java/com/br/dorotech/app/services/ProductService.java b/src/main/java/com/br/dorotech/app/services/ProductService.java index 0e5285e..97e510d 100644 --- a/src/main/java/com/br/dorotech/app/services/ProductService.java +++ b/src/main/java/com/br/dorotech/app/services/ProductService.java @@ -14,6 +14,6 @@ public interface ProductService { void deleteProduct(Long id); - void updateProduct(Long id, ProductDTO productDTO); + ProductDTO updateProduct(Long id, ProductDTO productDTO); } diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index b4765a0..77a1dd7 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -51,9 +51,10 @@ public void deleteProduct(Long id) { } @Override - public void updateProduct(Long id, ProductDTO productDTO) { + public ProductDTO updateProduct(Long id, ProductDTO productDTO) { Products products = productRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(HttpStatus.NOT_FOUND, "Id not found!")); Products productsUpdated = productsUpdateBuilder(products, productDTO); productRepository.save(productsUpdated); + return productDTO; } } From 7edb9b37fcc7102dd2a49b1c18d1822407826b35 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sat, 10 Dec 2022 19:04:41 -0300 Subject: [PATCH 33/55] refactor changed entity class name --- ...ProductsHelper.java => ProductHelper.java} | 24 +++++++------- .../entities/{Products.java => Product.java} | 2 +- .../app/repositories/ProductRepository.java | 4 +-- .../app/services/impl/ProductServiceImpl.java | 31 +++++++++---------- 4 files changed, 30 insertions(+), 31 deletions(-) rename src/main/java/com/br/dorotech/app/helper/{ProductsHelper.java => ProductHelper.java} (50%) rename src/main/java/com/br/dorotech/app/models/entities/{Products.java => Product.java} (97%) diff --git a/src/main/java/com/br/dorotech/app/helper/ProductsHelper.java b/src/main/java/com/br/dorotech/app/helper/ProductHelper.java similarity index 50% rename from src/main/java/com/br/dorotech/app/helper/ProductsHelper.java rename to src/main/java/com/br/dorotech/app/helper/ProductHelper.java index bb6660a..082f3a2 100644 --- a/src/main/java/com/br/dorotech/app/helper/ProductsHelper.java +++ b/src/main/java/com/br/dorotech/app/helper/ProductHelper.java @@ -1,21 +1,21 @@ package com.br.dorotech.app.helper; import com.br.dorotech.app.models.dtos.ProductDTO; -import com.br.dorotech.app.models.entities.Products; +import com.br.dorotech.app.models.entities.Product; -public class ProductsHelper { +public class ProductHelper { - public static ProductDTO productsDTOBuilder(Products products){ + public static ProductDTO productsDTOBuilder(Product product){ return ProductDTO.builder() - .amount(products.getAmount()) - .price(products.getPrice()) - .name(products.getName()) - .description(products.getDescription()) + .amount(product.getAmount()) + .price(product.getPrice()) + .name(product.getName()) + .description(product.getDescription()) .build(); } - public static Products productsBuilder(ProductDTO productDTO){ - return Products.builder() + public static Product productsBuilder(ProductDTO productDTO){ + return Product.builder() .amount(productDTO.getAmount()) .price(productDTO.getPrice()) .name(productDTO.getName()) @@ -23,9 +23,9 @@ public static Products productsBuilder(ProductDTO productDTO){ .build(); } - public static Products productsUpdateBuilder(Products products, ProductDTO productDTO){ - return Products.builder() - .id(products.getId()) + public static Product productsUpdateBuilder(Product product, ProductDTO productDTO){ + return Product.builder() + .id(product.getId()) .amount(productDTO.getAmount()) .price(productDTO.getPrice()) .name(productDTO.getName()) diff --git a/src/main/java/com/br/dorotech/app/models/entities/Products.java b/src/main/java/com/br/dorotech/app/models/entities/Product.java similarity index 97% rename from src/main/java/com/br/dorotech/app/models/entities/Products.java rename to src/main/java/com/br/dorotech/app/models/entities/Product.java index d09b81c..f5ef720 100644 --- a/src/main/java/com/br/dorotech/app/models/entities/Products.java +++ b/src/main/java/com/br/dorotech/app/models/entities/Product.java @@ -20,7 +20,7 @@ @NoArgsConstructor @AllArgsConstructor @Builder -public class Products { +public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java b/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java index e24f573..598c5aa 100644 --- a/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java +++ b/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java @@ -1,11 +1,11 @@ package com.br.dorotech.app.repositories; -import com.br.dorotech.app.models.entities.Products; +import com.br.dorotech.app.models.entities.Product; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository -public interface ProductRepository extends JpaRepository { +public interface ProductRepository extends JpaRepository { } diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index 77a1dd7..3170429 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -1,22 +1,21 @@ package com.br.dorotech.app.services.impl; import com.br.dorotech.app.exceptions.ResourceNotFoundException; -import com.br.dorotech.app.helper.ProductsHelper; +import com.br.dorotech.app.helper.ProductHelper; import com.br.dorotech.app.models.dtos.ProductDTO; -import com.br.dorotech.app.models.entities.Products; +import com.br.dorotech.app.models.entities.Product; import com.br.dorotech.app.repositories.ProductRepository; import com.br.dorotech.app.services.ProductService; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; -import springfox.documentation.swagger2.mappers.ModelMapper; import java.util.List; import java.util.stream.Collectors; -import static com.br.dorotech.app.helper.ProductsHelper.productsBuilder; -import static com.br.dorotech.app.helper.ProductsHelper.productsDTOBuilder; -import static com.br.dorotech.app.helper.ProductsHelper.productsUpdateBuilder; +import static com.br.dorotech.app.helper.ProductHelper.productsBuilder; +import static com.br.dorotech.app.helper.ProductHelper.productsDTOBuilder; +import static com.br.dorotech.app.helper.ProductHelper.productsUpdateBuilder; @Service @RequiredArgsConstructor @@ -32,29 +31,29 @@ public ProductDTO createNewProduct(ProductDTO productDTO) { @Override public List findAllProducts() { - List productsList = productRepository.findAll(); - return productsList.stream() - .map(ProductsHelper::productsDTOBuilder) + List productList = productRepository.findAll(); + return productList.stream() + .map(ProductHelper::productsDTOBuilder) .collect(Collectors.toList()); } @Override public ProductDTO findProductById(Long id) { - Products products = productRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(HttpStatus.NOT_FOUND, "Id not found!")); - return productsDTOBuilder(products); + Product product = productRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(HttpStatus.NOT_FOUND, "Id not found!")); + return productsDTOBuilder(product); } @Override public void deleteProduct(Long id) { - Products products = productRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(HttpStatus.NOT_FOUND, "Id not found!")); - productRepository.delete(products); + Product product = productRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(HttpStatus.NOT_FOUND, "Id not found!")); + productRepository.delete(product); } @Override public ProductDTO updateProduct(Long id, ProductDTO productDTO) { - Products products = productRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(HttpStatus.NOT_FOUND, "Id not found!")); - Products productsUpdated = productsUpdateBuilder(products, productDTO); - productRepository.save(productsUpdated); + Product product = productRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(HttpStatus.NOT_FOUND, "Id not found!")); + Product productUpdated = productsUpdateBuilder(product, productDTO); + productRepository.save(productUpdated); return productDTO; } } From 2ac0f93268c0ffb912cc70c165dbd704c34175f1 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 14:29:09 -0300 Subject: [PATCH 34/55] changed database configurations to dynamo db --- pom.xml | 21 +++++---- .../java/com/br/dorotech/app/DorotechApp.java | 2 + .../dorotech/app/configs/DynamoDbConfig.java | 44 ++++++++++++++++++ .../app/controllers/ProductController.java | 6 +-- .../dorotech/app/models/dtos/ProductDTO.java | 4 +- .../dorotech/app/models/entities/Product.java | 45 +++++++++---------- .../app/repositories/ProductRepository.java | 6 ++- .../dorotech/app/services/ProductService.java | 6 +-- .../app/services/impl/ProductServiceImpl.java | 8 ++-- src/main/resources/application.properties | 18 -------- src/main/resources/application.yml | 15 +++++++ 11 files changed, 110 insertions(+), 65 deletions(-) create mode 100644 src/main/java/com/br/dorotech/app/configs/DynamoDbConfig.java delete mode 100644 src/main/resources/application.properties create mode 100644 src/main/resources/application.yml diff --git a/pom.xml b/pom.xml index 2712e88..b35b00a 100644 --- a/pom.xml +++ b/pom.xml @@ -35,15 +35,6 @@ spring-boot-starter-test test - - org.springframework.boot - spring-boot-starter-data-jpa - - - com.h2database - h2 - runtime - io.springfox @@ -56,6 +47,18 @@ springfox-swagger2 2.9.2 + + + com.amazonaws + aws-java-sdk-dynamodb + 1.12.198 + + + com.github.derjust + spring-data-dynamodb + 5.1.0 + + diff --git a/src/main/java/com/br/dorotech/app/DorotechApp.java b/src/main/java/com/br/dorotech/app/DorotechApp.java index 1c8f388..c125db7 100644 --- a/src/main/java/com/br/dorotech/app/DorotechApp.java +++ b/src/main/java/com/br/dorotech/app/DorotechApp.java @@ -2,8 +2,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication +@EnableSwagger2 public class DorotechApp { public static void main(String[] args) { diff --git a/src/main/java/com/br/dorotech/app/configs/DynamoDbConfig.java b/src/main/java/com/br/dorotech/app/configs/DynamoDbConfig.java new file mode 100644 index 0000000..7b45529 --- /dev/null +++ b/src/main/java/com/br/dorotech/app/configs/DynamoDbConfig.java @@ -0,0 +1,44 @@ +package com.br.dorotech.app.configs; + +import com.amazonaws.auth.AWSCredentials; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; +import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.StringUtils; + + +@Configuration +@EnableDynamoDBRepositories(basePackages = "com.br.dorotech.app.repositories") +public class DynamoDbConfig { + + @Value("${amazon.dynamodb.endpoint}") + private String amazonDynamoDBEndpoint; + + @Value("${amazon.aws.accesskey}") + private String amazonAWSAccessKey; + + @Value("${amazon.aws.secretkey}") + private String amazonAWSSecretKey; + + @Bean + public AmazonDynamoDB amazonDynamoDB() { + AmazonDynamoDB amazonDynamoDB + = new AmazonDynamoDBClient(amazonAWSCredentials()); + + if (!StringUtils.isEmpty(amazonDynamoDBEndpoint)) { + amazonDynamoDB.setEndpoint(amazonDynamoDBEndpoint); + } + + return amazonDynamoDB; + } + + @Bean + public AWSCredentials amazonAWSCredentials() { + return new BasicAWSCredentials( + amazonAWSAccessKey, amazonAWSSecretKey); + } +} diff --git a/src/main/java/com/br/dorotech/app/controllers/ProductController.java b/src/main/java/com/br/dorotech/app/controllers/ProductController.java index b2a2b9d..d7b4ba0 100644 --- a/src/main/java/com/br/dorotech/app/controllers/ProductController.java +++ b/src/main/java/com/br/dorotech/app/controllers/ProductController.java @@ -36,20 +36,20 @@ public ResponseEntity createProduct(@RequestBody ProductDTO productD } @GetMapping(value = "/getProductById/{id}") - public ResponseEntity getProductById(@PathVariable Long id){ + public ResponseEntity getProductById(@PathVariable String id){ final ProductDTO productDTO = productService.findProductById(id); return new ResponseEntity<>(productDTO, HttpStatus.OK); } @DeleteMapping(value = "/deleteProduct/{id}") - public ResponseEntity deleteProduct(@PathVariable Long id) { + public ResponseEntity deleteProduct(@PathVariable String id) { final String msg = "Product Id " + id + " deleted!"; productService.deleteProduct(id); return new ResponseEntity<>(msg, HttpStatus.OK); } @PutMapping(value = "/updateProduct/{id}") - public ResponseEntity updateProduct(@PathVariable Long id, @RequestBody ProductDTO productDTO) { + public ResponseEntity updateProduct(@PathVariable String id, @RequestBody ProductDTO productDTO) { final ProductDTO productUpdateDTO = productService.updateProduct(id, productDTO); return new ResponseEntity<>(productUpdateDTO, HttpStatus.OK); } diff --git a/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java b/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java index 4e900f1..5c5bd2d 100644 --- a/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java +++ b/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java @@ -2,13 +2,13 @@ import lombok.AllArgsConstructor; import lombok.Builder; +import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Builder -@Getter -@Setter +@Data @NoArgsConstructor @AllArgsConstructor public class ProductDTO { diff --git a/src/main/java/com/br/dorotech/app/models/entities/Product.java b/src/main/java/com/br/dorotech/app/models/entities/Product.java index f5ef720..fd738d7 100644 --- a/src/main/java/com/br/dorotech/app/models/entities/Product.java +++ b/src/main/java/com/br/dorotech/app/models/entities/Product.java @@ -1,42 +1,39 @@ package com.br.dorotech.app.models.entities; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import lombok.AllArgsConstructor; import lombok.Builder; -import lombok.Getter; +import lombok.Data; import lombok.NoArgsConstructor; -import lombok.Setter; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "tb_products") -@Getter -@Setter -@NoArgsConstructor + +import java.io.Serializable; + +@DynamoDBTable(tableName = "products") +@Data @AllArgsConstructor +@NoArgsConstructor @Builder -public class Product { +public class Product implements Serializable { + + private static final long serialVersionUID = 1L; - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", nullable = false) - private Long id; + @DynamoDBHashKey(attributeName = "productId") + @DynamoDBAutoGeneratedKey + private String id; - @Column + @DynamoDBAttribute private String name; - @Column + @DynamoDBAttribute private String description; - @Column + @DynamoDBAttribute private Double price; - @Column + @DynamoDBAttribute private Double amount; } diff --git a/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java b/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java index 598c5aa..c6dbf1e 100644 --- a/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java +++ b/src/main/java/com/br/dorotech/app/repositories/ProductRepository.java @@ -1,11 +1,13 @@ package com.br.dorotech.app.repositories; import com.br.dorotech.app.models.entities.Product; -import org.springframework.data.jpa.repository.JpaRepository; +import org.socialsignin.spring.data.dynamodb.repository.DynamoDBCrudRepository; +import org.socialsignin.spring.data.dynamodb.repository.EnableScan; import org.springframework.stereotype.Repository; @Repository -public interface ProductRepository extends JpaRepository { +@EnableScan +public interface ProductRepository extends DynamoDBCrudRepository { } diff --git a/src/main/java/com/br/dorotech/app/services/ProductService.java b/src/main/java/com/br/dorotech/app/services/ProductService.java index 97e510d..0405679 100644 --- a/src/main/java/com/br/dorotech/app/services/ProductService.java +++ b/src/main/java/com/br/dorotech/app/services/ProductService.java @@ -10,10 +10,10 @@ public interface ProductService { List findAllProducts(); - ProductDTO findProductById(Long id); + ProductDTO findProductById(String id); - void deleteProduct(Long id); + void deleteProduct(String id); - ProductDTO updateProduct(Long id, ProductDTO productDTO); + ProductDTO updateProduct(String id, ProductDTO productDTO); } diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index 3170429..8a0e35a 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -31,26 +31,26 @@ public ProductDTO createNewProduct(ProductDTO productDTO) { @Override public List findAllProducts() { - List productList = productRepository.findAll(); + List productList = (List) productRepository.findAll(); return productList.stream() .map(ProductHelper::productsDTOBuilder) .collect(Collectors.toList()); } @Override - public ProductDTO findProductById(Long id) { + public ProductDTO findProductById(String id) { Product product = productRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(HttpStatus.NOT_FOUND, "Id not found!")); return productsDTOBuilder(product); } @Override - public void deleteProduct(Long id) { + public void deleteProduct(String id) { Product product = productRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(HttpStatus.NOT_FOUND, "Id not found!")); productRepository.delete(product); } @Override - public ProductDTO updateProduct(Long id, ProductDTO productDTO) { + public ProductDTO updateProduct(String id, ProductDTO productDTO) { Product product = productRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(HttpStatus.NOT_FOUND, "Id not found!")); Product productUpdated = productsUpdateBuilder(product, productDTO); productRepository.save(productUpdated); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties deleted file mode 100644 index 6aaf256..0000000 --- a/src/main/resources/application.properties +++ /dev/null @@ -1,18 +0,0 @@ -# DATASOURCE -spring.datasource.url=jdbc:h2:mem:testdb -spring.datasource.driverClassName=org.h2.Driver -spring.datasource.username=sa -spring.datasource.password=sa -spring.h2.console.enabled=true - -# JPA -spring.jpa.database-platform=org.hibernate.dialect.H2Dialect -spring.jpa.defer-datasource-initialization=true - - -# PORT CONFIG -server.port=8081 - -# CONFIG -server.error.include-message=always -server.error.include-binding-errors=always \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..77f9240 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,15 @@ +server: + port: 8081 + error: + include-message: always + include-binding-errors: always + +amazon: + aws: + accesskey: ${access.key} + secretkey: ${secret.key} + dynamodb: + endpoint: http://dynamodb.us-east-1.amazonaws.com + + region: us-east-1 + From a89099cf19523b276ad4f7f3d01abab1413a8a2f Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 14:54:12 -0300 Subject: [PATCH 35/55] created and implemented SQS configurations --- pom.xml | 25 ++++++++ .../configs/SQSJmsConsumerConfiguration.java | 62 +++++++++++++++++++ .../app/configs/SQSProviderConfiguration.java | 33 ++++++++++ .../app/sqs/ProductMessageConsumer.java | 33 ++++++++++ .../app/sqs/ProductMessageProducer.java | 22 +++++++ .../com/br/dorotech/app/util/JsonUtil.java | 54 ++++++++++++++++ src/main/resources/application.yml | 5 ++ 7 files changed, 234 insertions(+) create mode 100644 src/main/java/com/br/dorotech/app/configs/SQSJmsConsumerConfiguration.java create mode 100644 src/main/java/com/br/dorotech/app/configs/SQSProviderConfiguration.java create mode 100644 src/main/java/com/br/dorotech/app/sqs/ProductMessageConsumer.java create mode 100644 src/main/java/com/br/dorotech/app/sqs/ProductMessageProducer.java create mode 100644 src/main/java/com/br/dorotech/app/util/JsonUtil.java diff --git a/pom.xml b/pom.xml index b35b00a..fa9deb9 100644 --- a/pom.xml +++ b/pom.xml @@ -30,6 +30,7 @@ lombok true + org.springframework.boot spring-boot-starter-test @@ -53,12 +54,36 @@ aws-java-sdk-dynamodb 1.12.198 + com.github.derjust spring-data-dynamodb 5.1.0 + + com.amazonaws + amazon-sqs-java-messaging-lib + 1.0.8 + + + + org.springframework + spring-jms + + + + commons-io + commons-io + 2.4 + + + + com.amazonaws + aws-java-sdk-sqs + 1.12.198 + + diff --git a/src/main/java/com/br/dorotech/app/configs/SQSJmsConsumerConfiguration.java b/src/main/java/com/br/dorotech/app/configs/SQSJmsConsumerConfiguration.java new file mode 100644 index 0000000..399072b --- /dev/null +++ b/src/main/java/com/br/dorotech/app/configs/SQSJmsConsumerConfiguration.java @@ -0,0 +1,62 @@ +package com.br.dorotech.app.configs; + +import com.amazon.sqs.javamessaging.ProviderConfiguration; +import com.amazon.sqs.javamessaging.SQSConnectionFactory; +import com.amazonaws.services.sqs.AmazonSQS; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; +import org.springframework.jms.annotation.EnableJms; +import org.springframework.jms.config.DefaultJmsListenerContainerFactory; +import org.springframework.jms.core.JmsTemplate; +import org.springframework.util.ErrorHandler; + +import javax.annotation.PostConstruct; + +/** + * Configuration class for connection with SQS queues (consumer) + */ +@Configuration +@EnableJms +@DependsOn("SQSProviderConfiguration") +@Slf4j +public class SQSJmsConsumerConfiguration implements ErrorHandler { + + private SQSConnectionFactory connectionFactory; + + private AmazonSQS amazonSQS; + + public SQSJmsConsumerConfiguration(AmazonSQS amazonSQS) { + this.amazonSQS = amazonSQS; + } + + @PostConstruct + public void init() { + connectionFactory = createSQSConnectionFactory(); + } + + private SQSConnectionFactory createSQSConnectionFactory() { + return new SQSConnectionFactory(new ProviderConfiguration(), amazonSQS); + } + + @Bean + public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() { + final DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); + factory.setConnectionFactory(connectionFactory); + factory.setErrorHandler(this); + return factory; + } + + @Bean + public JmsTemplate defaultJmsTemplate() { + return new JmsTemplate(connectionFactory); + } + + @Override + public void handleError(Throwable t) { + log.error("Listener SQS error has been thrown"); + log.error("SQS_ERROR_LOCAL_MESSAGE: {}", t.getLocalizedMessage()); + log.error("SQS_ERROR_MESSAGE: {}", t.getMessage()); + } +} \ No newline at end of file diff --git a/src/main/java/com/br/dorotech/app/configs/SQSProviderConfiguration.java b/src/main/java/com/br/dorotech/app/configs/SQSProviderConfiguration.java new file mode 100644 index 0000000..3002a64 --- /dev/null +++ b/src/main/java/com/br/dorotech/app/configs/SQSProviderConfiguration.java @@ -0,0 +1,33 @@ +package com.br.dorotech.app.configs; + +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.services.sqs.AmazonSQS; +import com.amazonaws.services.sqs.AmazonSQSClientBuilder; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SQSProviderConfiguration { + + @Value("${amazon.region}") + private String region; + + @Value("${amazon.aws.accesskey}") + private String accessKey; + + @Value("${amazon.aws.secretkey}") + private String secretKey; + + @Bean + public AmazonSQS createSQSClient() { + return AmazonSQSClientBuilder + .standard() + .withCredentials(new AWSStaticCredentialsProvider( + new BasicAWSCredentials(accessKey,secretKey) + )) + .withRegion(region) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/br/dorotech/app/sqs/ProductMessageConsumer.java b/src/main/java/com/br/dorotech/app/sqs/ProductMessageConsumer.java new file mode 100644 index 0000000..47d905f --- /dev/null +++ b/src/main/java/com/br/dorotech/app/sqs/ProductMessageConsumer.java @@ -0,0 +1,33 @@ +package com.br.dorotech.app.sqs; + +import com.br.dorotech.app.models.dtos.ProductDTO; +import com.br.dorotech.app.services.ProductService; +import com.br.dorotech.app.util.JsonUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.jms.annotation.JmsListener; +import org.springframework.messaging.handler.annotation.Payload; +import org.springframework.stereotype.Component; + +@Component +@Slf4j +@RequiredArgsConstructor +public class ProductMessageConsumer { + + private ProductService productService; + + @Value("${amazon.queue.product-creation}") + private String queueName; + + @JmsListener(destination = "${amazon.queue.attendance}") + public void messageConsumer(@Payload String message) { + ProductDTO productDTO = JsonUtil.readValue(message, ProductDTO.class); + + log.info("***** PRODUCT CREATED: " + queueName + ", PRODUCT NAME: " + productDTO.getName() + + ", PRODUCT DESCRIPTION: " + productDTO.getDescription()); + + //IMPLEMENTAR CHAMADA EM SERVICE + } + +} \ No newline at end of file diff --git a/src/main/java/com/br/dorotech/app/sqs/ProductMessageProducer.java b/src/main/java/com/br/dorotech/app/sqs/ProductMessageProducer.java new file mode 100644 index 0000000..4135e91 --- /dev/null +++ b/src/main/java/com/br/dorotech/app/sqs/ProductMessageProducer.java @@ -0,0 +1,22 @@ +package com.br.dorotech.app.sqs; + +import com.amazonaws.services.sqs.AmazonSQS; +import com.amazonaws.services.sqs.model.SendMessageRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class ProductMessageProducer { + + private AmazonSQS amazonSQS; + + public void sentToQueue(final String queueName, final String message) { + amazonSQS.sendMessage(new SendMessageRequest() + .withQueueUrl(queueName) + .withMessageBody(message) + ); + } + +} + diff --git a/src/main/java/com/br/dorotech/app/util/JsonUtil.java b/src/main/java/com/br/dorotech/app/util/JsonUtil.java new file mode 100644 index 0000000..ea6102a --- /dev/null +++ b/src/main/java/com/br/dorotech/app/util/JsonUtil.java @@ -0,0 +1,54 @@ +package com.br.dorotech.app.util; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JsonUtil { + private static final Logger LOG = LoggerFactory.getLogger(JsonUtil.class); + + private static final ObjectMapper OBJECT_MAPPER = createObjectMapper(); + + private static final ObjectMapper createObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); + objectMapper.registerModule(new JavaTimeModule()); + objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + return objectMapper; + } + + + public static String writeValueAsString(Object value) { + try { + String json = OBJECT_MAPPER.writeValueAsString(value); + json = (json.equals("\"\"")) ? "{}" : json; + + return json; + } catch (JsonProcessingException e) { + LOG.error("Erro ao gerar json : " + value, e); + } + + return ""; + } + + public static T readValue(String json, Class valueType) { + try { + if (JsonNode.class.isAssignableFrom(valueType)) { + return (T) (OBJECT_MAPPER.readTree(json)); + } else { + return OBJECT_MAPPER.readValue(json, valueType); + } + } catch (Exception e) { + LOG.error("Erro ao gerar objeto a partir do JSON : " + json, e); + } + + return null; + } + +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 77f9240..7eaa6ee 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -11,5 +11,10 @@ amazon: dynamodb: endpoint: http://dynamodb.us-east-1.amazonaws.com + queue: + product-creation: products-creation + region: us-east-1 + + From 5129f23390767d1025874d4a53fbd992e16490de Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 14:55:52 -0300 Subject: [PATCH 36/55] refactor corrected queue name --- src/main/resources/application.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 7eaa6ee..572f4a9 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -12,7 +12,7 @@ amazon: endpoint: http://dynamodb.us-east-1.amazonaws.com queue: - product-creation: products-creation + product-creation: product-creation region: us-east-1 From ee7ccffcdfb8420bc13f88e0108972087e96a822 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 15:27:01 -0300 Subject: [PATCH 37/55] implemented asynchronous processing in product creation with SQS --- .../app/controllers/ProductController.java | 2 +- .../dorotech/app/services/ProductService.java | 4 +++- .../app/services/impl/ProductServiceImpl.java | 22 +++++++++++++++++-- .../app/sqs/ProductMessageConsumer.java | 12 +++++++--- .../app/sqs/ProductMessageProducer.java | 2 +- 5 files changed, 34 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/br/dorotech/app/controllers/ProductController.java b/src/main/java/com/br/dorotech/app/controllers/ProductController.java index d7b4ba0..7d1bb1b 100644 --- a/src/main/java/com/br/dorotech/app/controllers/ProductController.java +++ b/src/main/java/com/br/dorotech/app/controllers/ProductController.java @@ -31,7 +31,7 @@ public ResponseEntity> getAllProducts() { @PostMapping(value = "/createProduct") public ResponseEntity createProduct(@RequestBody ProductDTO productDTO) { - final ProductDTO createProductDTO = productService.createNewProduct(productDTO); + final ProductDTO createProductDTO = productService.startProductCreation(productDTO); return new ResponseEntity<>(createProductDTO, HttpStatus.CREATED); } diff --git a/src/main/java/com/br/dorotech/app/services/ProductService.java b/src/main/java/com/br/dorotech/app/services/ProductService.java index 0405679..022070c 100644 --- a/src/main/java/com/br/dorotech/app/services/ProductService.java +++ b/src/main/java/com/br/dorotech/app/services/ProductService.java @@ -6,7 +6,9 @@ public interface ProductService { - ProductDTO createNewProduct(ProductDTO productDTO); + ProductDTO startProductCreation(ProductDTO productDTO); + + void finishProductCreation(ProductDTO productDTO); List findAllProducts(); diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index 8a0e35a..22be9d0 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -6,7 +6,11 @@ import com.br.dorotech.app.models.entities.Product; import com.br.dorotech.app.repositories.ProductRepository; import com.br.dorotech.app.services.ProductService; +import com.br.dorotech.app.sqs.ProductMessageProducer; +import com.br.dorotech.app.util.JsonUtil; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; @@ -19,16 +23,29 @@ @Service @RequiredArgsConstructor +@Slf4j public class ProductServiceImpl implements ProductService { private final ProductRepository productRepository; + private final ProductMessageProducer productMessageProducer; + + @Value("${amazon.queue.product-creation}") + private String queueName; + @Override - public ProductDTO createNewProduct(ProductDTO productDTO) { - productRepository.save(productsBuilder(productDTO)); + public ProductDTO startProductCreation(ProductDTO productDTO) { + productMessageProducer.sentToQueue(queueName, JsonUtil.writeValueAsString(productDTO)); + log.info("***** PRODUCT CREATION DATA SENT TO QUEUE: " + queueName + ", PRODUCT NAME: " + productDTO.getName() + + ", PRODUCT DESCRIPTION: " + productDTO.getDescription()); return productDTO; } + @Override + public void finishProductCreation(ProductDTO productDTO){ + productRepository.save(productsBuilder(productDTO)); + } + @Override public List findAllProducts() { List productList = (List) productRepository.findAll(); @@ -56,4 +73,5 @@ public ProductDTO updateProduct(String id, ProductDTO productDTO) { productRepository.save(productUpdated); return productDTO; } + } diff --git a/src/main/java/com/br/dorotech/app/sqs/ProductMessageConsumer.java b/src/main/java/com/br/dorotech/app/sqs/ProductMessageConsumer.java index 47d905f..3560073 100644 --- a/src/main/java/com/br/dorotech/app/sqs/ProductMessageConsumer.java +++ b/src/main/java/com/br/dorotech/app/sqs/ProductMessageConsumer.java @@ -15,19 +15,25 @@ @RequiredArgsConstructor public class ProductMessageConsumer { - private ProductService productService; + private final ProductService productService; @Value("${amazon.queue.product-creation}") private String queueName; - @JmsListener(destination = "${amazon.queue.attendance}") + @JmsListener(destination = "${amazon.queue.product-creation}") public void messageConsumer(@Payload String message) { ProductDTO productDTO = JsonUtil.readValue(message, ProductDTO.class); log.info("***** PRODUCT CREATED: " + queueName + ", PRODUCT NAME: " + productDTO.getName() + ", PRODUCT DESCRIPTION: " + productDTO.getDescription()); - //IMPLEMENTAR CHAMADA EM SERVICE + System.out.println("***********************************************************************************************"); + System.out.println(); + System.out.println("Message consumed, Product Name : " + productDTO.getName() + " , Product Description : " + productDTO.getDescription()); + System.out.println(); + System.out.println("***********************************************************************************************"); + + productService.finishProductCreation(productDTO); } } \ No newline at end of file diff --git a/src/main/java/com/br/dorotech/app/sqs/ProductMessageProducer.java b/src/main/java/com/br/dorotech/app/sqs/ProductMessageProducer.java index 4135e91..a7e2bf0 100644 --- a/src/main/java/com/br/dorotech/app/sqs/ProductMessageProducer.java +++ b/src/main/java/com/br/dorotech/app/sqs/ProductMessageProducer.java @@ -9,7 +9,7 @@ @RequiredArgsConstructor public class ProductMessageProducer { - private AmazonSQS amazonSQS; + private final AmazonSQS amazonSQS; public void sentToQueue(final String queueName, final String message) { amazonSQS.sendMessage(new SendMessageRequest() From 238975f5ebae1878943f1ac51463ad0426c6bce8 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 15:43:24 -0300 Subject: [PATCH 38/55] refactor name changing --- src/main/java/com/br/dorotech/app/configs/SwaggerConfig.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/br/dorotech/app/configs/SwaggerConfig.java b/src/main/java/com/br/dorotech/app/configs/SwaggerConfig.java index a6f4fe0..f2d0a9d 100644 --- a/src/main/java/com/br/dorotech/app/configs/SwaggerConfig.java +++ b/src/main/java/com/br/dorotech/app/configs/SwaggerConfig.java @@ -29,7 +29,7 @@ public Docket DorotechApi() { private ApiInfo metaData() { return new ApiInfoBuilder() .title("Spring Boot REST API - Dorotech") - .description("\"Spring Boot REST API Attendance\"") + .description("\"Spring Boot REST API Dorotech App\"") .version("1.0.0") .license("Apache License Version 2.0") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"") From 30df035b9a27d5a7ba9449f64c40298d615bafa0 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 19:39:03 -0300 Subject: [PATCH 39/55] added buildspec and dockerfile --- Dockerfile | 4 ++++ buildspec.yml | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 Dockerfile create mode 100644 buildspec.yml diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e8cd48b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,4 @@ +FROM adoptopenjdk/openjdk11:alpine +EXPOSE:8081 +ADD target/dorotech_teste-1.0-SNAPSHOT.jar dorotech_teste-1.0-SNAPSHOT.jar +ENTRYPOINT ["java","-jar","/dorotech_teste-1.0-SNAPSHOT.jar"] \ No newline at end of file diff --git a/buildspec.yml b/buildspec.yml new file mode 100644 index 0000000..d83f88c --- /dev/null +++ b/buildspec.yml @@ -0,0 +1,32 @@ +version: 0.2 + + +phases: + pre_build: + commands: + - mvn clean install + - echo Logging in to Amazon ECR... + - aws --version + - $(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email) + - REPOSITORY_URI=237601488461.dkr.ecr.us-east-1.amazonaws.com/myrepository + - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7) + - IMAGE_TAG=build-$(echo $CODEBUILD_BUILD_ID | awk -F":" '{print $2}') + build: + commands: + - echo Build started on `date` + - echo Building the Docker image... + - docker build -t $REPOSITORY_URI:latest . + - docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG + post_build: + commands: + - echo Build completed on `date` + - echo Pushing the Docker images... + - docker push $REPOSITORY_URI:latest + - docker push $REPOSITORY_URI:$IMAGE_TAG + - echo Writing image definitions file... + - printf '[{"name":"dorotech-test","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json + - cat imagedefinitions.json +artifacts: + files: + - imagedefinitions.json + - target/dorotech_teste-1.0-SNAPSHOT.jar \ No newline at end of file From d2583435f1a20ad35e7dfa387af25b4300adb3b6 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 19:42:19 -0300 Subject: [PATCH 40/55] refactor removed println --- .../com/br/dorotech/app/sqs/ProductMessageConsumer.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/main/java/com/br/dorotech/app/sqs/ProductMessageConsumer.java b/src/main/java/com/br/dorotech/app/sqs/ProductMessageConsumer.java index 3560073..1f3bc89 100644 --- a/src/main/java/com/br/dorotech/app/sqs/ProductMessageConsumer.java +++ b/src/main/java/com/br/dorotech/app/sqs/ProductMessageConsumer.java @@ -27,12 +27,6 @@ public void messageConsumer(@Payload String message) { log.info("***** PRODUCT CREATED: " + queueName + ", PRODUCT NAME: " + productDTO.getName() + ", PRODUCT DESCRIPTION: " + productDTO.getDescription()); - System.out.println("***********************************************************************************************"); - System.out.println(); - System.out.println("Message consumed, Product Name : " + productDTO.getName() + " , Product Description : " + productDTO.getDescription()); - System.out.println(); - System.out.println("***********************************************************************************************"); - productService.finishProductCreation(productDTO); } From adad072f174b766b4aee50d8227e3546a6a80401 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 20:03:19 -0300 Subject: [PATCH 41/55] refactor changed buildspec file --- buildspec.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/buildspec.yml b/buildspec.yml index d83f88c..4014fd6 100644 --- a/buildspec.yml +++ b/buildspec.yml @@ -7,7 +7,6 @@ phases: - mvn clean install - echo Logging in to Amazon ECR... - aws --version - - $(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email) - REPOSITORY_URI=237601488461.dkr.ecr.us-east-1.amazonaws.com/myrepository - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7) - IMAGE_TAG=build-$(echo $CODEBUILD_BUILD_ID | awk -F":" '{print $2}') From ed1b437e5940c98d67345dbcb721202e9a254a77 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 20:15:00 -0300 Subject: [PATCH 42/55] refactor changed buildspec file --- buildspec.yml | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/buildspec.yml b/buildspec.yml index 4014fd6..53a832e 100644 --- a/buildspec.yml +++ b/buildspec.yml @@ -1,31 +1,20 @@ version: 0.2 - phases: + install: + runtime-versions: + java: corretto11 pre_build: commands: - - mvn clean install - - echo Logging in to Amazon ECR... - - aws --version - - REPOSITORY_URI=237601488461.dkr.ecr.us-east-1.amazonaws.com/myrepository - - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7) - - IMAGE_TAG=build-$(echo $CODEBUILD_BUILD_ID | awk -F":" '{print $2}') + - echo skipped on date... build: commands: - - echo Build started on `date` - - echo Building the Docker image... - - docker build -t $REPOSITORY_URI:latest . - - docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG + - echo Maven Build on `date` + - java -version + - mvn clean package post_build: commands: - echo Build completed on `date` - - echo Pushing the Docker images... - - docker push $REPOSITORY_URI:latest - - docker push $REPOSITORY_URI:$IMAGE_TAG - - echo Writing image definitions file... - - printf '[{"name":"dorotech-test","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json - - cat imagedefinitions.json artifacts: files: - - imagedefinitions.json - target/dorotech_teste-1.0-SNAPSHOT.jar \ No newline at end of file From f9db81d320f8b069b152ba3e27bac59563903f93 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 20:18:06 -0300 Subject: [PATCH 43/55] refactor changed buildspec file --- buildspec.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildspec.yml b/buildspec.yml index 53a832e..24e2d13 100644 --- a/buildspec.yml +++ b/buildspec.yml @@ -3,7 +3,7 @@ version: 0.2 phases: install: runtime-versions: - java: corretto11 + java: corretto17 pre_build: commands: - echo skipped on date... From ccc2d9dbe30a3bb9e8c184dc08405445f53818b4 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 20:53:09 -0300 Subject: [PATCH 44/55] refactor changed buildspec file --- buildspec.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/buildspec.yml b/buildspec.yml index 24e2d13..8020b67 100644 --- a/buildspec.yml +++ b/buildspec.yml @@ -15,6 +15,8 @@ phases: post_build: commands: - echo Build completed on `date` + - cat imagedefinitions.json artifacts: files: + - imagedefinitions.json - target/dorotech_teste-1.0-SNAPSHOT.jar \ No newline at end of file From ed0a908529e48d00c9d35f240165ce3f5b6d80b0 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 21:10:27 -0300 Subject: [PATCH 45/55] refactor corrected buildspec file to integrate aws codepipeline --- buildspec.yml | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/buildspec.yml b/buildspec.yml index 8020b67..8f47bfc 100644 --- a/buildspec.yml +++ b/buildspec.yml @@ -1,20 +1,29 @@ version: 0.2 + phases: - install: - runtime-versions: - java: corretto17 pre_build: commands: - - echo skipped on date... + - mvn clean install + - echo Logging in to Amazon ECR... + - aws --version + - aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 237601488461.dkr.ecr.us-east-1.amazonaws.com + - REPOSITORY_URI=237601488461.dkr.ecr.us-east-1.amazonaws.com/myrepository + - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7) + - IMAGE_TAG=build-$(echo $CODEBUILD_BUILD_ID | awk -F":" '{print $2}') build: commands: - - echo Maven Build on `date` - - java -version - - mvn clean package + - echo Build started on `date` + - echo Building the Docker image... + - docker build -t myrepository . + - docker tag myrepository:latest 237601488461.dkr.ecr.us-east-1.amazonaws.com/myrepository:latest post_build: commands: - echo Build completed on `date` + - echo Pushing the Docker images... + - docker push 237601488461.dkr.ecr.us-east-1.amazonaws.com/myrepository:latest + - echo Writing image definitions file... + - printf '[{"name":"dorotech-api","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json - cat imagedefinitions.json artifacts: files: From 671429a82fe1b6c5ac10ef7002fc577348ae70fc Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 21:25:38 -0300 Subject: [PATCH 46/55] refactor corrected buildspec file to integrate aws codepipeline --- buildspec.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildspec.yml b/buildspec.yml index 8f47bfc..e9a0def 100644 --- a/buildspec.yml +++ b/buildspec.yml @@ -23,7 +23,7 @@ phases: - echo Pushing the Docker images... - docker push 237601488461.dkr.ecr.us-east-1.amazonaws.com/myrepository:latest - echo Writing image definitions file... - - printf '[{"name":"dorotech-api","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json + - printf '[{"name":"myrepository","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json - cat imagedefinitions.json artifacts: files: From 4b38020574d05d461504467a1e8487bfc58c4be7 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 22:54:55 -0300 Subject: [PATCH 47/55] refactor corrected Dockerfile --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index e8cd48b..a37e530 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ FROM adoptopenjdk/openjdk11:alpine -EXPOSE:8081 +EXPOSE:81 ADD target/dorotech_teste-1.0-SNAPSHOT.jar dorotech_teste-1.0-SNAPSHOT.jar ENTRYPOINT ["java","-jar","/dorotech_teste-1.0-SNAPSHOT.jar"] \ No newline at end of file From 9f07be3eead2faeeca00f50172ea2dec3f1cad79 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Sun, 11 Dec 2022 22:57:39 -0300 Subject: [PATCH 48/55] refactor corrected Dockerfile --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index a37e530..fbe177a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ FROM adoptopenjdk/openjdk11:alpine -EXPOSE:81 +EXPOSE 81 ADD target/dorotech_teste-1.0-SNAPSHOT.jar dorotech_teste-1.0-SNAPSHOT.jar ENTRYPOINT ["java","-jar","/dorotech_teste-1.0-SNAPSHOT.jar"] \ No newline at end of file From 8779ed8558a4ab93a1f38c6740fac6382c619059 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Mon, 12 Dec 2022 15:27:18 -0300 Subject: [PATCH 49/55] refactor corrected container name --- buildspec.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildspec.yml b/buildspec.yml index e9a0def..19cc8a5 100644 --- a/buildspec.yml +++ b/buildspec.yml @@ -23,7 +23,7 @@ phases: - echo Pushing the Docker images... - docker push 237601488461.dkr.ecr.us-east-1.amazonaws.com/myrepository:latest - echo Writing image definitions file... - - printf '[{"name":"myrepository","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json + - printf '[{"name":"container","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json - cat imagedefinitions.json artifacts: files: From 05bfd6e1015e26afe0f3bc4072363e89b9291b71 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Mon, 12 Dec 2022 15:48:19 -0300 Subject: [PATCH 50/55] changed java image source --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index fbe177a..490f145 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM adoptopenjdk/openjdk11:alpine +FROM public.ecr.aws/amazoncorretto/amazoncorretto:11 EXPOSE 81 ADD target/dorotech_teste-1.0-SNAPSHOT.jar dorotech_teste-1.0-SNAPSHOT.jar ENTRYPOINT ["java","-jar","/dorotech_teste-1.0-SNAPSHOT.jar"] \ No newline at end of file From 30ec0443cd3f45f305ebe4d086ed8e8a322b9aed Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Mon, 12 Dec 2022 18:16:14 -0300 Subject: [PATCH 51/55] created documentation readme --- README.md | 96 ++++++++++++++++++++++--------------------------------- 1 file changed, 39 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index d171857..6c4b24d 100644 --- a/README.md +++ b/README.md @@ -4,73 +4,55 @@ Somos uma empresa com clientes que atuam em vários segmentos do mercado, com di Gostamos de compor nossos times com profissionais multidisciplinares, que tenham alta capacidade de aprendizado, sejam detalhistas, resilientes, questionadores e curiosos. Você, como Java Developer, será o responsável por implementar, dar manutenção, aplicar correções e propor soluções em projetos de software. -## Requisitos do desafio: + +### Documentação ``` -1. Criar um código que execute um CRUD(Create, Read, Update, Delete) em uma tabela para gerenciar produtos eletrônicos. -2. Use um banco NoSQL(DynamoDB é um diferencial). -3. Utilizar Spring como framework(Quarkus é um diferencial). -4. Dados da tabela a ser criada no banco: - - Products: - name, - description, - price, - amount. +1. Desenvolvido aplicação CRUD para cadastro, recuperação, update e delete. +2. Foi utilizado o Framework SpringBoot para desenvolvimento. -Seja criativo! fazer o melhor não é ser complexo. -``` +3. Os dados estão sendo persistidos no Banco de dados NOSQl DynamoDB, tambem estou utilizando Docker, ECR, e ECS fargate para deploy da aplicação. -## Dicas e Informações Valiosas -``` -O que gostaríamos de ver em seu teste: - - Convenção de nome em classes, objetos, variáveis, métodos e etc. - Faça commits regulares. Eles são melhores do que um commit gigantesco. Gostaríamos de ver commits organizados e padronizados, então capriche neles! - Bônus 1 Quarkus & AWS, implementação de uma lambda AWS utilizando framework Quarkus - Bônus 2 Testes automatizados - Observação: Nenhum dos itens acima é obrigatório. - -O que o seu Teste não deve ter: - Saber que não foi você quem implementou o projeto. - Várias bibliotecas instaladas sem uso. - Falta de organização de código. - Falta de documentação. - Nome de variáveis sem sentido ou sem padrão de nomes. - Histórico de commits desorganizado e despadronizado. - -Boa Sorte!! -``` +4. Utilizei processamento assincrono para criação de um novo produto, utilizando o SQS da AWS + +5. As variaveis de ambiente com as credenciais da AWS serão enviadas ao avaliador + Documentação + +6. A aplicação foi configurada para rodar na porta 8081, assim como a porta do container que esta sendo exposta é a porta 81 + +7. É possivil testar e verificar parte da documentação gerada pelo swagger no link gerado pelo mesmo: http://localhost:8081/swagger-ui.html#/ + +8. Como rodar manualmente: + - va ao diretorio raiz do projeto e acesse a pasta target + - em seguida abra no terminal a localização e entre com o seguinte comando + - mvn spring-boot:run + Obs: atente-se as variaveis de ambiente + +9. Caso deseje rodar via IDE recomendo fortemente o uso do Intellij, porem caso use outra IDE não deve encontrar grandes problemas pois todo o gerenciamento +de dependencias esta sendo feito pelo maven, basta apenas ter atenção ao detalhe do anotation processor do lombok e tambem adicionar as variaveis de ambiente -## Itens obrigatórios -``` -1. Possibilitar a criação de um novo produto -2. Possibilitar consulta de todos os produtos no banco de dados. -3. Possibilitar consultar um produto específico pelo id. -4. Permitir a exclusão de um produto. -5. Persistir os dados na base. ``` -## Itens desejáveis +### Métodos HTTP ``` -1. Criação de Testes unitários. -2. Utilização de alguma ferramenta AWS(API Gateway, Lambda, SQS, SNS, EC2,..). -3. Docker. -4. Utilização de algum padrão de projeto. +--->>>Local + - Busca todos os produtos - GET : http://localhost:8081/products/getAllProducts + - Cria produto - POST : http://localhost:8081/products/createProduct + - Encontra produto por ID - GET : GET http://localhost:8081/products/getProductById/{{id}} + - Deleta produto por ID - DELETE : http://localhost:8081/products/deleteProduct/{{id}} + - Atualiza produto por ID - UPDATE : http://localhost:8081/products/updateProduct/{{id}} + ``` -### Instruções para entrega +### Funcionamento do programa ``` -1. Fazer um fork desse repositório -2. Criar um branch com o seu primeiro e último nome -git checkout -b joao-silva + OBS: Recomendo a utilizção do Swagger para fins de testes manuais. -3. Escreva a documentação da sua aplicação -Você deve, substituir o conteúdo do arquivo README.md e escrever a documentação da sua aplicação, com os seguintes tópicos: - - Projeto: Descreva o projeto e como você o executou. Seja objetivo. - - Tecnologias: Descreva quais tecnologias foram utilizadas, enumerando versões (se necessário) e os links para suas documentações, quais bibliotecas instalou e porque. -Como compilar e rodar: Descreva como compilar e rodar sua aplicação. - -4. Faça uma Pull Request -Após implementada a solução, crie uma pull request com o seu projeto para esse repositório, avise o recrutador. -``` + - Ao iniciar o programa localmente o mesmo ira rodar na porta local 8081 e necessitará das variaveis de ambiente para se conectar a AWS + e por fim se conectar ao DynamoDB e ao sistema de filas SQS + - Ja existe uma carga de dados no Banco então se ao iniciar o software e acessar o metodo GET /getAllProducts esse por sua vez deverá retornar os produtos do banco + - Para criar um produto isso deverá ser feito através do metodo POST /createProduct, a criação de produtos ocorrerá em background com o DTO do produto sendo enviado + para uma fila SQS, e só após a fila ser consumida esse novo produto será persistido no banco. + - Para fazer um update, primeiro deve-se saber o ID do produto em seguida atualizar as informação e então enviar a requisição. + - Para se fazer um delete também é necessário saber o ID do produto que se deseja excluir. From f4acbc296f491109b0022754c6d064daaceb8fda Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Mon, 12 Dec 2022 18:22:14 -0300 Subject: [PATCH 52/55] refactor removed unused imports --- src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java b/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java index 5c5bd2d..3a5c8b8 100644 --- a/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java +++ b/src/main/java/com/br/dorotech/app/models/dtos/ProductDTO.java @@ -3,9 +3,7 @@ import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; -import lombok.Getter; import lombok.NoArgsConstructor; -import lombok.Setter; @Builder @Data From 8f0cd8805eb7616fbdb880c81ae5e98d96d3df8e Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Mon, 12 Dec 2022 18:31:28 -0300 Subject: [PATCH 53/55] changed method getAll return type to show product IDs thats gonna be useful to update and delete --- .../br/dorotech/app/controllers/ProductController.java | 7 ++++--- .../com/br/dorotech/app/services/ProductService.java | 3 ++- .../dorotech/app/services/impl/ProductServiceImpl.java | 9 ++------- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/br/dorotech/app/controllers/ProductController.java b/src/main/java/com/br/dorotech/app/controllers/ProductController.java index 7d1bb1b..aed6514 100644 --- a/src/main/java/com/br/dorotech/app/controllers/ProductController.java +++ b/src/main/java/com/br/dorotech/app/controllers/ProductController.java @@ -1,6 +1,7 @@ package com.br.dorotech.app.controllers; import com.br.dorotech.app.models.dtos.ProductDTO; +import com.br.dorotech.app.models.entities.Product; import com.br.dorotech.app.services.ProductService; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; @@ -24,9 +25,9 @@ public class ProductController { private final ProductService productService; @GetMapping(value = "/getAllProducts") - public ResponseEntity> getAllProducts() { - final List productDTOS = productService.findAllProducts(); - return new ResponseEntity<>(productDTOS, HttpStatus.OK); + public ResponseEntity> getAllProducts() { + final List product = productService.findAllProducts(); + return new ResponseEntity<>(product, HttpStatus.OK); } @PostMapping(value = "/createProduct") diff --git a/src/main/java/com/br/dorotech/app/services/ProductService.java b/src/main/java/com/br/dorotech/app/services/ProductService.java index 022070c..9e58c6d 100644 --- a/src/main/java/com/br/dorotech/app/services/ProductService.java +++ b/src/main/java/com/br/dorotech/app/services/ProductService.java @@ -1,6 +1,7 @@ package com.br.dorotech.app.services; import com.br.dorotech.app.models.dtos.ProductDTO; +import com.br.dorotech.app.models.entities.Product; import java.util.List; @@ -10,7 +11,7 @@ public interface ProductService { void finishProductCreation(ProductDTO productDTO); - List findAllProducts(); + List findAllProducts(); ProductDTO findProductById(String id); diff --git a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java index 22be9d0..932473f 100644 --- a/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java +++ b/src/main/java/com/br/dorotech/app/services/impl/ProductServiceImpl.java @@ -1,7 +1,6 @@ package com.br.dorotech.app.services.impl; import com.br.dorotech.app.exceptions.ResourceNotFoundException; -import com.br.dorotech.app.helper.ProductHelper; import com.br.dorotech.app.models.dtos.ProductDTO; import com.br.dorotech.app.models.entities.Product; import com.br.dorotech.app.repositories.ProductRepository; @@ -15,7 +14,6 @@ import org.springframework.stereotype.Service; import java.util.List; -import java.util.stream.Collectors; import static com.br.dorotech.app.helper.ProductHelper.productsBuilder; import static com.br.dorotech.app.helper.ProductHelper.productsDTOBuilder; @@ -47,11 +45,8 @@ public void finishProductCreation(ProductDTO productDTO){ } @Override - public List findAllProducts() { - List productList = (List) productRepository.findAll(); - return productList.stream() - .map(ProductHelper::productsDTOBuilder) - .collect(Collectors.toList()); + public List findAllProducts() { + return (List) productRepository.findAll(); } @Override From bd8e75ca0d94e17f847edfee299f6bf2474624b8 Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Mon, 12 Dec 2022 19:23:05 -0300 Subject: [PATCH 54/55] changed readme --- README.md | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 6c4b24d..eab6a59 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,22 @@ # Desafio Back End Java na DoroTech -Somos uma empresa com clientes que atuam em vários segmentos do mercado, com diferentes tecnologias, culturas e desafios. - -Gostamos de compor nossos times com profissionais multidisciplinares, que tenham alta capacidade de aprendizado, sejam detalhistas, resilientes, questionadores e curiosos. Você, como Java Developer, será o responsável por implementar, dar manutenção, aplicar correções e propor soluções em projetos de software. - - ### Documentação ``` -1. Desenvolvido aplicação CRUD para cadastro, recuperação, update e delete. -2. Foi utilizado o Framework SpringBoot para desenvolvimento. -3. Os dados estão sendo persistidos no Banco de dados NOSQl DynamoDB, tambem estou utilizando Docker, ECR, e ECS fargate para deploy da aplicação. +1. Desenvolvido aplicação CRUD para cadastro, recuperação, update e delete de produtos. + +2. Foi utilizado o Framework SpringBoot para desenvolvimento e java 11. + +3. Os dados estão sendo persistidos no Banco de dados NOSQl DynamoDB, tambem estou utilizando Docker, ECR, ECS, fargate, CodeBuild e CodePipeline para deploy da aplicação. 4. Utilizei processamento assincrono para criação de um novo produto, utilizando o SQS da AWS -5. As variaveis de ambiente com as credenciais da AWS serão enviadas ao avaliador - Documentação +5. As variaveis de ambiente com as credenciais da AWS para testar a aplicação serão enviadas ao avaliador 6. A aplicação foi configurada para rodar na porta 8081, assim como a porta do container que esta sendo exposta é a porta 81 -7. É possivil testar e verificar parte da documentação gerada pelo swagger no link gerado pelo mesmo: http://localhost:8081/swagger-ui.html#/ +7. É possivil testar e verificar parte da documentação gerada pelo swagger no link gerado pelo mesmo quando rodando local: http://localhost:8081/swagger-ui.html#/ 8. Como rodar manualmente: - va ao diretorio raiz do projeto e acesse a pasta target @@ -31,6 +27,7 @@ Gostamos de compor nossos times com profissionais multidisciplinares, que tenham 9. Caso deseje rodar via IDE recomendo fortemente o uso do Intellij, porem caso use outra IDE não deve encontrar grandes problemas pois todo o gerenciamento de dependencias esta sendo feito pelo maven, basta apenas ter atenção ao detalhe do anotation processor do lombok e tambem adicionar as variaveis de ambiente + ``` ### Métodos HTTP @@ -47,7 +44,7 @@ de dependencias esta sendo feito pelo maven, basta apenas ter atenção ao detal ### Funcionamento do programa ``` - OBS: Recomendo a utilizção do Swagger para fins de testes manuais. + OBS: Recomendo a utilização do Swagger para fins de testes manuais. Link Segue Acima - Ao iniciar o programa localmente o mesmo ira rodar na porta local 8081 e necessitará das variaveis de ambiente para se conectar a AWS e por fim se conectar ao DynamoDB e ao sistema de filas SQS From 338817ab3f37cf1e82abc834b1aa7a9907d494ba Mon Sep 17 00:00:00 2001 From: smk-1991 Date: Mon, 12 Dec 2022 20:00:45 -0300 Subject: [PATCH 55/55] changed readme --- README.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index eab6a59..c0c6ec2 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,9 @@ ### Documentação ``` - 1. Desenvolvido aplicação CRUD para cadastro, recuperação, update e delete de produtos. -2. Foi utilizado o Framework SpringBoot para desenvolvimento e java 11. +2. Foi utilizado o Framework SpringBoot para desenvolvimento, java 11, Maven, Swagger e Lombok. 3. Os dados estão sendo persistidos no Banco de dados NOSQl DynamoDB, tambem estou utilizando Docker, ECR, ECS, fargate, CodeBuild e CodePipeline para deploy da aplicação. @@ -23,6 +22,9 @@ - em seguida abra no terminal a localização e entre com o seguinte comando - mvn spring-boot:run Obs: atente-se as variaveis de ambiente + +9. Acesso através da API publica : http://54.237.216.243:8081/ + rotas + Acesso atraǘes da API publica + Swagger : http://54.237.216.243:8081/swagger-ui.html#/ 9. Caso deseje rodar via IDE recomendo fortemente o uso do Intellij, porem caso use outra IDE não deve encontrar grandes problemas pois todo o gerenciamento de dependencias esta sendo feito pelo maven, basta apenas ter atenção ao detalhe do anotation processor do lombok e tambem adicionar as variaveis de ambiente @@ -53,3 +55,7 @@ de dependencias esta sendo feito pelo maven, basta apenas ter atenção ao detal para uma fila SQS, e só após a fila ser consumida esse novo produto será persistido no banco. - Para fazer um update, primeiro deve-se saber o ID do produto em seguida atualizar as informação e então enviar a requisição. - Para se fazer um delete também é necessário saber o ID do produto que se deseja excluir. + +``` + +