├── order-microservice ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── ms │ │ │ │ └── order │ │ │ │ ├── dto │ │ │ │ ├── enums │ │ │ │ │ ├── OrderInboxStatus.java │ │ │ │ │ ├── OrderStatus.java │ │ │ │ │ ├── OrderOutboxStatus.java │ │ │ │ │ └── ProductOutboxStatus.java │ │ │ │ ├── request │ │ │ │ │ └── OrderRequestDto.java │ │ │ │ ├── event │ │ │ │ │ └── StockCreateEvent.java │ │ │ │ └── response │ │ │ │ │ └── OrderDebeziumResponse.java │ │ │ │ ├── repository │ │ │ │ ├── OrderRepository.java │ │ │ │ ├── OrderOutboxRepository.java │ │ │ │ └── OrderInboxRepository.java │ │ │ │ ├── OrderMicroserviceApplication.java │ │ │ │ ├── util │ │ │ │ └── Operation.java │ │ │ │ ├── controller │ │ │ │ └── OrderController.java │ │ │ │ ├── entity │ │ │ │ ├── OrderInbox.java │ │ │ │ ├── Order.java │ │ │ │ └── OrderOutbox.java │ │ │ │ ├── service │ │ │ │ ├── OutboxService.java │ │ │ │ └── OrderService.java │ │ │ │ ├── configuration │ │ │ │ ├── DebeziumConnectorConfig.java │ │ │ │ └── KafkaConfig.java │ │ │ │ ├── listener │ │ │ │ └── DebeziumSourceEventListener.java │ │ │ │ └── consumer │ │ │ │ └── OrderConsumer.java │ │ └── resources │ │ │ └── application.yml │ └── test │ │ └── java │ │ └── com │ │ └── ms │ │ └── order │ │ └── OrderMicroserviceApplicationTests.java ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── .gitignore ├── pom.xml ├── mvnw.cmd └── mvnw ├── stock-microservice ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── ms │ │ │ │ └── stock │ │ │ │ ├── dto │ │ │ │ ├── enums │ │ │ │ │ └── ProductOutboxStatus.java │ │ │ │ ├── request │ │ │ │ │ └── OrderRequestDto.java │ │ │ │ ├── event │ │ │ │ │ └── StockCreateEvent.java │ │ │ │ └── response │ │ │ │ │ └── OrderDebeziumResponse.java │ │ │ │ ├── StockMicroserviceApplication.java │ │ │ │ ├── repository │ │ │ │ ├── ProductInboxRepository.java │ │ │ │ ├── ProductOutboxRepository.java │ │ │ │ └── ProductsRepository.java │ │ │ │ ├── util │ │ │ │ └── Operation.java │ │ │ │ ├── runner │ │ │ │ └── ProductRunner.java │ │ │ │ ├── entity │ │ │ │ ├── ProductInbox.java │ │ │ │ ├── Products.java │ │ │ │ └── ProductOutbox.java │ │ │ │ ├── configuration │ │ │ │ ├── DebeziumConnectorConfig.java │ │ │ │ └── KafkaConfig.java │ │ │ │ ├── consumer │ │ │ │ └── OrderCreatedConsumer.java │ │ │ │ ├── listener │ │ │ │ └── DebeziumSourceEventListener.java │ │ │ │ └── service │ │ │ │ └── StockService.java │ │ └── resources │ │ │ └── application.yml │ └── test │ │ └── java │ │ └── com │ │ └── ms │ │ └── stock │ │ └── StockMicroserviceApplicationTests.java ├── .gitignore ├── pom.xml ├── mvnw.cmd └── mvnw ├── readme.md └── docker-compose.yml /order-microservice/src/main/java/com/ms/order/dto/enums/OrderInboxStatus.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.dto.enums; 2 | 3 | public enum OrderInboxStatus { 4 | CREATED, 5 | PROCESSED 6 | } 7 | -------------------------------------------------------------------------------- /order-microservice/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tugayesilyurt/spring-embedded-debezium-kafka-inbox-outbox-pattern/HEAD/order-microservice/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/dto/enums/OrderStatus.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.dto.enums; 2 | 3 | public enum OrderStatus { 4 | CREATED, 5 | FAILED, 6 | COMPLETED 7 | } 8 | -------------------------------------------------------------------------------- /stock-microservice/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tugayesilyurt/spring-embedded-debezium-kafka-inbox-outbox-pattern/HEAD/stock-microservice/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/dto/enums/OrderOutboxStatus.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.dto.enums; 2 | 3 | public enum OrderOutboxStatus { 4 | CREATED, 5 | PROCESSED, 6 | DONE 7 | } 8 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/dto/enums/ProductOutboxStatus.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.dto.enums; 2 | 3 | public enum ProductOutboxStatus { 4 | CREATED, 5 | FAILED, 6 | DONE 7 | } 8 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/dto/enums/ProductOutboxStatus.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.dto.enums; 2 | 3 | public enum ProductOutboxStatus { 4 | CREATED, 5 | FAILED, 6 | DONE 7 | } 8 | -------------------------------------------------------------------------------- /order-microservice/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 7002 3 | 4 | spring: 5 | jpa: 6 | hibernate: 7 | ddl-auto: update 8 | datasource: 9 | url: jdbc:postgresql://localhost:5432/saga 10 | username: saga 11 | password: saga 12 | 13 | 14 | kafka: 15 | bootstrapAddress: localhost:29092 16 | 17 | -------------------------------------------------------------------------------- /stock-microservice/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 7003 3 | 4 | spring: 5 | jpa: 6 | hibernate: 7 | ddl-auto: update 8 | datasource: 9 | url: jdbc:postgresql://localhost:5432/saga 10 | username: saga 11 | password: saga 12 | 13 | 14 | kafka: 15 | bootstrapAddress: localhost:29092 16 | 17 | 18 | -------------------------------------------------------------------------------- /order-microservice/src/test/java/com/ms/order/OrderMicroserviceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.ms.order; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class OrderMicroserviceApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /stock-microservice/src/test/java/com/ms/stock/StockMicroserviceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class StockMicroserviceApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/repository/OrderRepository.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.repository; 2 | 3 | import com.ms.order.entity.Order; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface OrderRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/dto/request/OrderRequestDto.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.dto.request; 2 | 3 | import lombok.*; 4 | 5 | import java.math.BigDecimal; 6 | import java.util.List; 7 | 8 | @Data 9 | @Builder 10 | @AllArgsConstructor 11 | @NoArgsConstructor 12 | public class OrderRequestDto { 13 | 14 | private Long productId; 15 | private BigDecimal totalAmount; 16 | private Long userId; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/dto/event/StockCreateEvent.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.dto.event; 2 | 3 | import lombok.*; 4 | 5 | import java.math.BigDecimal; 6 | 7 | @Data 8 | @Builder 9 | @NoArgsConstructor 10 | @AllArgsConstructor 11 | public class StockCreateEvent { 12 | 13 | private Long orderId; 14 | private BigDecimal totalAmount; 15 | private String idempotentKey; 16 | private Long productId; 17 | 18 | } -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/OrderMicroserviceApplication.java: -------------------------------------------------------------------------------- 1 | package com.ms.order; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class OrderMicroserviceApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(OrderMicroserviceApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/StockMicroserviceApplication.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class StockMicroserviceApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(StockMicroserviceApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/dto/request/OrderRequestDto.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.dto.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import java.math.BigDecimal; 9 | 10 | @Data 11 | @Builder 12 | @AllArgsConstructor 13 | @NoArgsConstructor 14 | public class OrderRequestDto { 15 | 16 | private Long productId; 17 | private BigDecimal totalAmount; 18 | private Long userId; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/repository/ProductInboxRepository.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.repository; 2 | 3 | import com.ms.stock.entity.ProductInbox; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import java.util.Optional; 8 | 9 | @Repository 10 | public interface ProductInboxRepository extends JpaRepository { 11 | 12 | Optional findByIdempotentKey(String idempotentKey); 13 | } 14 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/dto/event/StockCreateEvent.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.dto.event; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import java.math.BigDecimal; 9 | 10 | @Data 11 | @Builder 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | public class StockCreateEvent { 15 | 16 | private Long orderId; 17 | private BigDecimal totalAmount; 18 | private String idempotentKey; 19 | private Long productId; 20 | 21 | } -------------------------------------------------------------------------------- /order-microservice/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /stock-microservice/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/dto/response/OrderDebeziumResponse.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.dto.response; 2 | 3 | import com.ms.stock.dto.enums.ProductOutboxStatus; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Builder 10 | @Data 11 | @AllArgsConstructor 12 | @NoArgsConstructor 13 | public class OrderDebeziumResponse { 14 | 15 | private Long id; 16 | private String aggregate_type; 17 | private Long created_date; 18 | private String event_type; 19 | private String idempotent_key; 20 | private String payload; 21 | private ProductOutboxStatus status; 22 | private Long order_id; 23 | } 24 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/dto/response/OrderDebeziumResponse.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.dto.response; 2 | 3 | import com.ms.order.dto.enums.ProductOutboxStatus; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Builder 10 | @Data 11 | @AllArgsConstructor 12 | @NoArgsConstructor 13 | public class OrderDebeziumResponse { 14 | 15 | private Long id; 16 | private String aggregate_type; 17 | private Long created_date; 18 | private String event_type; 19 | private String idempotent_key; 20 | private String payload; 21 | private ProductOutboxStatus status; 22 | private Long order_id; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/util/Operation.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.util; 2 | 3 | public enum Operation { 4 | 5 | READ("r"), 6 | CREATE("c"), 7 | UPDATE("u"), 8 | DELETE("d"); 9 | 10 | private final String code; 11 | 12 | private Operation(String code) { 13 | this.code = code; 14 | } 15 | 16 | public String code() { 17 | return this.code; 18 | } 19 | 20 | public static Operation forCode(String code) { 21 | Operation[] var1 = values(); 22 | int var2 = var1.length; 23 | 24 | for(int var3 = 0; var3 < var2; ++var3) { 25 | Operation op = var1[var3]; 26 | if (op.code().equalsIgnoreCase(code)) { 27 | return op; 28 | } 29 | } 30 | return null; 31 | } 32 | } -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/util/Operation.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.util; 2 | 3 | public enum Operation { 4 | 5 | READ("r"), 6 | CREATE("c"), 7 | UPDATE("u"), 8 | DELETE("d"); 9 | 10 | private final String code; 11 | 12 | private Operation(String code) { 13 | this.code = code; 14 | } 15 | 16 | public String code() { 17 | return this.code; 18 | } 19 | 20 | public static Operation forCode(String code) { 21 | Operation[] var1 = values(); 22 | int var2 = var1.length; 23 | 24 | for(int var3 = 0; var3 < var2; ++var3) { 25 | Operation op = var1[var3]; 26 | if (op.code().equalsIgnoreCase(code)) { 27 | return op; 28 | } 29 | } 30 | return null; 31 | } 32 | } -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/repository/ProductOutboxRepository.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.repository; 2 | 3 | import com.ms.stock.entity.ProductOutbox; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Modifying; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.data.repository.query.Param; 8 | import org.springframework.stereotype.Repository; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | @Repository 12 | public interface ProductOutboxRepository extends JpaRepository { 13 | 14 | @Modifying 15 | @Transactional 16 | @Query(value = "DELETE FROM product_outbox where id =:id", nativeQuery = true) 17 | void deleteProductOutbox(@Param("id") Long id); 18 | } 19 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Saga Distributed Transaction Pattern - Spring boot + embedded debezium + kafka + inbox-outbox pattern 2 | 3 | Medium article link -> [Medium Link](https://medium.com/@htyesilyurt/saga-distributed-transaction-pattern-spring-boot-embedded-debezium-apache-kafka-8d111de0b444). 4 | 5 | Technologies 6 | ------------ 7 | - `Spring Boot` 8 | - `Changes Data Capture (CDC) with embedded debezium` 9 | - `Inbox-Outbox Pattern ( Inbox For Exactly once semantic - Outbox for CDC)` 10 | - `Apache Kafka ( Data streaming )` 11 | - `PostgreSQL` 12 | 13 | ## Run the System 14 | 15 | We can easily run the whole with only a single command: 16 | 17 | * `docker-compose up -d` 18 | 19 | #### 5: Starting order-microservice` 20 | 21 | ```shell 22 | ./order-microservice 23 | mvn spring-boot:run 24 | ``` 25 | 26 | #### 5: Starting stopk-microservice` 27 | 28 | ```shell 29 | ./stock-microservice 30 | mvn spring-boot:run 31 | ``` 32 | 33 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/repository/OrderOutboxRepository.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.repository; 2 | 3 | import com.ms.order.entity.OrderOutbox; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Modifying; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.data.repository.query.Param; 8 | import org.springframework.stereotype.Repository; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | import java.util.Optional; 12 | 13 | @Repository 14 | public interface OrderOutboxRepository extends JpaRepository { 15 | 16 | @Modifying 17 | @Transactional 18 | @Query(value = "DELETE FROM order_outbox where id =:id", nativeQuery = true) 19 | void deleteOrderOutbox(@Param("id") Long id); 20 | 21 | Optional findByOrderId(Long orderId); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/repository/OrderInboxRepository.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.repository; 2 | 3 | import com.ms.order.entity.OrderInbox; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Modifying; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.data.repository.query.Param; 8 | import org.springframework.stereotype.Repository; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | import java.util.Optional; 12 | 13 | @Repository 14 | public interface OrderInboxRepository extends JpaRepository { 15 | 16 | @Modifying 17 | @Transactional 18 | @Query(value = "DELETE FROM order_inbox where id =:id", nativeQuery = true) 19 | void deleteOrderInbox(@Param("id") Long id); 20 | 21 | Optional findByIdempotentKey(String idempotentKey); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/repository/ProductsRepository.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.repository; 2 | 3 | import com.ms.stock.entity.Products; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Modifying; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.data.repository.query.Param; 8 | import org.springframework.stereotype.Repository; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | import java.util.Optional; 12 | 13 | @Repository 14 | public interface ProductsRepository extends JpaRepository { 15 | 16 | Optional findByProductId(Long productId); 17 | 18 | 19 | @Modifying 20 | @Transactional 21 | @Query(value = "update products set version = version + 1,stock_size = stock_size - 1 " + 22 | "where id =:id and version =:version",nativeQuery = true) 23 | Integer updateProductStock(@Param("id") Long id,@Param("version") Integer version); 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/controller/OrderController.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.controller; 2 | 3 | import com.ms.order.dto.request.OrderRequestDto; 4 | import com.ms.order.service.OrderService; 5 | import lombok.RequiredArgsConstructor; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.web.bind.annotation.PostMapping; 9 | import org.springframework.web.bind.annotation.RequestBody; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | @RestController 14 | @RequestMapping("/v1/order") 15 | @RequiredArgsConstructor 16 | public class OrderController { 17 | 18 | private final OrderService orderService; 19 | 20 | @PostMapping 21 | public ResponseEntity createOrder(@RequestBody OrderRequestDto orderRequestDto){ 22 | return new ResponseEntity<>( 23 | orderService.createOrder(orderRequestDto), HttpStatus.CREATED 24 | ); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/runner/ProductRunner.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.runner; 2 | 3 | import com.ms.stock.entity.Products; 4 | import com.ms.stock.repository.ProductsRepository; 5 | import lombok.RequiredArgsConstructor; 6 | import org.springframework.boot.CommandLineRunner; 7 | import org.springframework.stereotype.Component; 8 | 9 | import java.math.BigDecimal; 10 | import java.time.LocalDateTime; 11 | 12 | @Component 13 | @RequiredArgsConstructor 14 | public class ProductRunner implements CommandLineRunner { 15 | 16 | private final ProductsRepository productStockRepository; 17 | 18 | @Override 19 | public void run(String... args){ 20 | 21 | productStockRepository.deleteAll(); 22 | 23 | Products product = Products.builder() 24 | .productId(10l) 25 | .createdDate(LocalDateTime.now()) 26 | .version(10) 27 | .stockSize(10) 28 | .totalAmount(new BigDecimal(100.20)) 29 | .build(); 30 | 31 | productStockRepository.save(product); 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /order-microservice/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.7/apache-maven-3.8.7-bin.zip 18 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar 19 | -------------------------------------------------------------------------------- /stock-microservice/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.7/apache-maven-3.8.7-bin.zip 18 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar 19 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/entity/ProductInbox.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.entity; 2 | 3 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 4 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 5 | import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; 6 | import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; 7 | import jakarta.persistence.*; 8 | import lombok.AllArgsConstructor; 9 | import lombok.Builder; 10 | import lombok.Data; 11 | import lombok.NoArgsConstructor; 12 | 13 | import java.time.LocalDateTime; 14 | 15 | @Entity 16 | @Table(name = "product_inbox") 17 | @Builder 18 | @AllArgsConstructor 19 | @NoArgsConstructor 20 | @Data 21 | public class ProductInbox { 22 | 23 | @Id 24 | @GeneratedValue(strategy = GenerationType.IDENTITY) 25 | private long id; 26 | 27 | @JsonSerialize(using = LocalDateTimeSerializer.class) 28 | @JsonDeserialize(using = LocalDateTimeDeserializer.class) 29 | private LocalDateTime createdDate; 30 | 31 | @Column(length = 2000) 32 | private String payload; 33 | 34 | @Column(unique = true) 35 | private String idempotentKey; 36 | } 37 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/entity/OrderInbox.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.entity; 2 | 3 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 4 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 5 | import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; 6 | import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; 7 | import com.ms.order.dto.enums.OrderInboxStatus; 8 | import jakarta.persistence.*; 9 | import lombok.AllArgsConstructor; 10 | import lombok.Builder; 11 | import lombok.Data; 12 | import lombok.NoArgsConstructor; 13 | 14 | import java.time.LocalDateTime; 15 | 16 | @Entity 17 | @Table(name = "order_inbox") 18 | @Builder 19 | @AllArgsConstructor 20 | @NoArgsConstructor 21 | @Data 22 | public class OrderInbox { 23 | 24 | @Id 25 | @GeneratedValue(strategy = GenerationType.IDENTITY) 26 | private long id; 27 | 28 | @JsonSerialize(using = LocalDateTimeSerializer.class) 29 | @JsonDeserialize(using = LocalDateTimeDeserializer.class) 30 | private LocalDateTime createdDate; 31 | 32 | @Column(length = 2000) 33 | private String payload; 34 | 35 | @Column(unique = true) 36 | private String idempotentKey; 37 | } 38 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/entity/Products.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.entity; 2 | 3 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 4 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 5 | import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; 6 | import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; 7 | import jakarta.persistence.*; 8 | import lombok.AllArgsConstructor; 9 | import lombok.Builder; 10 | import lombok.Data; 11 | import lombok.NoArgsConstructor; 12 | 13 | import java.math.BigDecimal; 14 | import java.time.LocalDateTime; 15 | 16 | @Entity 17 | @Table(name = "products") 18 | @Builder 19 | @AllArgsConstructor 20 | @NoArgsConstructor 21 | @Data 22 | public class Products { 23 | 24 | @Id 25 | @GeneratedValue(strategy = GenerationType.IDENTITY) 26 | private long id; 27 | 28 | @JsonSerialize(using = LocalDateTimeSerializer.class) 29 | @JsonDeserialize(using = LocalDateTimeDeserializer.class) 30 | private LocalDateTime createdDate; 31 | 32 | @Column(unique = true) 33 | private Long productId; 34 | 35 | private BigDecimal totalAmount; 36 | private Integer stockSize; 37 | private Integer version; 38 | 39 | } 40 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/entity/Order.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.entity; 2 | 3 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 4 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 5 | import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; 6 | import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; 7 | import com.ms.order.dto.enums.OrderStatus; 8 | import jakarta.persistence.*; 9 | import lombok.AllArgsConstructor; 10 | import lombok.Builder; 11 | import lombok.Data; 12 | import lombok.NoArgsConstructor; 13 | 14 | import java.math.BigDecimal; 15 | import java.time.LocalDateTime; 16 | 17 | @Data 18 | @Entity 19 | @Table(name = "orders") 20 | @Builder 21 | @AllArgsConstructor 22 | @NoArgsConstructor 23 | public class Order { 24 | 25 | @Id 26 | @GeneratedValue(strategy = GenerationType.IDENTITY) 27 | private long id; 28 | 29 | @JsonSerialize(using = LocalDateTimeSerializer.class) 30 | @JsonDeserialize(using = LocalDateTimeDeserializer.class) 31 | private LocalDateTime createdDate; 32 | 33 | private Long productId; 34 | private BigDecimal totalAmount; 35 | private Long userId; 36 | private OrderStatus orderStatus; 37 | private String description; 38 | 39 | } 40 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/service/OutboxService.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.service; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.ms.order.dto.response.OrderDebeziumResponse; 5 | import com.ms.order.entity.OrderOutbox; 6 | import com.ms.order.repository.OrderOutboxRepository; 7 | import com.ms.order.util.Operation; 8 | import lombok.RequiredArgsConstructor; 9 | import lombok.SneakyThrows; 10 | import lombok.extern.slf4j.Slf4j; 11 | import org.springframework.kafka.core.KafkaTemplate; 12 | import org.springframework.stereotype.Service; 13 | 14 | import java.util.Map; 15 | 16 | @Service 17 | @RequiredArgsConstructor 18 | @Slf4j 19 | public class OutboxService { 20 | 21 | private final OrderOutboxRepository orderOutboxRepository; 22 | private final KafkaTemplate kafkaTemplate; 23 | private final ObjectMapper mapper = new ObjectMapper(); 24 | 25 | public void save(OrderOutbox orderOutbox){ 26 | orderOutboxRepository.save(orderOutbox); 27 | } 28 | 29 | @SneakyThrows 30 | public void maintainReadModel(Map productData, Operation operation) { 31 | final OrderDebeziumResponse response = mapper.convertValue(productData, OrderDebeziumResponse.class); 32 | kafkaTemplate.send("order-created",response.getIdempotent_key(),mapper.writeValueAsString(response)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/entity/OrderOutbox.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.entity; 2 | 3 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 4 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 5 | import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; 6 | import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; 7 | import com.ms.order.dto.enums.OrderOutboxStatus; 8 | import jakarta.persistence.*; 9 | import lombok.AllArgsConstructor; 10 | import lombok.Builder; 11 | import lombok.Data; 12 | import lombok.NoArgsConstructor; 13 | 14 | import java.time.LocalDateTime; 15 | 16 | @Data 17 | @Entity 18 | @Table(name = "order_outbox") 19 | @AllArgsConstructor 20 | @NoArgsConstructor 21 | @Builder 22 | public class OrderOutbox { 23 | 24 | @Id 25 | @GeneratedValue(strategy = GenerationType.IDENTITY) 26 | private long id; 27 | 28 | @JsonSerialize(using = LocalDateTimeSerializer.class) 29 | @JsonDeserialize(using = LocalDateTimeDeserializer.class) 30 | private LocalDateTime createdDate; 31 | 32 | private String aggregateType; 33 | 34 | private String eventType; 35 | 36 | @Column(length = 2000) 37 | private String payload; 38 | 39 | @Column(unique = true) 40 | private String idempotentKey; 41 | 42 | private OrderOutboxStatus status; 43 | 44 | private Long orderId; 45 | 46 | } 47 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/entity/ProductOutbox.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.entity; 2 | 3 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 4 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 5 | import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; 6 | import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; 7 | import com.ms.stock.dto.enums.ProductOutboxStatus; 8 | import com.ms.stock.dto.enums.ProductOutboxStatus; 9 | import jakarta.persistence.*; 10 | import lombok.AllArgsConstructor; 11 | import lombok.Builder; 12 | import lombok.Data; 13 | import lombok.NoArgsConstructor; 14 | 15 | import java.time.LocalDateTime; 16 | 17 | @Data 18 | @Entity 19 | @Table(name = "product_outbox") 20 | @AllArgsConstructor 21 | @NoArgsConstructor 22 | @Builder 23 | public class ProductOutbox { 24 | 25 | @Id 26 | @GeneratedValue(strategy = GenerationType.IDENTITY) 27 | private long id; 28 | 29 | @JsonSerialize(using = LocalDateTimeSerializer.class) 30 | @JsonDeserialize(using = LocalDateTimeDeserializer.class) 31 | private LocalDateTime createdDate; 32 | 33 | private String aggregateType; 34 | 35 | private String eventType; 36 | 37 | private String payload; 38 | 39 | @Column(unique = true) 40 | private String idempotentKey; 41 | 42 | private ProductOutboxStatus status; 43 | 44 | private Long orderId; 45 | 46 | } 47 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/configuration/DebeziumConnectorConfig.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.configuration; 2 | 3 | import org.apache.commons.lang3.RandomStringUtils; 4 | import org.springframework.context.annotation.Bean; 5 | 6 | @org.springframework.context.annotation.Configuration 7 | public class DebeziumConnectorConfig { 8 | @Bean 9 | public io.debezium.config.Configuration sagaConnector() { 10 | return io.debezium.config.Configuration.create() 11 | .with("connector.class", "io.debezium.connector.postgresql.PostgresConnector") 12 | .with("offset.storage", "org.apache.kafka.connect.storage.FileOffsetBackingStore") 13 | .with("offset.storage.file.filename", "/Users/tugayesilyurt/Desktop/Projects/saga-offset.dat") 14 | .with("offset.flush.interval.ms", 60000) 15 | .with("name", "saga-postgres-connector-product") 16 | .with("database.server.name", "saga-outbox-server-product") 17 | .with("database.hostname", "localhost") 18 | .with("database.port", "5432") 19 | .with("database.user", "saga") 20 | .with("database.password", "saga") 21 | .with("database.dbname", "saga") 22 | .with("topic.prefix","test-product") 23 | .with("decimal.handling.mode","string") 24 | .with("wal_level","logical") 25 | .with("plugin.name","pgoutput") 26 | .with("table.include.list","public.product_outbox") 27 | .with("slot.name", RandomStringUtils.randomAlphabetic(5).toLowerCase()).build(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/configuration/DebeziumConnectorConfig.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.configuration; 2 | 3 | import org.apache.commons.lang3.RandomStringUtils; 4 | import org.springframework.context.annotation.Bean; 5 | 6 | import java.util.Arrays; 7 | 8 | @org.springframework.context.annotation.Configuration 9 | public class DebeziumConnectorConfig { 10 | @Bean 11 | public io.debezium.config.Configuration sagaConnector() { 12 | return io.debezium.config.Configuration.create() 13 | .with("connector.class", "io.debezium.connector.postgresql.PostgresConnector") 14 | .with("offset.storage", "org.apache.kafka.connect.storage.FileOffsetBackingStore") 15 | .with("offset.storage.file.filename", "/Users/tugayesilyurt/Desktop/Projects/saga-offset.dat") 16 | .with("offset.flush.interval.ms", 60000) 17 | .with("name", "saga-postgres-connector") 18 | .with("database.server.name", "saga-outbox-server") 19 | .with("database.hostname", "localhost") 20 | .with("database.port", "5432") 21 | .with("database.user", "saga") 22 | .with("database.password", "saga") 23 | .with("database.dbname", "saga") 24 | .with("topic.prefix","test-order") 25 | .with("decimal.handling.mode","string") 26 | .with("wal_level","logical") 27 | .with("plugin.name","pgoutput") 28 | .with("table.include.list","public.order_outbox") 29 | .with("slot.name", RandomStringUtils.randomAlphabetic(5).toLowerCase()).build(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/consumer/OrderCreatedConsumer.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.consumer; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.ms.stock.dto.response.OrderDebeziumResponse; 6 | import com.ms.stock.entity.ProductInbox; 7 | import com.ms.stock.repository.ProductInboxRepository; 8 | import com.ms.stock.service.StockService; 9 | import lombok.NonNull; 10 | import lombok.RequiredArgsConstructor; 11 | import lombok.extern.slf4j.Slf4j; 12 | import org.springframework.kafka.annotation.KafkaListener; 13 | import org.springframework.kafka.support.Acknowledgment; 14 | import org.springframework.kafka.support.KafkaHeaders; 15 | import org.springframework.messaging.handler.annotation.Header; 16 | import org.springframework.messaging.handler.annotation.Payload; 17 | import org.springframework.stereotype.Service; 18 | 19 | import java.time.LocalDateTime; 20 | 21 | @Service 22 | @Slf4j 23 | @RequiredArgsConstructor 24 | public class OrderCreatedConsumer { 25 | 26 | private final ObjectMapper objectMapper = new ObjectMapper(); 27 | private final ProductInboxRepository stockInboxRepository; 28 | private final StockService stockService; 29 | 30 | @KafkaListener(topics = "order-created", groupId = "orderCreatedConsumer") 31 | public void handleOrderCreate(@Payload String message, 32 | @Header(KafkaHeaders.RECEIVED_KEY) @NonNull String idempotentKey, 33 | Acknowledgment acknowledgment) throws JsonProcessingException { 34 | 35 | log.info("message " + message); 36 | log.info("key " + idempotentKey); 37 | 38 | if (stockInboxRepository.findByIdempotentKey(idempotentKey).isPresent()){ 39 | log.error("Stock inbox not created, {} already exist!", idempotentKey); 40 | acknowledgment.acknowledge(); 41 | return; 42 | } 43 | 44 | final OrderDebeziumResponse response = objectMapper.readValue(message,OrderDebeziumResponse.class); 45 | 46 | stockInboxRepository.save(createStockInbox(message,idempotentKey)); 47 | 48 | stockService.stockEventCreate(response); 49 | 50 | acknowledgment.acknowledge(); 51 | } 52 | 53 | private ProductInbox createStockInbox(String event, String idempotentKey){ 54 | return ProductInbox.builder() 55 | .payload(event) 56 | .createdDate(LocalDateTime.now()) 57 | .idempotentKey(idempotentKey) 58 | .build(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/listener/DebeziumSourceEventListener.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.listener; 2 | 3 | import java.util.Map; 4 | import java.util.concurrent.Executor; 5 | import java.util.concurrent.Executors; 6 | 7 | import com.ms.order.service.OutboxService; 8 | import com.ms.order.util.Operation; 9 | import io.debezium.embedded.EmbeddedEngine; 10 | import jakarta.annotation.PostConstruct; 11 | import jakarta.annotation.PreDestroy; 12 | import org.apache.commons.lang3.tuple.Pair; 13 | import org.apache.kafka.connect.data.Field; 14 | import org.apache.kafka.connect.data.Struct; 15 | import org.apache.kafka.connect.source.SourceRecord; 16 | import org.springframework.stereotype.Component; 17 | 18 | import io.debezium.config.Configuration; 19 | import lombok.extern.slf4j.Slf4j; 20 | 21 | import static io.debezium.data.Envelope.FieldName.*; 22 | import static java.util.stream.Collectors.toMap; 23 | 24 | @Slf4j 25 | @Component 26 | public class DebeziumSourceEventListener { 27 | 28 | private final Executor executor = Executors.newSingleThreadExecutor(); 29 | 30 | private final EmbeddedEngine engine; 31 | private final OutboxService outboxService; 32 | 33 | private DebeziumSourceEventListener(Configuration sagaConnector, OutboxService outboxService) { 34 | this.engine = EmbeddedEngine 35 | .create() 36 | .using(sagaConnector) 37 | .notifying(this::handleEvent).build(); 38 | 39 | this.outboxService = outboxService; 40 | } 41 | 42 | @PostConstruct 43 | private void start() { 44 | this.executor.execute(engine); 45 | } 46 | 47 | @PreDestroy 48 | private void stop() { 49 | if (this.engine != null) { 50 | this.engine.stop(); 51 | } 52 | } 53 | 54 | private void handleEvent(SourceRecord sourceRecord) { 55 | Struct sourceRecordValue = (Struct) sourceRecord.value(); 56 | 57 | if(sourceRecordValue != null) { 58 | Operation operation = Operation.forCode((String) sourceRecordValue.get(OPERATION)); 59 | 60 | if(operation == Operation.CREATE) { 61 | 62 | Struct struct = (Struct) sourceRecordValue.get(AFTER); 63 | Map payload = struct.schema().fields().stream() 64 | .map(Field::name) 65 | .filter(fieldName -> struct.get(fieldName) != null) 66 | .map(fieldName -> Pair.of(fieldName, struct.get(fieldName))) 67 | .collect(toMap(Pair::getKey, Pair::getValue)); 68 | 69 | log.info("Data Changed: {} with Operation: {}", payload, operation.name()); 70 | outboxService.maintainReadModel(payload,operation); 71 | } 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | 3 | services: 4 | postgres: 5 | image: postgres:13 6 | container_name: postgres 7 | environment: 8 | - POSTGRES_USER=saga 9 | - POSTGRES_PASSWORD=saga 10 | - POSTGRES_DB=saga 11 | ports: 12 | - "5432:5432" 13 | command: 14 | - "postgres" 15 | - "-c" 16 | - "wal_level=logical" 17 | pgadmin: 18 | image: dpage/pgadmin4 19 | container_name: pgadmin 20 | environment: 21 | - PGADMIN_DEFAULT_EMAIL=htyesilyurt@gmail.com 22 | - PGADMIN_DEFAULT_PASSWORD=saga 23 | ports: 24 | - "8080:80" 25 | 26 | zookeeper: 27 | image: confluentinc/cp-zookeeper:latest 28 | container_name: zookeeper 29 | environment: 30 | ZOOKEEPER_CLIENT_PORT: 2181 31 | ZOOKEEPER_TICK_TIME: 2000 32 | ZK_SERVER_HEAP: "-Xmx256M -Xms256M" 33 | ports: 34 | - 22181:2181 35 | kafka: 36 | image: confluentinc/cp-kafka:latest 37 | container_name: kafka-broker 38 | depends_on: 39 | - zookeeper 40 | ports: 41 | - 29092:29092 42 | environment: 43 | KAFKA_BROKER_ID: 1 44 | KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 45 | KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092 46 | KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT 47 | KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT 48 | KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 49 | KAFKA_HEAP_OPTS: "-Xmx256M -Xms256M" 50 | init-kafka: 51 | image: confluentinc/cp-kafka:6.1.1 52 | depends_on: 53 | - kafka 54 | entrypoint: [ '/bin/sh', '-c' ] 55 | command: | 56 | " 57 | # blocks until kafka is reachable 58 | kafka-topics --bootstrap-server kafka:9092 --list 59 | 60 | echo -e 'Creating kafka topics' 61 | kafka-topics --bootstrap-server kafka:9092 --create --if-not-exists --topic product-update-fail --replication-factor 1 --partitions 1 62 | kafka-topics --bootstrap-server kafka:9092 --create --if-not-exists --topic order-created --replication-factor 1 --partitions 1 63 | kafka-topics --bootstrap-server kafka:9092 --create --if-not-exists --topic product-update-successfully --replication-factor 1 --partitions 1 64 | 65 | echo -e 'Successfully created the following topics:' 66 | kafka-topics --bootstrap-server kafka:9092 --list 67 | " 68 | kafka-ui: 69 | container_name: kafka-ui 70 | image: provectuslabs/kafka-ui:latest 71 | ports: 72 | - 9000:8080 73 | depends_on: 74 | - zookeeper 75 | - kafka 76 | environment: 77 | KAFKA_CLUSTERS_0_NAME: loan-kafka-ui 78 | KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka:9092 79 | KAFKA_CLUSTERS_0_ZOOKEEPER: zookeeper:2181 80 | 81 | 82 | networks: 83 | saga-network: 84 | driver: bridge -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/listener/DebeziumSourceEventListener.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.listener; 2 | 3 | import com.ms.stock.service.StockService; 4 | import com.ms.stock.util.Operation; 5 | import io.debezium.config.Configuration; 6 | import io.debezium.embedded.EmbeddedEngine; 7 | import jakarta.annotation.PostConstruct; 8 | import jakarta.annotation.PreDestroy; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.apache.commons.lang3.tuple.Pair; 11 | import org.apache.kafka.connect.data.Field; 12 | import org.apache.kafka.connect.data.Struct; 13 | import org.apache.kafka.connect.source.SourceRecord; 14 | import org.springframework.stereotype.Component; 15 | 16 | import java.util.Map; 17 | import java.util.concurrent.Executor; 18 | import java.util.concurrent.Executors; 19 | 20 | import static io.debezium.data.Envelope.FieldName.AFTER; 21 | import static io.debezium.data.Envelope.FieldName.OPERATION; 22 | import static java.util.stream.Collectors.toMap; 23 | 24 | @Slf4j 25 | @Component 26 | public class DebeziumSourceEventListener { 27 | 28 | private final Executor executor = Executors.newSingleThreadExecutor(); 29 | 30 | private final EmbeddedEngine engine; 31 | private final StockService stockService; 32 | 33 | private DebeziumSourceEventListener(Configuration sagaConnector, StockService stockService) { 34 | this.engine = EmbeddedEngine 35 | .create() 36 | .using(sagaConnector) 37 | .notifying(this::handleEvent).build(); 38 | 39 | this.stockService = stockService; 40 | } 41 | 42 | @PostConstruct 43 | private void start() { 44 | this.executor.execute(engine); 45 | } 46 | 47 | @PreDestroy 48 | private void stop() { 49 | if (this.engine != null) { 50 | this.engine.stop(); 51 | } 52 | } 53 | 54 | private void handleEvent(SourceRecord sourceRecord) { 55 | Struct sourceRecordValue = (Struct) sourceRecord.value(); 56 | 57 | if(sourceRecordValue != null) { 58 | Operation operation = Operation.forCode((String) sourceRecordValue.get(OPERATION)); 59 | 60 | if(operation == Operation.CREATE) { 61 | 62 | Struct struct = (Struct) sourceRecordValue.get(AFTER); 63 | Map payload = struct.schema().fields().stream() 64 | .map(Field::name) 65 | .filter(fieldName -> struct.get(fieldName) != null) 66 | .map(fieldName -> Pair.of(fieldName, struct.get(fieldName))) 67 | .collect(toMap(Pair::getKey, Pair::getValue)); 68 | 69 | log.info("Data Changed: {} with Operation: {}", payload, operation.name()); 70 | stockService.maintainReadModel(payload,operation); 71 | } 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/service/OrderService.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.service; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.ms.order.dto.enums.OrderOutboxStatus; 6 | import com.ms.order.dto.enums.OrderStatus; 7 | import com.ms.order.dto.event.StockCreateEvent; 8 | import com.ms.order.dto.request.OrderRequestDto; 9 | import com.ms.order.entity.Order; 10 | import com.ms.order.entity.OrderOutbox; 11 | import com.ms.order.repository.OrderRepository; 12 | import lombok.RequiredArgsConstructor; 13 | import lombok.extern.slf4j.Slf4j; 14 | import org.apache.commons.lang3.RandomStringUtils; 15 | import org.springframework.stereotype.Service; 16 | 17 | import java.time.LocalDateTime; 18 | 19 | @Service 20 | @RequiredArgsConstructor 21 | @Slf4j 22 | public class OrderService { 23 | 24 | private final OrderRepository orderRepository; 25 | private final OutboxService outboxService; 26 | private final ObjectMapper objectMapper = new ObjectMapper(); 27 | 28 | public Boolean createOrder(OrderRequestDto orderRequestDto){ 29 | Order order = orderRepository.save(convertToOrder(orderRequestDto)); 30 | outboxService.save(toOutboxEntity(order)); 31 | return true; 32 | } 33 | 34 | private OrderOutbox toOutboxEntity(Order order){ 35 | String payload = null; 36 | String idempotentKey = RandomStringUtils.randomAlphanumeric(10); 37 | try{ 38 | StockCreateEvent stockCreateEvent = StockCreateEvent.builder() 39 | .orderId(order.getId()) 40 | .productId(order.getProductId()) 41 | .idempotentKey(idempotentKey) 42 | .totalAmount(order.getTotalAmount()) 43 | .build(); 44 | 45 | payload = objectMapper.writeValueAsString(stockCreateEvent); 46 | 47 | }catch (JsonProcessingException ex){ 48 | log.error("Object could not convert to String. Object: {}", order.toString()); 49 | throw new RuntimeException(ex); 50 | } 51 | 52 | return OrderOutbox.builder() 53 | .status(OrderOutboxStatus.CREATED) 54 | .createdDate(LocalDateTime.now()) 55 | .idempotentKey(idempotentKey) 56 | .payload(payload) 57 | .aggregateType("Order") 58 | .eventType("OrderCreated") 59 | .orderId(order.getId()) 60 | .build(); 61 | } 62 | 63 | private Order convertToOrder(OrderRequestDto orderRequestDto){ 64 | return Order.builder() 65 | .createdDate(LocalDateTime.now()) 66 | .totalAmount(orderRequestDto.getTotalAmount()) 67 | .productId(orderRequestDto.getProductId()) 68 | .userId(orderRequestDto.getUserId()) 69 | .orderStatus(OrderStatus.CREATED) 70 | .description("Order Created") 71 | .build(); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/configuration/KafkaConfig.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.configuration; 2 | 3 | import org.apache.kafka.clients.consumer.ConsumerConfig; 4 | import org.apache.kafka.clients.producer.ProducerConfig; 5 | import org.apache.kafka.common.serialization.StringDeserializer; 6 | import org.apache.kafka.common.serialization.StringSerializer; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.kafka.annotation.EnableKafka; 11 | import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; 12 | import org.springframework.kafka.core.*; 13 | import org.springframework.kafka.listener.ContainerProperties; 14 | import org.springframework.kafka.support.serializer.JsonDeserializer; 15 | import org.springframework.kafka.support.serializer.JsonSerializer; 16 | 17 | import java.util.HashMap; 18 | import java.util.Map; 19 | 20 | @Configuration 21 | @EnableKafka 22 | public class KafkaConfig { 23 | 24 | @Value(value = "${kafka.bootstrapAddress}") 25 | private String bootstrapAddress; 26 | 27 | @Bean 28 | public KafkaTemplate kafkaTemplate() { 29 | return new KafkaTemplate<>(producerFactory()); 30 | } 31 | @Bean 32 | public ConsumerFactory consumerFactory() { 33 | Map configProps = new HashMap<>(); 34 | configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); 35 | configProps.put(ConsumerConfig.GROUP_ID_CONFIG, "orderCreatedConsumer"); 36 | configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); 37 | configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); 38 | configProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); 39 | configProps.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000"); 40 | return new DefaultKafkaConsumerFactory<>(configProps); 41 | } 42 | @Bean 43 | public ConcurrentKafkaListenerContainerFactory 44 | kafkaListenerContainerFactory() { 45 | 46 | ConcurrentKafkaListenerContainerFactory factory = 47 | new ConcurrentKafkaListenerContainerFactory<>(); 48 | factory.setConsumerFactory(consumerFactory()); 49 | factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE); 50 | return factory; 51 | } 52 | 53 | @Bean 54 | public ProducerFactory producerFactory() { 55 | Map configProps = new HashMap<>(); 56 | configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); 57 | configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); 58 | configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); 59 | return new DefaultKafkaProducerFactory<>(configProps); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /order-microservice/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 3.0.6 9 | 10 | 11 | com.ms.order 12 | order-microservice 13 | 0.0.1-SNAPSHOT 14 | order-microservice 15 | Order Microservice 16 | 17 | 20 18 | 2.1.2.Final 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter 24 | 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-web 29 | 30 | 31 | org.springframework.kafka 32 | spring-kafka 33 | 34 | 35 | org.projectlombok 36 | lombok 37 | true 38 | 39 | 40 | org.springframework.kafka 41 | spring-kafka-test 42 | test 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-data-jpa 47 | 48 | 49 | org.postgresql 50 | postgresql 51 | runtime 52 | 53 | 54 | org.apache.commons 55 | commons-lang3 56 | 3.12.0 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-starter-test 61 | test 62 | 63 | 64 | io.debezium 65 | debezium-api 66 | ${version.debezium} 67 | 68 | 69 | io.debezium 70 | debezium-embedded 71 | ${version.debezium} 72 | 73 | 74 | io.debezium 75 | debezium-connector-postgres 76 | ${version.debezium} 77 | 78 | 79 | org.springframework.boot 80 | spring-boot-starter-validation 81 | 82 | 83 | 84 | 85 | 86 | 87 | org.springframework.boot 88 | spring-boot-maven-plugin 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /stock-microservice/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 3.0.6 9 | 10 | 11 | com.ms.stock 12 | stock-microservice 13 | 0.0.1-SNAPSHOT 14 | stock-microservice 15 | Stock Microservice 16 | 17 | 20 18 | 2.1.2.Final 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter 24 | 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-web 29 | 30 | 31 | org.springframework.kafka 32 | spring-kafka 33 | 34 | 35 | org.projectlombok 36 | lombok 37 | true 38 | 39 | 40 | org.springframework.kafka 41 | spring-kafka-test 42 | test 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-data-jpa 47 | 48 | 49 | org.postgresql 50 | postgresql 51 | runtime 52 | 53 | 54 | org.apache.commons 55 | commons-lang3 56 | 3.12.0 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-starter-test 61 | test 62 | 63 | 64 | io.debezium 65 | debezium-api 66 | ${version.debezium} 67 | 68 | 69 | io.debezium 70 | debezium-embedded 71 | ${version.debezium} 72 | 73 | 74 | io.debezium 75 | debezium-connector-postgres 76 | ${version.debezium} 77 | 78 | 79 | org.springframework.boot 80 | spring-boot-starter-validation 81 | 82 | 83 | 84 | 85 | 86 | 87 | org.springframework.boot 88 | spring-boot-maven-plugin 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/configuration/KafkaConfig.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.configuration; 2 | 3 | import org.apache.kafka.clients.consumer.ConsumerConfig; 4 | import org.apache.kafka.clients.producer.ProducerConfig; 5 | import org.apache.kafka.common.serialization.StringDeserializer; 6 | import org.apache.kafka.common.serialization.StringSerializer; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.kafka.annotation.EnableKafka; 11 | import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; 12 | import org.springframework.kafka.core.*; 13 | import org.springframework.kafka.listener.ContainerProperties; 14 | import org.springframework.kafka.support.serializer.JsonDeserializer; 15 | import org.springframework.kafka.support.serializer.JsonSerializer; 16 | 17 | import java.util.HashMap; 18 | import java.util.Map; 19 | 20 | @EnableKafka 21 | @Configuration 22 | public class KafkaConfig { 23 | 24 | @Value(value = "${kafka.bootstrapAddress}") 25 | private String bootstrapAddress; 26 | 27 | @Bean 28 | public ConsumerFactory consumerFactoryFail() { 29 | Map configProps = new HashMap<>(); 30 | configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); 31 | configProps.put(ConsumerConfig.GROUP_ID_CONFIG, "fail"); 32 | configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); 33 | configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); 34 | configProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); 35 | configProps.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000"); 36 | return new DefaultKafkaConsumerFactory<>(configProps); 37 | } 38 | @Bean 39 | public ConcurrentKafkaListenerContainerFactory 40 | orderFailFactory() { 41 | 42 | ConcurrentKafkaListenerContainerFactory factory = 43 | new ConcurrentKafkaListenerContainerFactory<>(); 44 | factory.setConsumerFactory(consumerFactoryFail()); 45 | factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE); 46 | return factory; 47 | } 48 | 49 | @Bean 50 | public ConsumerFactory consumerFactorySuccess() { 51 | Map configProps = new HashMap<>(); 52 | configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); 53 | configProps.put(ConsumerConfig.GROUP_ID_CONFIG, "success"); 54 | configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); 55 | configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); 56 | configProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); 57 | configProps.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000"); 58 | return new DefaultKafkaConsumerFactory<>(configProps); 59 | } 60 | @Bean 61 | public ConcurrentKafkaListenerContainerFactory 62 | orderSuccessFactory() { 63 | 64 | ConcurrentKafkaListenerContainerFactory factory = 65 | new ConcurrentKafkaListenerContainerFactory<>(); 66 | factory.setConsumerFactory(consumerFactorySuccess()); 67 | factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE); 68 | return factory; 69 | } 70 | @Bean 71 | public ProducerFactory productProducerFactory() { 72 | Map configProps = new HashMap<>(); 73 | configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); 74 | configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); 75 | configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); 76 | configProps.put(ProducerConfig.ACKS_CONFIG, "all"); 77 | configProps.put(ProducerConfig.RETRIES_CONFIG, Integer.MAX_VALUE); 78 | configProps.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true); 79 | return new DefaultKafkaProducerFactory<>(configProps); 80 | } 81 | 82 | @Bean 83 | public KafkaTemplate productKafkaTemplate() { 84 | return new KafkaTemplate<>(productProducerFactory()); 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /order-microservice/src/main/java/com/ms/order/consumer/OrderConsumer.java: -------------------------------------------------------------------------------- 1 | package com.ms.order.consumer; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.ms.order.dto.enums.OrderInboxStatus; 6 | import com.ms.order.dto.enums.OrderOutboxStatus; 7 | import com.ms.order.dto.enums.OrderStatus; 8 | import com.ms.order.dto.response.OrderDebeziumResponse; 9 | import com.ms.order.entity.Order; 10 | import com.ms.order.entity.OrderInbox; 11 | import com.ms.order.entity.OrderOutbox; 12 | import com.ms.order.repository.OrderInboxRepository; 13 | import com.ms.order.repository.OrderOutboxRepository; 14 | import com.ms.order.repository.OrderRepository; 15 | import lombok.NonNull; 16 | import lombok.RequiredArgsConstructor; 17 | import lombok.extern.slf4j.Slf4j; 18 | import org.springframework.kafka.annotation.KafkaListener; 19 | import org.springframework.kafka.support.Acknowledgment; 20 | import org.springframework.kafka.support.KafkaHeaders; 21 | import org.springframework.messaging.handler.annotation.Header; 22 | import org.springframework.messaging.handler.annotation.Payload; 23 | import org.springframework.stereotype.Service; 24 | 25 | import java.time.LocalDateTime; 26 | import java.util.Optional; 27 | 28 | @Service 29 | @Slf4j 30 | @RequiredArgsConstructor 31 | public class OrderConsumer { 32 | 33 | private final ObjectMapper objectMapper = new ObjectMapper(); 34 | private final OrderRepository orderRepository; 35 | private final OrderOutboxRepository orderOutboxRepository; 36 | private final OrderInboxRepository orderInboxRepository; 37 | 38 | @KafkaListener(topics = "product-update-fail", groupId = "fail",containerFactory = "orderFailFactory") 39 | public void handleFailOrder(@Payload String message, 40 | @Header(KafkaHeaders.RECEIVED_KEY) @NonNull String idempotentKey, 41 | Acknowledgment acknowledgment) throws JsonProcessingException { 42 | 43 | log.info("message " + message); 44 | log.info("key " + idempotentKey); 45 | 46 | if (orderInboxRepository.findByIdempotentKey(idempotentKey).isPresent()){ 47 | log.error("Stock inbox not created, {} already exist!", idempotentKey); 48 | acknowledgment.acknowledge(); 49 | return; 50 | } 51 | 52 | final OrderDebeziumResponse response = objectMapper.readValue(message,OrderDebeziumResponse.class); 53 | 54 | Optional order = orderRepository.findById(response.getOrder_id()); 55 | 56 | if(order.isPresent()){ 57 | order.get().setOrderStatus(OrderStatus.FAILED); 58 | order.get().setDescription(response.getEvent_type()); 59 | orderRepository.save(order.get()); 60 | 61 | Optional orderOutbox = orderOutboxRepository.findByOrderId(order.get().getId()); 62 | if(orderOutbox.isPresent()){ 63 | orderOutbox.get().setStatus(OrderOutboxStatus.DONE); 64 | orderOutboxRepository.save(orderOutbox.get()); 65 | } 66 | 67 | } 68 | orderInboxRepository.save(OrderInbox.builder().payload(message).createdDate(LocalDateTime.now()) 69 | .idempotentKey(idempotentKey).build()); 70 | 71 | acknowledgment.acknowledge(); 72 | } 73 | 74 | @KafkaListener(topics = "product-update-successfully", groupId = "success",containerFactory = "orderSuccessFactory") 75 | public void handleSuccessOrder(@Payload String message, 76 | @Header(KafkaHeaders.RECEIVED_KEY) @NonNull String idempotentKey, 77 | Acknowledgment acknowledgment) throws JsonProcessingException { 78 | 79 | log.info("message " + message); 80 | log.info("key " + idempotentKey); 81 | 82 | if (orderInboxRepository.findByIdempotentKey(idempotentKey).isPresent()){ 83 | log.error("Stock inbox not created, {} already exist!", idempotentKey); 84 | acknowledgment.acknowledge(); 85 | return; 86 | } 87 | 88 | final OrderDebeziumResponse response = objectMapper.readValue(message,OrderDebeziumResponse.class); 89 | 90 | Optional order = orderRepository.findById(response.getOrder_id()); 91 | 92 | if(order.isPresent()){ 93 | order.get().setOrderStatus(OrderStatus.COMPLETED); 94 | order.get().setDescription(response.getEvent_type()); 95 | orderRepository.save(order.get()); 96 | 97 | Optional orderOutbox = orderOutboxRepository.findByOrderId(order.get().getId()); 98 | if(orderOutbox.isPresent()){ 99 | orderOutbox.get().setStatus(OrderOutboxStatus.DONE); 100 | orderOutboxRepository.save(orderOutbox.get()); 101 | } 102 | 103 | } 104 | orderInboxRepository.save(OrderInbox.builder().payload(message).createdDate(LocalDateTime.now()) 105 | .idempotentKey(idempotentKey).build()); 106 | 107 | acknowledgment.acknowledge(); 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /stock-microservice/src/main/java/com/ms/stock/service/StockService.java: -------------------------------------------------------------------------------- 1 | package com.ms.stock.service; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.ms.stock.dto.enums.ProductOutboxStatus; 6 | import com.ms.stock.dto.event.StockCreateEvent; 7 | import com.ms.stock.dto.response.OrderDebeziumResponse; 8 | import com.ms.stock.entity.ProductOutbox; 9 | import com.ms.stock.entity.Products; 10 | import com.ms.stock.repository.ProductOutboxRepository; 11 | import com.ms.stock.repository.ProductsRepository; 12 | import com.ms.stock.util.Operation; 13 | import lombok.RequiredArgsConstructor; 14 | import lombok.SneakyThrows; 15 | import lombok.extern.slf4j.Slf4j; 16 | import org.apache.commons.lang3.RandomStringUtils; 17 | import org.apache.commons.lang3.StringUtils; 18 | import org.springframework.kafka.core.KafkaTemplate; 19 | import org.springframework.stereotype.Service; 20 | 21 | import java.time.LocalDateTime; 22 | import java.util.Map; 23 | import java.util.Optional; 24 | 25 | @Service 26 | @Slf4j 27 | @RequiredArgsConstructor 28 | public class StockService { 29 | 30 | private final ProductsRepository productStockRepository; 31 | private final ProductOutboxRepository productOutboxRepository; 32 | private final KafkaTemplate kafkaTemplate; 33 | private final ObjectMapper mapper = new ObjectMapper(); 34 | 35 | @SneakyThrows 36 | public void maintainReadModel(Map productData, Operation operation) { 37 | final OrderDebeziumResponse response = mapper.convertValue(productData, OrderDebeziumResponse.class); 38 | String topic = StringUtils.EMPTY; 39 | if(response.getStatus() == ProductOutboxStatus.DONE) 40 | topic = "product-update-successfully"; 41 | else 42 | topic = "product-update-fail"; 43 | 44 | kafkaTemplate.send(topic,response.getIdempotent_key(),mapper.writeValueAsString(response)); 45 | } 46 | 47 | @SneakyThrows 48 | public void stockEventCreate(OrderDebeziumResponse response){ 49 | 50 | StockCreateEvent stockCreateEvent = mapper.readValue(response.getPayload(),StockCreateEvent.class); 51 | 52 | Optional productStock = productStockRepository.findByProductId(stockCreateEvent.getProductId()); 53 | 54 | if(productStock.isPresent()){ 55 | if(productStock.get().getStockSize() < 1){ 56 | productOutboxRepository.save(toOutboxEntity(productStock.get(),ProductOutboxStatus.FAILED,"orderFailed","notAvaliableStock",stockCreateEvent.getOrderId())); 57 | return; 58 | } 59 | 60 | if(stockCreateEvent.getTotalAmount().compareTo(productStock.get().getTotalAmount()) < 0){ 61 | productOutboxRepository.save(toOutboxEntity(productStock.get(),ProductOutboxStatus.FAILED,"orderFailed","amountNotEnough",stockCreateEvent.getOrderId())); 62 | return; 63 | } 64 | 65 | Integer updateVersion = productStockRepository.updateProductStock(productStock.get().getId(),productStock.get().getVersion()); 66 | if(updateVersion < 1){ 67 | productOutboxRepository.save(toOutboxEntity(productStock.get(),ProductOutboxStatus.FAILED,"orderFailed","versionChange",stockCreateEvent.getOrderId())); 68 | return; 69 | } 70 | 71 | productOutboxRepository.save(toOutboxEntity(productStock.get(),ProductOutboxStatus.DONE,"orderCompleted","successfull",stockCreateEvent.getOrderId())); 72 | 73 | }else{ 74 | productOutboxRepository.save(toOutboxEntityNoProduct(stockCreateEvent,ProductOutboxStatus.FAILED,"orderFailed","noProduct")); 75 | } 76 | } 77 | 78 | private ProductOutbox toOutboxEntity(Products productStock, ProductOutboxStatus productOutboxStatus,String aggregateType,String eventType,Long orderId){ 79 | String payload = null; 80 | String idempotentKey = RandomStringUtils.randomAlphanumeric(10); 81 | try{ 82 | 83 | payload = mapper.writeValueAsString(productStock); 84 | 85 | }catch (JsonProcessingException ex){ 86 | log.error("Object could not convert to String. Object: {}", productStock.toString()); 87 | throw new RuntimeException(ex); 88 | } 89 | 90 | return ProductOutbox.builder() 91 | .status(productOutboxStatus) 92 | .createdDate(LocalDateTime.now()) 93 | .idempotentKey(idempotentKey) 94 | .payload(payload) 95 | .aggregateType(aggregateType) 96 | .eventType(eventType) 97 | .orderId(orderId) 98 | .build(); 99 | } 100 | 101 | private ProductOutbox toOutboxEntityNoProduct(StockCreateEvent stockCreateEvent, ProductOutboxStatus productOutboxStatus,String aggregateType,String eventType){ 102 | String payload = null; 103 | String idempotentKey = RandomStringUtils.randomAlphanumeric(10); 104 | try{ 105 | 106 | payload = mapper.writeValueAsString(stockCreateEvent); 107 | 108 | }catch (JsonProcessingException ex){ 109 | log.error("Object could not convert to String. Object: {}", stockCreateEvent.toString()); 110 | throw new RuntimeException(ex); 111 | } 112 | 113 | return ProductOutbox.builder() 114 | .status(productOutboxStatus) 115 | .createdDate(LocalDateTime.now()) 116 | .idempotentKey(idempotentKey) 117 | .payload(payload) 118 | .aggregateType(aggregateType) 119 | .eventType(eventType) 120 | .orderId(stockCreateEvent.getOrderId()) 121 | .build(); 122 | } 123 | 124 | } 125 | -------------------------------------------------------------------------------- /order-microservice/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 50 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 124 | 125 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% ^ 162 | %JVM_CONFIG_MAVEN_PROPS% ^ 163 | %MAVEN_OPTS% ^ 164 | %MAVEN_DEBUG_OPTS% ^ 165 | -classpath %WRAPPER_JAR% ^ 166 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 167 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 168 | if ERRORLEVEL 1 goto error 169 | goto end 170 | 171 | :error 172 | set ERROR_CODE=1 173 | 174 | :end 175 | @endlocal & set ERROR_CODE=%ERROR_CODE% 176 | 177 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 178 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 179 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 180 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 181 | :skipRcPost 182 | 183 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 184 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 185 | 186 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 187 | 188 | cmd /C exit /B %ERROR_CODE% 189 | -------------------------------------------------------------------------------- /stock-microservice/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 50 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 124 | 125 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% ^ 162 | %JVM_CONFIG_MAVEN_PROPS% ^ 163 | %MAVEN_OPTS% ^ 164 | %MAVEN_DEBUG_OPTS% ^ 165 | -classpath %WRAPPER_JAR% ^ 166 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 167 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 168 | if ERRORLEVEL 1 goto error 169 | goto end 170 | 171 | :error 172 | set ERROR_CODE=1 173 | 174 | :end 175 | @endlocal & set ERROR_CODE=%ERROR_CODE% 176 | 177 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 178 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 179 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 180 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 181 | :skipRcPost 182 | 183 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 184 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 185 | 186 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 187 | 188 | cmd /C exit /B %ERROR_CODE% 189 | -------------------------------------------------------------------------------- /order-microservice/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /usr/local/etc/mavenrc ] ; then 40 | . /usr/local/etc/mavenrc 41 | fi 42 | 43 | if [ -f /etc/mavenrc ] ; then 44 | . /etc/mavenrc 45 | fi 46 | 47 | if [ -f "$HOME/.mavenrc" ] ; then 48 | . "$HOME/.mavenrc" 49 | fi 50 | 51 | fi 52 | 53 | # OS specific support. $var _must_ be set to either true or false. 54 | cygwin=false; 55 | darwin=false; 56 | mingw=false 57 | case "`uname`" in 58 | CYGWIN*) cygwin=true ;; 59 | MINGW*) mingw=true;; 60 | Darwin*) darwin=true 61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 63 | if [ -z "$JAVA_HOME" ]; then 64 | if [ -x "/usr/libexec/java_home" ]; then 65 | export JAVA_HOME="`/usr/libexec/java_home`" 66 | else 67 | export JAVA_HOME="/Library/Java/Home" 68 | fi 69 | fi 70 | ;; 71 | esac 72 | 73 | if [ -z "$JAVA_HOME" ] ; then 74 | if [ -r /etc/gentoo-release ] ; then 75 | JAVA_HOME=`java-config --jre-home` 76 | fi 77 | fi 78 | 79 | if [ -z "$M2_HOME" ] ; then 80 | ## resolve links - $0 may be a link to maven's home 81 | PRG="$0" 82 | 83 | # need this for relative symlinks 84 | while [ -h "$PRG" ] ; do 85 | ls=`ls -ld "$PRG"` 86 | link=`expr "$ls" : '.*-> \(.*\)$'` 87 | if expr "$link" : '/.*' > /dev/null; then 88 | PRG="$link" 89 | else 90 | PRG="`dirname "$PRG"`/$link" 91 | fi 92 | done 93 | 94 | saveddir=`pwd` 95 | 96 | M2_HOME=`dirname "$PRG"`/.. 97 | 98 | # make it fully qualified 99 | M2_HOME=`cd "$M2_HOME" && pwd` 100 | 101 | cd "$saveddir" 102 | # echo Using m2 at $M2_HOME 103 | fi 104 | 105 | # For Cygwin, ensure paths are in UNIX format before anything is touched 106 | if $cygwin ; then 107 | [ -n "$M2_HOME" ] && 108 | M2_HOME=`cygpath --unix "$M2_HOME"` 109 | [ -n "$JAVA_HOME" ] && 110 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 111 | [ -n "$CLASSPATH" ] && 112 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 113 | fi 114 | 115 | # For Mingw, ensure paths are in UNIX format before anything is touched 116 | if $mingw ; then 117 | [ -n "$M2_HOME" ] && 118 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 119 | [ -n "$JAVA_HOME" ] && 120 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 121 | fi 122 | 123 | if [ -z "$JAVA_HOME" ]; then 124 | javaExecutable="`which javac`" 125 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 126 | # readlink(1) is not available as standard on Solaris 10. 127 | readLink=`which readlink` 128 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 129 | if $darwin ; then 130 | javaHome="`dirname \"$javaExecutable\"`" 131 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 132 | else 133 | javaExecutable="`readlink -f \"$javaExecutable\"`" 134 | fi 135 | javaHome="`dirname \"$javaExecutable\"`" 136 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 137 | JAVA_HOME="$javaHome" 138 | export JAVA_HOME 139 | fi 140 | fi 141 | fi 142 | 143 | if [ -z "$JAVACMD" ] ; then 144 | if [ -n "$JAVA_HOME" ] ; then 145 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 146 | # IBM's JDK on AIX uses strange locations for the executables 147 | JAVACMD="$JAVA_HOME/jre/sh/java" 148 | else 149 | JAVACMD="$JAVA_HOME/bin/java" 150 | fi 151 | else 152 | JAVACMD="`\\unset -f command; \\command -v java`" 153 | fi 154 | fi 155 | 156 | if [ ! -x "$JAVACMD" ] ; then 157 | echo "Error: JAVA_HOME is not defined correctly." >&2 158 | echo " We cannot execute $JAVACMD" >&2 159 | exit 1 160 | fi 161 | 162 | if [ -z "$JAVA_HOME" ] ; then 163 | echo "Warning: JAVA_HOME environment variable is not set." 164 | fi 165 | 166 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 167 | 168 | # traverses directory structure from process work directory to filesystem root 169 | # first directory with .mvn subdirectory is considered project base directory 170 | find_maven_basedir() { 171 | 172 | if [ -z "$1" ] 173 | then 174 | echo "Path not specified to find_maven_basedir" 175 | return 1 176 | fi 177 | 178 | basedir="$1" 179 | wdir="$1" 180 | while [ "$wdir" != '/' ] ; do 181 | if [ -d "$wdir"/.mvn ] ; then 182 | basedir=$wdir 183 | break 184 | fi 185 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 186 | if [ -d "${wdir}" ]; then 187 | wdir=`cd "$wdir/.."; pwd` 188 | fi 189 | # end of workaround 190 | done 191 | echo "${basedir}" 192 | } 193 | 194 | # concatenates all lines of a file 195 | concat_lines() { 196 | if [ -f "$1" ]; then 197 | echo "$(tr -s '\n' ' ' < "$1")" 198 | fi 199 | } 200 | 201 | BASE_DIR=`find_maven_basedir "$(pwd)"` 202 | if [ -z "$BASE_DIR" ]; then 203 | exit 1; 204 | fi 205 | 206 | ########################################################################################## 207 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 208 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 209 | ########################################################################################## 210 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Found .mvn/wrapper/maven-wrapper.jar" 213 | fi 214 | else 215 | if [ "$MVNW_VERBOSE" = true ]; then 216 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 217 | fi 218 | if [ -n "$MVNW_REPOURL" ]; then 219 | jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 220 | else 221 | jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 222 | fi 223 | while IFS="=" read key value; do 224 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 225 | esac 226 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 227 | if [ "$MVNW_VERBOSE" = true ]; then 228 | echo "Downloading from: $jarUrl" 229 | fi 230 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 231 | if $cygwin; then 232 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 233 | fi 234 | 235 | if command -v wget > /dev/null; then 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Found wget ... using wget" 238 | fi 239 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 240 | wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 241 | else 242 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 243 | fi 244 | elif command -v curl > /dev/null; then 245 | if [ "$MVNW_VERBOSE" = true ]; then 246 | echo "Found curl ... using curl" 247 | fi 248 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 249 | curl -o "$wrapperJarPath" "$jarUrl" -f 250 | else 251 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 252 | fi 253 | 254 | else 255 | if [ "$MVNW_VERBOSE" = true ]; then 256 | echo "Falling back to using Java to download" 257 | fi 258 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 259 | # For Cygwin, switch paths to Windows format before running javac 260 | if $cygwin; then 261 | javaClass=`cygpath --path --windows "$javaClass"` 262 | fi 263 | if [ -e "$javaClass" ]; then 264 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 265 | if [ "$MVNW_VERBOSE" = true ]; then 266 | echo " - Compiling MavenWrapperDownloader.java ..." 267 | fi 268 | # Compiling the Java class 269 | ("$JAVA_HOME/bin/javac" "$javaClass") 270 | fi 271 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 272 | # Running the downloader 273 | if [ "$MVNW_VERBOSE" = true ]; then 274 | echo " - Running MavenWrapperDownloader.java ..." 275 | fi 276 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 277 | fi 278 | fi 279 | fi 280 | fi 281 | ########################################################################################## 282 | # End of extension 283 | ########################################################################################## 284 | 285 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 286 | if [ "$MVNW_VERBOSE" = true ]; then 287 | echo $MAVEN_PROJECTBASEDIR 288 | fi 289 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 290 | 291 | # For Cygwin, switch paths to Windows format before running java 292 | if $cygwin; then 293 | [ -n "$M2_HOME" ] && 294 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 295 | [ -n "$JAVA_HOME" ] && 296 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 297 | [ -n "$CLASSPATH" ] && 298 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 299 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 300 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 301 | fi 302 | 303 | # Provide a "standardized" way to retrieve the CLI args that will 304 | # work with both Windows and non-Windows executions. 305 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 306 | export MAVEN_CMD_LINE_ARGS 307 | 308 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 309 | 310 | exec "$JAVACMD" \ 311 | $MAVEN_OPTS \ 312 | $MAVEN_DEBUG_OPTS \ 313 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 314 | "-Dmaven.home=${M2_HOME}" \ 315 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 316 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 317 | -------------------------------------------------------------------------------- /stock-microservice/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /usr/local/etc/mavenrc ] ; then 40 | . /usr/local/etc/mavenrc 41 | fi 42 | 43 | if [ -f /etc/mavenrc ] ; then 44 | . /etc/mavenrc 45 | fi 46 | 47 | if [ -f "$HOME/.mavenrc" ] ; then 48 | . "$HOME/.mavenrc" 49 | fi 50 | 51 | fi 52 | 53 | # OS specific support. $var _must_ be set to either true or false. 54 | cygwin=false; 55 | darwin=false; 56 | mingw=false 57 | case "`uname`" in 58 | CYGWIN*) cygwin=true ;; 59 | MINGW*) mingw=true;; 60 | Darwin*) darwin=true 61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 63 | if [ -z "$JAVA_HOME" ]; then 64 | if [ -x "/usr/libexec/java_home" ]; then 65 | export JAVA_HOME="`/usr/libexec/java_home`" 66 | else 67 | export JAVA_HOME="/Library/Java/Home" 68 | fi 69 | fi 70 | ;; 71 | esac 72 | 73 | if [ -z "$JAVA_HOME" ] ; then 74 | if [ -r /etc/gentoo-release ] ; then 75 | JAVA_HOME=`java-config --jre-home` 76 | fi 77 | fi 78 | 79 | if [ -z "$M2_HOME" ] ; then 80 | ## resolve links - $0 may be a link to maven's home 81 | PRG="$0" 82 | 83 | # need this for relative symlinks 84 | while [ -h "$PRG" ] ; do 85 | ls=`ls -ld "$PRG"` 86 | link=`expr "$ls" : '.*-> \(.*\)$'` 87 | if expr "$link" : '/.*' > /dev/null; then 88 | PRG="$link" 89 | else 90 | PRG="`dirname "$PRG"`/$link" 91 | fi 92 | done 93 | 94 | saveddir=`pwd` 95 | 96 | M2_HOME=`dirname "$PRG"`/.. 97 | 98 | # make it fully qualified 99 | M2_HOME=`cd "$M2_HOME" && pwd` 100 | 101 | cd "$saveddir" 102 | # echo Using m2 at $M2_HOME 103 | fi 104 | 105 | # For Cygwin, ensure paths are in UNIX format before anything is touched 106 | if $cygwin ; then 107 | [ -n "$M2_HOME" ] && 108 | M2_HOME=`cygpath --unix "$M2_HOME"` 109 | [ -n "$JAVA_HOME" ] && 110 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 111 | [ -n "$CLASSPATH" ] && 112 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 113 | fi 114 | 115 | # For Mingw, ensure paths are in UNIX format before anything is touched 116 | if $mingw ; then 117 | [ -n "$M2_HOME" ] && 118 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 119 | [ -n "$JAVA_HOME" ] && 120 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 121 | fi 122 | 123 | if [ -z "$JAVA_HOME" ]; then 124 | javaExecutable="`which javac`" 125 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 126 | # readlink(1) is not available as standard on Solaris 10. 127 | readLink=`which readlink` 128 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 129 | if $darwin ; then 130 | javaHome="`dirname \"$javaExecutable\"`" 131 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 132 | else 133 | javaExecutable="`readlink -f \"$javaExecutable\"`" 134 | fi 135 | javaHome="`dirname \"$javaExecutable\"`" 136 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 137 | JAVA_HOME="$javaHome" 138 | export JAVA_HOME 139 | fi 140 | fi 141 | fi 142 | 143 | if [ -z "$JAVACMD" ] ; then 144 | if [ -n "$JAVA_HOME" ] ; then 145 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 146 | # IBM's JDK on AIX uses strange locations for the executables 147 | JAVACMD="$JAVA_HOME/jre/sh/java" 148 | else 149 | JAVACMD="$JAVA_HOME/bin/java" 150 | fi 151 | else 152 | JAVACMD="`\\unset -f command; \\command -v java`" 153 | fi 154 | fi 155 | 156 | if [ ! -x "$JAVACMD" ] ; then 157 | echo "Error: JAVA_HOME is not defined correctly." >&2 158 | echo " We cannot execute $JAVACMD" >&2 159 | exit 1 160 | fi 161 | 162 | if [ -z "$JAVA_HOME" ] ; then 163 | echo "Warning: JAVA_HOME environment variable is not set." 164 | fi 165 | 166 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 167 | 168 | # traverses directory structure from process work directory to filesystem root 169 | # first directory with .mvn subdirectory is considered project base directory 170 | find_maven_basedir() { 171 | 172 | if [ -z "$1" ] 173 | then 174 | echo "Path not specified to find_maven_basedir" 175 | return 1 176 | fi 177 | 178 | basedir="$1" 179 | wdir="$1" 180 | while [ "$wdir" != '/' ] ; do 181 | if [ -d "$wdir"/.mvn ] ; then 182 | basedir=$wdir 183 | break 184 | fi 185 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 186 | if [ -d "${wdir}" ]; then 187 | wdir=`cd "$wdir/.."; pwd` 188 | fi 189 | # end of workaround 190 | done 191 | echo "${basedir}" 192 | } 193 | 194 | # concatenates all lines of a file 195 | concat_lines() { 196 | if [ -f "$1" ]; then 197 | echo "$(tr -s '\n' ' ' < "$1")" 198 | fi 199 | } 200 | 201 | BASE_DIR=`find_maven_basedir "$(pwd)"` 202 | if [ -z "$BASE_DIR" ]; then 203 | exit 1; 204 | fi 205 | 206 | ########################################################################################## 207 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 208 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 209 | ########################################################################################## 210 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Found .mvn/wrapper/maven-wrapper.jar" 213 | fi 214 | else 215 | if [ "$MVNW_VERBOSE" = true ]; then 216 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 217 | fi 218 | if [ -n "$MVNW_REPOURL" ]; then 219 | jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 220 | else 221 | jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 222 | fi 223 | while IFS="=" read key value; do 224 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 225 | esac 226 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 227 | if [ "$MVNW_VERBOSE" = true ]; then 228 | echo "Downloading from: $jarUrl" 229 | fi 230 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 231 | if $cygwin; then 232 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 233 | fi 234 | 235 | if command -v wget > /dev/null; then 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Found wget ... using wget" 238 | fi 239 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 240 | wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 241 | else 242 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 243 | fi 244 | elif command -v curl > /dev/null; then 245 | if [ "$MVNW_VERBOSE" = true ]; then 246 | echo "Found curl ... using curl" 247 | fi 248 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 249 | curl -o "$wrapperJarPath" "$jarUrl" -f 250 | else 251 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 252 | fi 253 | 254 | else 255 | if [ "$MVNW_VERBOSE" = true ]; then 256 | echo "Falling back to using Java to download" 257 | fi 258 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 259 | # For Cygwin, switch paths to Windows format before running javac 260 | if $cygwin; then 261 | javaClass=`cygpath --path --windows "$javaClass"` 262 | fi 263 | if [ -e "$javaClass" ]; then 264 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 265 | if [ "$MVNW_VERBOSE" = true ]; then 266 | echo " - Compiling MavenWrapperDownloader.java ..." 267 | fi 268 | # Compiling the Java class 269 | ("$JAVA_HOME/bin/javac" "$javaClass") 270 | fi 271 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 272 | # Running the downloader 273 | if [ "$MVNW_VERBOSE" = true ]; then 274 | echo " - Running MavenWrapperDownloader.java ..." 275 | fi 276 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 277 | fi 278 | fi 279 | fi 280 | fi 281 | ########################################################################################## 282 | # End of extension 283 | ########################################################################################## 284 | 285 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 286 | if [ "$MVNW_VERBOSE" = true ]; then 287 | echo $MAVEN_PROJECTBASEDIR 288 | fi 289 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 290 | 291 | # For Cygwin, switch paths to Windows format before running java 292 | if $cygwin; then 293 | [ -n "$M2_HOME" ] && 294 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 295 | [ -n "$JAVA_HOME" ] && 296 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 297 | [ -n "$CLASSPATH" ] && 298 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 299 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 300 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 301 | fi 302 | 303 | # Provide a "standardized" way to retrieve the CLI args that will 304 | # work with both Windows and non-Windows executions. 305 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 306 | export MAVEN_CMD_LINE_ARGS 307 | 308 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 309 | 310 | exec "$JAVACMD" \ 311 | $MAVEN_OPTS \ 312 | $MAVEN_DEBUG_OPTS \ 313 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 314 | "-Dmaven.home=${M2_HOME}" \ 315 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 316 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 317 | --------------------------------------------------------------------------------