├── order-service ├── settings.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── src │ ├── main │ │ ├── java │ │ │ └── payment │ │ │ │ └── saga │ │ │ │ └── order │ │ │ │ ├── model │ │ │ │ ├── Event.java │ │ │ │ ├── Order.java │ │ │ │ ├── Payment.java │ │ │ │ ├── Product.java │ │ │ │ ├── OrderPurchaseEvent.java │ │ │ │ ├── TransactionEvent.java │ │ │ │ ├── PaymentEvent.java │ │ │ │ └── OrderPurchase.java │ │ │ │ ├── enums │ │ │ │ ├── PaymentStatus.java │ │ │ │ ├── TransactionStatus.java │ │ │ │ └── OrderStatus.java │ │ │ │ ├── consumer │ │ │ │ ├── EventConsumer.java │ │ │ │ └── TransactionEventConsumer.java │ │ │ │ ├── repository │ │ │ │ ├── ProductRepository.java │ │ │ │ └── OrderPurchaseRepository.java │ │ │ │ ├── OrderServiceApplication.java │ │ │ │ ├── config │ │ │ │ ├── JdbcConfig.java │ │ │ │ └── OrderServiceConfig.java │ │ │ │ ├── processor │ │ │ │ └── OrderPurchaseProcessor.java │ │ │ │ ├── controller │ │ │ │ └── OrderController.java │ │ │ │ └── service │ │ │ │ └── OrderService.java │ │ └── resources │ │ │ ├── data.sql │ │ │ └── application.yml │ └── test │ │ └── java │ │ └── payment │ │ └── saga │ │ └── order │ │ └── OrderServiceApplicationTests.java ├── .gitignore ├── build.gradle ├── gradlew.bat └── gradlew ├── payment-service ├── settings.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── src │ ├── main │ │ ├── java │ │ │ └── payment │ │ │ │ └── saga │ │ │ │ └── payment │ │ │ │ ├── model │ │ │ │ ├── Event.java │ │ │ │ ├── Payment.java │ │ │ │ ├── Transaction.java │ │ │ │ ├── TransactionEvent.java │ │ │ │ ├── OrderPurchaseEvent.java │ │ │ │ ├── PaymentEvent.java │ │ │ │ └── User.java │ │ │ │ ├── enums │ │ │ │ ├── PaymentStatus.java │ │ │ │ └── TransactionStatus.java │ │ │ │ ├── handler │ │ │ │ ├── EventHandler.java │ │ │ │ ├── OrderPurchaseEventHandler.java │ │ │ │ └── PaymentEventHandler.java │ │ │ │ ├── repository │ │ │ │ ├── UserRepository.java │ │ │ │ └── TransactionRepository.java │ │ │ │ ├── PaymentServiceApplication.java │ │ │ │ ├── config │ │ │ │ ├── JdbcConfig.java │ │ │ │ └── PaymentServiceConfig.java │ │ │ │ ├── controller │ │ │ │ └── TransactionController.java │ │ │ │ └── service │ │ │ │ └── TransactionService.java │ │ └── resources │ │ │ ├── data.sql │ │ │ └── application.yml │ └── test │ │ └── java │ │ └── payment │ │ └── saga │ │ └── payment │ │ └── PaymentServiceApplicationTests.java ├── .gitignore ├── build.gradle ├── gradlew.bat └── gradlew ├── Choreography Saga.jpg ├── .gitignore ├── docker ├── .gitignore └── docker-compose.yml ├── README.md └── LICENSE /order-service/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'order-service' 2 | -------------------------------------------------------------------------------- /payment-service/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'payment-service' 2 | -------------------------------------------------------------------------------- /Choreography Saga.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohnChangUK/Payment-Choreography-Saga/HEAD/Choreography Saga.jpg -------------------------------------------------------------------------------- /order-service/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohnChangUK/Payment-Choreography-Saga/HEAD/order-service/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/model/Event.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.model; 2 | 3 | public interface Event { 4 | 5 | String getEvent(); 6 | } 7 | -------------------------------------------------------------------------------- /payment-service/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohnChangUK/Payment-Choreography-Saga/HEAD/payment-service/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/model/Event.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.model; 2 | 3 | public interface Event { 4 | 5 | String getEvent(); 6 | } 7 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/enums/PaymentStatus.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.enums; 2 | 3 | public enum PaymentStatus { 4 | 5 | APPROVED, 6 | DECLINED 7 | 8 | } 9 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/enums/PaymentStatus.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.enums; 2 | 3 | public enum PaymentStatus { 4 | 5 | APPROVED, 6 | DECLINED 7 | 8 | } 9 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/enums/TransactionStatus.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.enums; 2 | 3 | public enum TransactionStatus { 4 | 5 | SUCCESSFUL, 6 | UNSUCCESSFUL 7 | 8 | } 9 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/enums/TransactionStatus.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.enums; 2 | 3 | public enum TransactionStatus { 4 | 5 | SUCCESSFUL, 6 | UNSUCCESSFUL 7 | 8 | } 9 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/enums/OrderStatus.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.enums; 2 | 3 | public enum OrderStatus { 4 | 5 | CREATED, 6 | COMPLETED, 7 | FAILED 8 | 9 | } 10 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/model/Order.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.model; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class Order { 7 | 8 | private Integer userId; 9 | private Integer productId; 10 | 11 | } 12 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/consumer/EventConsumer.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.consumer; 2 | 3 | import payment.saga.order.model.Event; 4 | 5 | public interface EventConsumer { 6 | 7 | void consumeEvent(T event); 8 | } 9 | -------------------------------------------------------------------------------- /order-service/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /payment-service/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/handler/EventHandler.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.handler; 2 | 3 | import payment.saga.payment.model.Event; 4 | 5 | public interface EventHandler { 6 | 7 | R handleEvent(T event); 8 | } 9 | -------------------------------------------------------------------------------- /order-service/src/test/java/payment/saga/order/OrderServiceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class OrderServiceApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /payment-service/src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE IF EXISTS users; 2 | 3 | CREATE TABLE users ( 4 | id INT AUTO_INCREMENT PRIMARY KEY, 5 | user_id INT(250) NOT NULL, 6 | balance float NOT NULL 7 | ); 8 | 9 | INSERT INTO users (user_id, balance) VALUES 10 | (1, 100.00), 11 | (2, 200.00), 12 | (3, 500.00), 13 | (4, 1000.00), 14 | (5, 2000.00); -------------------------------------------------------------------------------- /payment-service/src/test/java/payment/saga/payment/PaymentServiceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class PaymentServiceApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /order-service/src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE IF EXISTS products; 2 | 3 | CREATE TABLE products ( 4 | id INT AUTO_INCREMENT PRIMARY KEY, 5 | product_id INT(250) NOT NULL, 6 | price float NOT NULL 7 | ); 8 | 9 | INSERT INTO products (product_id, price) VALUES 10 | (1, 50.00), 11 | (2, 75.00), 12 | (3, 100.00), 13 | (4, 500.00), 14 | (5, 1000.00); 15 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | import payment.saga.payment.model.User; 6 | 7 | @Repository 8 | public interface UserRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/repository/ProductRepository.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | import payment.saga.order.model.Product; 6 | 7 | @Repository 8 | public interface ProductRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/repository/OrderPurchaseRepository.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | import payment.saga.order.model.OrderPurchase; 6 | 7 | @Repository 8 | public interface OrderPurchaseRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/repository/TransactionRepository.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | import payment.saga.payment.model.Transaction; 6 | 7 | @Repository 8 | public interface TransactionRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/OrderServiceApplication.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class OrderServiceApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(OrderServiceApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/PaymentServiceApplication.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class PaymentServiceApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(PaymentServiceApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/model/Payment.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.model; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.ToString; 6 | 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.Id; 10 | import java.math.BigDecimal; 11 | 12 | @AllArgsConstructor 13 | @Data 14 | @Entity 15 | @ToString 16 | public class Payment { 17 | 18 | @Id 19 | @GeneratedValue 20 | private Integer id; 21 | private BigDecimal amount; 22 | } 23 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/model/Payment.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.model; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.ToString; 6 | 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.Id; 10 | import java.math.BigDecimal; 11 | 12 | @AllArgsConstructor 13 | @Data 14 | @Entity 15 | @ToString 16 | public class Payment { 17 | 18 | @Id 19 | @GeneratedValue 20 | private Integer id; 21 | private BigDecimal amount; 22 | } 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /order-service/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /payment-service/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /docker/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | zk-single-kafka-multiple/ 8 | 9 | 10 | ### STS ### 11 | .apt_generated 12 | .classpath 13 | .factorypath 14 | .project 15 | .settings 16 | .springBeans 17 | .sts4-cache 18 | bin/ 19 | !**/src/main/**/bin/ 20 | !**/src/test/**/bin/ 21 | 22 | ### IntelliJ IDEA ### 23 | .idea 24 | *.iws 25 | *.iml 26 | *.ipr 27 | out/ 28 | !**/src/main/**/out/ 29 | !**/src/test/**/out/ 30 | 31 | ### NetBeans ### 32 | /nbproject/private/ 33 | /nbbuild/ 34 | /dist/ 35 | /nbdist/ 36 | /.nb-gradle/ 37 | 38 | ### VS Code ### 39 | .vscode/ 40 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/model/Product.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.model; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | import lombok.ToString; 7 | 8 | import javax.persistence.Entity; 9 | import javax.persistence.GeneratedValue; 10 | import javax.persistence.Id; 11 | import javax.persistence.Table; 12 | 13 | @ToString 14 | @AllArgsConstructor 15 | @NoArgsConstructor 16 | @Data 17 | @Entity 18 | @Table(name = "products") 19 | public class Product { 20 | 21 | @Id 22 | @GeneratedValue 23 | private Integer id; 24 | private Integer productId; 25 | private double price; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/config/JdbcConfig.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import reactor.core.scheduler.Scheduler; 7 | import reactor.core.scheduler.Schedulers; 8 | 9 | import java.util.concurrent.Executors; 10 | 11 | @Configuration 12 | public class JdbcConfig { 13 | 14 | @Bean 15 | public Scheduler jdbcScheduler(@Value("${spring.datasource.maximum-pool-size}") int connectionPoolSize) { 16 | return Schedulers.fromExecutor(Executors.newFixedThreadPool(connectionPoolSize)); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/config/JdbcConfig.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import reactor.core.scheduler.Scheduler; 7 | import reactor.core.scheduler.Schedulers; 8 | 9 | import java.util.concurrent.Executors; 10 | 11 | @Configuration 12 | public class JdbcConfig { 13 | 14 | @Bean 15 | public Scheduler jdbcScheduler(@Value("${spring.datasource.maximum-pool-size}") int connectionPoolSize) { 16 | return Schedulers.fromExecutor(Executors.newFixedThreadPool(connectionPoolSize)); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /order-service/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9192 3 | 4 | spring: 5 | cloud: 6 | stream: 7 | function: 8 | definition: orderPurchaseEventPublisher;transactionEventProcessor; 9 | bindings: 10 | orderPurchaseEventPublisher-out-0: 11 | destination: orders 12 | transactionEventProcessor-in-0: 13 | destination: transactions 14 | datasource: 15 | url: jdbc:h2:mem:mydb;DB_CLOSE_DELAY=-1 16 | driverClassName: org.h2.Driver 17 | username: sa 18 | password: 19 | maximum-pool-size: 100 20 | jpa: 21 | hibernate: 22 | ddl-auto: create 23 | database-platform: org.hibernate.dialect.H2Dialect 24 | database: H2 25 | generate-ddl: true 26 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/model/Transaction.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.model; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.ToString; 6 | 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.Id; 10 | 11 | @ToString 12 | @AllArgsConstructor 13 | @Data 14 | @Entity 15 | public class Transaction { 16 | 17 | @Id 18 | @GeneratedValue 19 | private Integer id; 20 | private Integer orderId; 21 | private double price; 22 | 23 | public Transaction() { 24 | } 25 | 26 | public Transaction setOrderId(Integer orderId) { 27 | this.orderId = orderId; 28 | return this; 29 | } 30 | 31 | public Transaction setPrice(double price) { 32 | this.price = price; 33 | return this; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /payment-service/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9191 3 | 4 | spring: 5 | cloud: 6 | stream: 7 | function: 8 | definition: orderPurchaseEventProcessor;paymentEventSubscriber 9 | bindings: 10 | orderPurchaseEventProcessor-in-0: 11 | destination: orders 12 | orderPurchaseEventProcessor-out-0: 13 | destination: payments 14 | paymentEventSubscriber-in-0: 15 | destination: payments 16 | paymentEventSubscriber-out-0: 17 | destination: transactions 18 | datasource: 19 | url: jdbc:h2:mem:testdb 20 | driverClassName: org.h2.Driver 21 | username: sa 22 | password: 23 | maximum-pool-size: 100 24 | jpa: 25 | hibernate: 26 | ddl-auto: create 27 | database-platform: org.hibernate.dialect.H2Dialect 28 | database: H2 29 | generate-ddl: true 30 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/model/OrderPurchaseEvent.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.model; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class OrderPurchaseEvent implements Event { 7 | 8 | private static final String EVENT = "OrderPurchase"; 9 | 10 | private Integer orderId; 11 | private Integer userId; 12 | private double price; 13 | 14 | public OrderPurchaseEvent setOrderId(Integer orderId) { 15 | this.orderId = orderId; 16 | return this; 17 | } 18 | 19 | public OrderPurchaseEvent setUserId(Integer userId) { 20 | this.userId = userId; 21 | return this; 22 | } 23 | 24 | public OrderPurchaseEvent setPrice(double price) { 25 | this.price = price; 26 | return this; 27 | } 28 | 29 | @Override 30 | public String getEvent() { 31 | return EVENT; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/model/TransactionEvent.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.model; 2 | 3 | import lombok.Getter; 4 | import lombok.ToString; 5 | import payment.saga.order.enums.TransactionStatus; 6 | 7 | @ToString 8 | @Getter 9 | public class TransactionEvent implements Event { 10 | 11 | private static final String EVENT = "Transaction"; 12 | 13 | private Integer orderId; 14 | private TransactionStatus status; 15 | 16 | public TransactionEvent() { 17 | } 18 | 19 | public TransactionEvent orderId(Integer orderId) { 20 | this.orderId = orderId; 21 | return this; 22 | } 23 | 24 | public TransactionEvent status(TransactionStatus status) { 25 | this.status = status; 26 | return this; 27 | } 28 | 29 | @Override 30 | public String getEvent() { 31 | return EVENT; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/model/TransactionEvent.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.model; 2 | 3 | import lombok.Getter; 4 | import lombok.ToString; 5 | import payment.saga.payment.enums.TransactionStatus; 6 | 7 | @ToString 8 | @Getter 9 | public class TransactionEvent implements Event { 10 | 11 | private static final String EVENT = "Transaction"; 12 | 13 | private Integer orderId; 14 | private TransactionStatus status; 15 | 16 | public TransactionEvent() { 17 | } 18 | 19 | public TransactionEvent orderId(Integer orderId) { 20 | this.orderId = orderId; 21 | return this; 22 | } 23 | 24 | public TransactionEvent status(TransactionStatus status) { 25 | this.status = status; 26 | return this; 27 | } 28 | 29 | @Override 30 | public String getEvent() { 31 | return EVENT; 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/model/OrderPurchaseEvent.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.model; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class OrderPurchaseEvent implements Event { 7 | 8 | private static final String EVENT = "OrderPurchase"; 9 | 10 | private Integer orderId; 11 | private Integer userId; 12 | private double price; 13 | 14 | public OrderPurchaseEvent setOrderId(Integer orderId) { 15 | this.orderId = orderId; 16 | return this; 17 | } 18 | 19 | public OrderPurchaseEvent setUserId(Integer userId) { 20 | this.userId = userId; 21 | return this; 22 | } 23 | 24 | public OrderPurchaseEvent setPrice(double price) { 25 | this.price = price; 26 | return this; 27 | } 28 | 29 | @Override 30 | public String getEvent() { 31 | return EVENT; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/model/PaymentEvent.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.model; 2 | 3 | import lombok.Getter; 4 | import lombok.ToString; 5 | import payment.saga.order.enums.PaymentStatus; 6 | 7 | @ToString 8 | @Getter 9 | public class PaymentEvent implements Event { 10 | 11 | private static final String EVENT = "Payment"; 12 | 13 | private Integer orderId; 14 | private PaymentStatus status; 15 | private double price; 16 | 17 | public PaymentEvent() { 18 | } 19 | 20 | public PaymentEvent orderId(Integer orderId) { 21 | this.orderId = orderId; 22 | return this; 23 | } 24 | 25 | public PaymentEvent status(PaymentStatus status) { 26 | this.status = status; 27 | return this; 28 | } 29 | 30 | public PaymentEvent price(double price) { 31 | this.price = price; 32 | return this; 33 | } 34 | 35 | @Override 36 | public String getEvent() { 37 | return EVENT; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/model/PaymentEvent.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.model; 2 | 3 | import lombok.Getter; 4 | import lombok.ToString; 5 | import payment.saga.payment.enums.PaymentStatus; 6 | 7 | @ToString 8 | @Getter 9 | public class PaymentEvent implements Event { 10 | 11 | private static final String EVENT = "Payment"; 12 | 13 | private Integer orderId; 14 | private PaymentStatus status; 15 | private double price; 16 | 17 | public PaymentEvent() { 18 | } 19 | 20 | public PaymentEvent orderId(Integer orderId) { 21 | this.orderId = orderId; 22 | return this; 23 | } 24 | 25 | public PaymentEvent status(PaymentStatus status) { 26 | this.status = status; 27 | return this; 28 | } 29 | 30 | public PaymentEvent price(double price) { 31 | this.price = price; 32 | return this; 33 | } 34 | 35 | @Override 36 | public String getEvent() { 37 | return EVENT; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/processor/OrderPurchaseProcessor.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.processor; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Component; 5 | import payment.saga.order.model.OrderPurchase; 6 | import payment.saga.order.model.OrderPurchaseEvent; 7 | import reactor.core.publisher.Sinks; 8 | 9 | @Component 10 | public class OrderPurchaseProcessor { 11 | 12 | private final Sinks.Many sink; 13 | 14 | @Autowired 15 | public OrderPurchaseProcessor(Sinks.Many sink) { 16 | this.sink = sink; 17 | } 18 | 19 | public void process(OrderPurchase orderPurchase) { 20 | OrderPurchaseEvent orderPurchaseEvent = new OrderPurchaseEvent() 21 | .setUserId(orderPurchase.getUserId()) 22 | .setOrderId(orderPurchase.getId()) 23 | .setPrice(orderPurchase.getPrice()); 24 | sink.emitNext(orderPurchaseEvent, Sinks.EmitFailureHandler.FAIL_FAST); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/model/User.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.model; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.ToString; 6 | 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.Id; 10 | import javax.persistence.Table; 11 | 12 | @ToString 13 | @AllArgsConstructor 14 | @Data 15 | @Entity 16 | @Table(name = "users") 17 | public class User { 18 | 19 | @Id 20 | @GeneratedValue 21 | private Integer id; 22 | private Integer userId; 23 | private double balance; 24 | 25 | public User() { 26 | } 27 | 28 | public Integer getId() { 29 | return id; 30 | } 31 | 32 | public void setId(Integer id) { 33 | this.id = id; 34 | } 35 | 36 | public Integer getUserId() { 37 | return userId; 38 | } 39 | 40 | public void setUserId(Integer userId) { 41 | this.userId = userId; 42 | } 43 | 44 | public double getBalance() { 45 | return balance; 46 | } 47 | 48 | public void setBalance(double balance) { 49 | this.balance = balance; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/model/OrderPurchase.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.model; 2 | 3 | import lombok.Data; 4 | import lombok.ToString; 5 | import payment.saga.order.enums.OrderStatus; 6 | 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.Id; 10 | 11 | @Data 12 | @Entity 13 | @ToString 14 | public class OrderPurchase { 15 | 16 | public OrderPurchase() { 17 | } 18 | 19 | @Id 20 | @GeneratedValue 21 | private Integer id; 22 | private Integer userId; 23 | private Integer productId; 24 | private double price; 25 | private OrderStatus status; 26 | 27 | public OrderPurchase setUserId(Integer userId) { 28 | this.userId = userId; 29 | return this; 30 | } 31 | 32 | public OrderPurchase setProductId(Integer productId) { 33 | this.productId = productId; 34 | return this; 35 | } 36 | 37 | public OrderPurchase setPrice(double price) { 38 | this.price = price; 39 | return this; 40 | } 41 | 42 | public OrderPurchase setStatus(OrderStatus status) { 43 | this.status = status; 44 | return this; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /order-service/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.4.1' 3 | id 'io.spring.dependency-management' version '1.0.10.RELEASE' 4 | id 'java' 5 | } 6 | 7 | group = 'payment.saga.order' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '11' 10 | 11 | configurations { 12 | compileOnly { 13 | extendsFrom annotationProcessor 14 | } 15 | } 16 | 17 | repositories { 18 | mavenCentral() 19 | maven { url 'https://repo.spring.io/milestone' } 20 | } 21 | 22 | ext { 23 | set('springCloudVersion', "2020.0.0") 24 | } 25 | 26 | dependencies { 27 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 28 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 29 | implementation 'org.springframework.cloud:spring-cloud-stream' 30 | implementation 'org.springframework.cloud:spring-cloud-stream-binder-kafka' 31 | implementation 'org.springframework.kafka:spring-kafka' 32 | implementation 'com.h2database:h2:1.4.200' 33 | compileOnly 'org.projectlombok:lombok' 34 | annotationProcessor 'org.projectlombok:lombok' 35 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 36 | testImplementation 'io.projectreactor:reactor-test' 37 | testImplementation 'org.springframework.kafka:spring-kafka-test' 38 | } 39 | 40 | dependencyManagement { 41 | imports { 42 | mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" 43 | } 44 | } 45 | 46 | test { 47 | useJUnitPlatform() 48 | } 49 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/config/OrderServiceConfig.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import payment.saga.order.consumer.EventConsumer; 7 | import payment.saga.order.model.OrderPurchaseEvent; 8 | import payment.saga.order.model.TransactionEvent; 9 | import reactor.core.publisher.Flux; 10 | import reactor.core.publisher.Sinks; 11 | 12 | import java.util.function.Consumer; 13 | import java.util.function.Supplier; 14 | 15 | @Configuration 16 | public class OrderServiceConfig { 17 | 18 | private final EventConsumer transactionEventConsumer; 19 | 20 | @Autowired 21 | public OrderServiceConfig(EventConsumer transactionEventConsumer) { 22 | this.transactionEventConsumer = transactionEventConsumer; 23 | } 24 | 25 | @Bean 26 | public Sinks.Many sink() { 27 | return Sinks.many() 28 | .multicast() 29 | .directBestEffort(); 30 | } 31 | 32 | @Bean 33 | public Supplier> orderPurchaseEventPublisher( 34 | Sinks.Many publisher) { 35 | return publisher::asFlux; 36 | } 37 | 38 | @Bean 39 | public Consumer transactionEventProcessor() { 40 | return transactionEventConsumer::consumeEvent; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/controller/TransactionController.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.controller; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.http.MediaType; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.PathVariable; 7 | import org.springframework.web.bind.annotation.RestController; 8 | import payment.saga.payment.model.Transaction; 9 | import payment.saga.payment.service.TransactionService; 10 | import reactor.core.publisher.Flux; 11 | import reactor.core.publisher.Mono; 12 | 13 | import java.util.List; 14 | 15 | @RestController 16 | public class TransactionController { 17 | 18 | private final TransactionService transactionService; 19 | 20 | @Autowired 21 | public TransactionController(TransactionService transactionService) { 22 | this.transactionService = transactionService; 23 | } 24 | 25 | @GetMapping("transactions/all") 26 | public Flux getAllOrders() { 27 | return transactionService.getAll(); 28 | } 29 | 30 | @GetMapping(path = "transactions/all/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) 31 | public Flux> getAllOrdersStream() { 32 | return transactionService.reactiveGetAll(); 33 | } 34 | 35 | @GetMapping("transactions/{id}") 36 | public Mono getOrderById(@PathVariable Integer id) { 37 | return transactionService.getOrderById(id); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /payment-service/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.4.1' 3 | id 'io.spring.dependency-management' version '1.0.10.RELEASE' 4 | id 'java' 5 | } 6 | 7 | group = 'payment.saga.payment' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '11' 10 | 11 | configurations { 12 | compileOnly { 13 | extendsFrom annotationProcessor 14 | } 15 | } 16 | 17 | repositories { 18 | mavenCentral() 19 | maven { url 'https://repo.spring.io/milestone' } 20 | } 21 | 22 | ext { 23 | set('springCloudVersion', "2020.0.0") 24 | } 25 | 26 | dependencies { 27 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 28 | implementation 'org.springframework.boot:spring-boot-devtools' 29 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 30 | implementation 'org.springframework.cloud:spring-cloud-stream' 31 | implementation 'org.springframework.cloud:spring-cloud-stream-binder-kafka' 32 | implementation 'org.springframework.kafka:spring-kafka' 33 | implementation 'com.h2database:h2:1.4.200' 34 | compileOnly 'org.projectlombok:lombok' 35 | annotationProcessor 'org.projectlombok:lombok' 36 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 37 | testImplementation 'io.projectreactor:reactor-test' 38 | testImplementation 'org.springframework.kafka:spring-kafka-test' 39 | } 40 | 41 | dependencyManagement { 42 | imports { 43 | mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" 44 | } 45 | } 46 | 47 | test { 48 | useJUnitPlatform() 49 | } 50 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/config/PaymentServiceConfig.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import payment.saga.payment.handler.EventHandler; 7 | import payment.saga.payment.model.OrderPurchaseEvent; 8 | import payment.saga.payment.model.PaymentEvent; 9 | import payment.saga.payment.model.TransactionEvent; 10 | 11 | import java.util.function.Function; 12 | 13 | @Configuration 14 | public class PaymentServiceConfig { 15 | 16 | private final EventHandler paymentEventHandler; 17 | private final EventHandler orderPurchaseEventHandler; 18 | 19 | @Autowired 20 | public PaymentServiceConfig( 21 | EventHandler paymentEventHandler, 22 | EventHandler orderPurchaseEventHandler) { 23 | this.paymentEventHandler = paymentEventHandler; 24 | this.orderPurchaseEventHandler = orderPurchaseEventHandler; 25 | } 26 | 27 | @Bean 28 | public Function orderPurchaseEventProcessor() { 29 | return orderPurchaseEventHandler::handleEvent; 30 | } 31 | 32 | @Bean 33 | public Function paymentEventSubscriber() { 34 | return paymentEventHandler::handleEvent; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/controller/OrderController.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.controller; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.http.MediaType; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.PathVariable; 7 | import org.springframework.web.bind.annotation.PostMapping; 8 | import org.springframework.web.bind.annotation.RequestBody; 9 | import org.springframework.web.bind.annotation.RestController; 10 | import payment.saga.order.model.Order; 11 | import payment.saga.order.model.OrderPurchase; 12 | import payment.saga.order.service.OrderService; 13 | import reactor.core.publisher.Flux; 14 | import reactor.core.publisher.Mono; 15 | 16 | import java.util.List; 17 | 18 | @RestController 19 | public class OrderController { 20 | 21 | private final OrderService orderService; 22 | 23 | @Autowired 24 | public OrderController(OrderService orderService) { 25 | this.orderService = orderService; 26 | } 27 | 28 | @PostMapping("orders/create") 29 | public Mono createOrder(@RequestBody Order order) { 30 | return orderService.createOrder(order); 31 | } 32 | 33 | @GetMapping("orders/all") 34 | public Flux getAllOrders() { 35 | return orderService.getAll(); 36 | } 37 | 38 | @GetMapping(path = "orders/all/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) 39 | public Flux> getAllOrdersStream() { 40 | return orderService.reactiveGetAll(); 41 | } 42 | 43 | @GetMapping("orders/{id}") 44 | public Mono getOrderById(@PathVariable Integer id) { 45 | return orderService.getOrderById(id); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/consumer/TransactionEventConsumer.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.consumer; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Component; 5 | import payment.saga.order.model.OrderPurchase; 6 | import payment.saga.order.model.TransactionEvent; 7 | import payment.saga.order.repository.OrderPurchaseRepository; 8 | import reactor.core.publisher.Mono; 9 | import reactor.core.scheduler.Scheduler; 10 | 11 | import static payment.saga.order.enums.OrderStatus.COMPLETED; 12 | import static payment.saga.order.enums.OrderStatus.FAILED; 13 | import static payment.saga.order.enums.TransactionStatus.SUCCESSFUL; 14 | 15 | @Component 16 | public class TransactionEventConsumer implements EventConsumer { 17 | 18 | private final OrderPurchaseRepository orderPurchaseRepository; 19 | private final Scheduler jdbcScheduler; 20 | 21 | @Autowired 22 | public TransactionEventConsumer( 23 | OrderPurchaseRepository orderPurchaseRepository, 24 | Scheduler jdbcScheduler) { 25 | this.orderPurchaseRepository = orderPurchaseRepository; 26 | this.jdbcScheduler = jdbcScheduler; 27 | } 28 | 29 | public void consumeEvent(TransactionEvent event) { 30 | Mono.fromRunnable( 31 | () -> orderPurchaseRepository.findById(event.getOrderId()) 32 | .ifPresent(order -> { 33 | setStatus(event, order); 34 | orderPurchaseRepository.save(order); 35 | })) 36 | .subscribeOn(jdbcScheduler) 37 | .subscribe(); 38 | } 39 | 40 | private void setStatus(TransactionEvent transactionEvent, OrderPurchase order) { 41 | order.setStatus(SUCCESSFUL.equals(transactionEvent.getStatus()) 42 | ? COMPLETED 43 | : FAILED); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/handler/OrderPurchaseEventHandler.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.handler; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Component; 5 | import payment.saga.payment.model.OrderPurchaseEvent; 6 | import payment.saga.payment.model.PaymentEvent; 7 | import payment.saga.payment.model.User; 8 | import payment.saga.payment.repository.UserRepository; 9 | 10 | import javax.transaction.Transactional; 11 | 12 | import static payment.saga.payment.enums.PaymentStatus.APPROVED; 13 | import static payment.saga.payment.enums.PaymentStatus.DECLINED; 14 | 15 | @Component 16 | public class OrderPurchaseEventHandler implements EventHandler { 17 | 18 | private final UserRepository userRepository; 19 | 20 | @Autowired 21 | public OrderPurchaseEventHandler(UserRepository userRepository) { 22 | this.userRepository = userRepository; 23 | } 24 | 25 | @Transactional 26 | public PaymentEvent handleEvent(OrderPurchaseEvent event) { 27 | double orderPrice = event.getPrice(); 28 | Integer userId = event.getUserId(); 29 | PaymentEvent paymentEvent = new PaymentEvent() 30 | .orderId(event.getOrderId()) 31 | .price(event.getPrice()) 32 | .status(DECLINED); 33 | userRepository 34 | .findById(userId) 35 | .ifPresent(user -> deductUserBalance(orderPrice, paymentEvent, user)); 36 | return paymentEvent; 37 | } 38 | 39 | private void deductUserBalance(double orderPrice, PaymentEvent paymentEvent, User user) { 40 | double userBalance = user.getBalance(); 41 | if (userBalance >= orderPrice) { 42 | user.setBalance(userBalance - orderPrice); 43 | userRepository.save(user); 44 | paymentEvent.status(APPROVED); 45 | } 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/handler/PaymentEventHandler.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.handler; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Component; 5 | import payment.saga.payment.model.PaymentEvent; 6 | import payment.saga.payment.model.Transaction; 7 | import payment.saga.payment.model.TransactionEvent; 8 | import payment.saga.payment.repository.TransactionRepository; 9 | import reactor.core.publisher.Mono; 10 | import reactor.core.scheduler.Scheduler; 11 | 12 | import javax.transaction.Transactional; 13 | 14 | import static payment.saga.payment.enums.PaymentStatus.APPROVED; 15 | import static payment.saga.payment.enums.TransactionStatus.SUCCESSFUL; 16 | import static payment.saga.payment.enums.TransactionStatus.UNSUCCESSFUL; 17 | 18 | @Component 19 | public class PaymentEventHandler implements EventHandler { 20 | 21 | private final TransactionRepository transactionRepository; 22 | private final Scheduler jdbcScheduler; 23 | 24 | @Autowired 25 | public PaymentEventHandler( 26 | TransactionRepository transactionRepository, 27 | Scheduler jdbcScheduler) { 28 | this.transactionRepository = transactionRepository; 29 | this.jdbcScheduler = jdbcScheduler; 30 | } 31 | 32 | @Transactional 33 | public TransactionEvent handleEvent(PaymentEvent event) { 34 | Mono.fromRunnable(() -> transactionRepository.save( 35 | new Transaction() 36 | .setOrderId(event.getOrderId()) 37 | .setPrice(event.getPrice()))) 38 | .subscribeOn(jdbcScheduler) 39 | .subscribe(); 40 | 41 | return new TransactionEvent() 42 | .orderId(event.getOrderId()) 43 | .status(APPROVED.equals(event.getStatus()) 44 | ? SUCCESSFUL 45 | : UNSUCCESSFUL); 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /payment-service/src/main/java/payment/saga/payment/service/TransactionService.java: -------------------------------------------------------------------------------- 1 | package payment.saga.payment.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.web.server.ResponseStatusException; 7 | import payment.saga.payment.model.Transaction; 8 | import payment.saga.payment.repository.TransactionRepository; 9 | import reactor.core.publisher.Flux; 10 | import reactor.core.publisher.Mono; 11 | import reactor.core.scheduler.Scheduler; 12 | import reactor.util.function.Tuple2; 13 | 14 | import java.time.Duration; 15 | import java.util.List; 16 | import java.util.stream.Stream; 17 | 18 | @Service 19 | public class TransactionService { 20 | 21 | private final TransactionRepository transactionRepository; 22 | private final Scheduler jdbcScheduler; 23 | 24 | @Autowired 25 | public TransactionService(TransactionRepository transactionRepository, 26 | Scheduler jdbcScheduler) { 27 | this.transactionRepository = transactionRepository; 28 | this.jdbcScheduler = jdbcScheduler; 29 | } 30 | 31 | public Flux getAll() { 32 | return Flux.defer( 33 | () -> Flux.fromIterable(transactionRepository.findAll())) 34 | .subscribeOn(jdbcScheduler); 35 | } 36 | 37 | public Flux> reactiveGetAll() { 38 | Flux interval = Flux.interval(Duration.ofMillis(2000)); 39 | Flux> transactionFlux = Flux.fromStream( 40 | Stream.generate(transactionRepository::findAll)); 41 | return Flux.zip(interval, transactionFlux) 42 | .map(Tuple2::getT2); 43 | } 44 | 45 | public Mono getOrderById(Integer id) { 46 | return Mono.fromCallable( 47 | () -> transactionRepository.findById(id) 48 | .orElseThrow(() -> new ResponseStatusException( 49 | HttpStatus.NOT_FOUND, "Transaction id: " + id + " does not exist"))) 50 | .subscribeOn(jdbcScheduler); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## [Choreography Saga Pattern](https://docs.microsoft.com/en-us/azure/architecture/reference-architectures/saga/saga) - Payment Microservices 2 | ### [Medium Article](https://medium.com/@johnchang94/choreography-saga-pattern-with-spring-cloud-kafka-ad46f01fc30a) - Explanation In Depth 3 | ### Implemented with 4 | - Spring Cloud Stream with Apache Kafka Binder 5 | - Spring WebFlux 6 | - Leveraging Netty's non-blocking server model 7 | 8 | Operations persising to the database have a dedicated, well-tuned thread pool as it can isolate blocking IO calls separately from the application. 9 | 10 | ### System Design 11 | 12 |

13 | 14 |

15 | 16 | #### To start ZooKeeper and Kafka Brokers 17 | ``` 18 | cd docker 19 | ``` 20 | 21 | - #### Run 22 | ``` 23 | docker-compose up 24 | ``` 25 | 26 | ### Alternatively run Kafka locally by download binaries 27 | #### Kafka Binary Distribution [Download](http://apachemirror.wuchna.com/kafka/2.3.1). 28 | 29 | #### Kafka Docker 30 | - Once the Kafka Docker containers are running, go onto `localhost:9000` and create a cluster `Click 'Add Cluster'` with any name e.g. `payment-saga`. 31 | - Under `Cluster Zookeeper Hosts` enter `zoo:2181` 32 | ### Topics 33 | - There are 3 topics which the Order and Payment Services use; these must be created before starting both applications. 34 | ``` 35 | - orders 36 | - payments 37 | - transactions 38 | ``` 39 | 40 | #### Run 41 | - Run the Order Service and the Payment Service application 42 | - Make a POST Request to `localhost:9192/orders/create` with request body: 43 | ``` 44 | { 45 | "userId": 1, 46 | "productId": 1 47 | } 48 | ``` 49 | - Make a GET Request to `localhost:9192/orders/all` and see the order status updated 50 | 51 | #### Data Flow 52 | - The Order Service application takes in an `Order` as a request, 53 | which creates and sends an `OrderPurchaseEvent` to the Kafka topic `orders` which is processed by `OrderPurchaseEventHandler` in the payment service. 54 | - `OrderPurchaseEventHandler` processes the event and calculates if user has enough credit. If so, 55 | it sets the generated `PaymentEvent` status to `APPROVED`, otherwise `DECLINED`. 56 | - A `PaymentEvent` is emitted to the Kafka topic `payments`, which the `PaymentEventHandler` in the Payment Service application 57 | listens for. 58 | - If the `PaymentEvent` status is `APPROVED`, it saves the transaction in the `TransactionRepository`. 59 | A `TransactionEvent` is emitted to the `transactions` topic. 60 | - The `TransactionEventConsumer` reads this in the order service, if successful, the `OrderRepository` saves this as 61 | `ORDER_COMPLETED`, else `ORDER_FAILED` 62 | -------------------------------------------------------------------------------- /docker/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | services: 4 | zoo: 5 | image: zookeeper:3.4.9 6 | hostname: zoo 7 | ports: 8 | - "2181:2181" 9 | environment: 10 | ZOO_MY_ID: 1 11 | ZOO_PORT: 2181 12 | ZOO_SERVERS: server.1=zoo:2888:3888 13 | volumes: 14 | - ./zk-single-kafka-multiple/zoo/data:/data 15 | - ./zk-single-kafka-multiple/zoo/datalog:/datalog 16 | kafka1: 17 | image: confluentinc/cp-kafka:5.3.0 18 | hostname: kafka1 19 | ports: 20 | - "9092:9092" 21 | environment: 22 | KAFKA_ADVERTISED_LISTENERS: LISTENER_DOCKER_INTERNAL://kafka1:19092,LISTENER_DOCKER_EXTERNAL://${DOCKER_HOST_IP:-127.0.0.1}:9092 23 | KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: LISTENER_DOCKER_INTERNAL:PLAINTEXT,LISTENER_DOCKER_EXTERNAL:PLAINTEXT 24 | KAFKA_INTER_BROKER_LISTENER_NAME: LISTENER_DOCKER_INTERNAL 25 | KAFKA_ZOOKEEPER_CONNECT: "zoo:2181" 26 | KAFKA_BROKER_ID: 1 27 | KAFKA_LOG4J_LOGGERS: "kafka.controller=INFO,kafka.producer.async.DefaultEventHandler=INFO,state.change.logger=INFO" 28 | KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 29 | volumes: 30 | - ./zk-single-kafka-multiple/kafka1/data:/var/lib/kafka/data 31 | depends_on: 32 | - zoo 33 | kafka2: 34 | image: confluentinc/cp-kafka:5.3.0 35 | hostname: kafka2 36 | ports: 37 | - "9093:9093" 38 | environment: 39 | KAFKA_ADVERTISED_LISTENERS: LISTENER_DOCKER_INTERNAL://kafka2:19093,LISTENER_DOCKER_EXTERNAL://${DOCKER_HOST_IP:-127.0.0.1}:9093 40 | KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: LISTENER_DOCKER_INTERNAL:PLAINTEXT,LISTENER_DOCKER_EXTERNAL:PLAINTEXT 41 | KAFKA_INTER_BROKER_LISTENER_NAME: LISTENER_DOCKER_INTERNAL 42 | KAFKA_ZOOKEEPER_CONNECT: "zoo:2181" 43 | KAFKA_BROKER_ID: 2 44 | KAFKA_LOG4J_LOGGERS: "kafka.controller=INFO,kafka.producer.async.DefaultEventHandler=INFO,state.change.logger=INFO" 45 | volumes: 46 | - ./zk-single-kafka-multiple/kafka2/data:/var/lib/kafka/data 47 | depends_on: 48 | - zoo 49 | kafka3: 50 | image: confluentinc/cp-kafka:5.3.0 51 | hostname: kafka3 52 | ports: 53 | - "9094:9094" 54 | environment: 55 | KAFKA_ADVERTISED_LISTENERS: LISTENER_DOCKER_INTERNAL://kafka3:19094,LISTENER_DOCKER_EXTERNAL://${DOCKER_HOST_IP:-127.0.0.1}:9094 56 | KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: LISTENER_DOCKER_INTERNAL:PLAINTEXT,LISTENER_DOCKER_EXTERNAL:PLAINTEXT 57 | KAFKA_INTER_BROKER_LISTENER_NAME: LISTENER_DOCKER_INTERNAL 58 | KAFKA_ZOOKEEPER_CONNECT: "zoo:2181" 59 | KAFKA_BROKER_ID: 3 60 | KAFKA_LOG4J_LOGGERS: "kafka.controller=INFO,kafka.producer.async.DefaultEventHandler=INFO,state.change.logger=INFO" 61 | volumes: 62 | - ./zk-single-kafka-multiple/kafka3/data:/var/lib/kafka/data 63 | depends_on: 64 | - zoo 65 | manager: 66 | image: sheepkiller/kafka-manager 67 | ports: 68 | - 9000:9000 69 | environment: 70 | - ZK_HOSTS=zoo:2181 71 | depends_on: 72 | - zoo 73 | -------------------------------------------------------------------------------- /order-service/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /payment-service/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /order-service/src/main/java/payment/saga/order/service/OrderService.java: -------------------------------------------------------------------------------- 1 | package payment.saga.order.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.web.server.ResponseStatusException; 7 | import payment.saga.order.enums.OrderStatus; 8 | import payment.saga.order.model.Order; 9 | import payment.saga.order.model.OrderPurchase; 10 | import payment.saga.order.processor.OrderPurchaseProcessor; 11 | import payment.saga.order.repository.OrderPurchaseRepository; 12 | import payment.saga.order.repository.ProductRepository; 13 | import reactor.core.publisher.Flux; 14 | import reactor.core.publisher.Mono; 15 | import reactor.core.scheduler.Scheduler; 16 | import reactor.util.function.Tuple2; 17 | 18 | import java.time.Duration; 19 | import java.util.List; 20 | import java.util.stream.Stream; 21 | 22 | @Service 23 | public class OrderService { 24 | 25 | private final OrderPurchaseRepository orderPurchaseRepository; 26 | private final OrderPurchaseProcessor orderPurchaseProcessor; 27 | private final ProductRepository productRepository; 28 | private final Scheduler jdbcScheduler; 29 | 30 | @Autowired 31 | public OrderService( 32 | OrderPurchaseRepository orderPurchaseRepository, 33 | OrderPurchaseProcessor orderPurchaseProcessor, 34 | ProductRepository productRepository, Scheduler jdbcScheduler) { 35 | this.orderPurchaseRepository = orderPurchaseRepository; 36 | this.orderPurchaseProcessor = orderPurchaseProcessor; 37 | this.productRepository = productRepository; 38 | this.jdbcScheduler = jdbcScheduler; 39 | } 40 | 41 | public Mono createOrder(Order order) { 42 | OrderPurchase orderPurchase = getOrderPurchase(order); 43 | OrderPurchase savedOrderPurchase = orderPurchaseRepository.save(orderPurchase); 44 | orderPurchaseProcessor.process(orderPurchase); 45 | return Mono.just(savedOrderPurchase); 46 | } 47 | 48 | public Flux getAll() { 49 | return Flux.defer( 50 | () -> Flux.fromIterable(orderPurchaseRepository.findAll())) 51 | .subscribeOn(jdbcScheduler); 52 | } 53 | 54 | public Flux> reactiveGetAll() { 55 | Flux interval = Flux.interval(Duration.ofMillis(2000)); 56 | Flux> orderPurchaseFlux = Flux.fromStream( 57 | Stream.generate(orderPurchaseRepository::findAll)); 58 | return Flux.zip(interval, orderPurchaseFlux) 59 | .map(Tuple2::getT2); 60 | } 61 | 62 | public Mono getOrderById(Integer id) { 63 | return Mono.fromCallable( 64 | () -> orderPurchaseRepository.findById(id) 65 | .orElseThrow(() -> new ResponseStatusException( 66 | HttpStatus.NOT_FOUND, "Order id: " + id + " does not exist"))) 67 | .subscribeOn(jdbcScheduler); 68 | } 69 | 70 | private OrderPurchase getOrderPurchase(final Order order) { 71 | Integer productId = order.getProductId(); 72 | return new OrderPurchase() 73 | .setProductId(productId) 74 | .setUserId(order.getUserId()) 75 | .setPrice(productRepository.findById(productId) 76 | .orElseThrow(() -> new ResponseStatusException( 77 | HttpStatus.NOT_FOUND, "Product ID: " + productId + " does not exist")) 78 | .getPrice()) 79 | .setStatus(OrderStatus.CREATED); 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /order-service/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /payment-service/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------