Merge remote-tracking branch 'origin/PR-7145' into PR-7145
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
## Axon
|
||||
|
||||
This module contains articles about Axon
|
||||
|
||||
## Profiles
|
||||
|
||||
Optionally the code can be run with the 'mongo' profile to use Mongo to store the projection. Otherwise, an in-memory
|
||||
projection is used.
|
||||
|
||||
## Scripts
|
||||
|
||||
Two scripts are included to easily start middleware using Docker matching the properties files:
|
||||
|
||||
- `start_axon_server.sh` to start an Axon Server instance
|
||||
- `start_mongo.sh` to start a MongoDB instance
|
||||
|
||||
### Relevant articles
|
||||
|
||||
- [A Guide to the Axon Framework](https://www.baeldung.com/axon-cqrs-event-sourcing)
|
||||
- [Multi-Entity Aggregates in Axon](https://www.baeldung.com/java-axon-multi-entity-aggregates)
|
||||
- [Snapshotting Aggregates in Axon](https://www.baeldung.com/axon-snapshotting-aggregates)
|
||||
- [Dispatching Queries in Axon Framework](https://www.baeldung.com/axon-query-dispatching)
|
||||
- [Persisting the Query Model](https://www.baeldung.com/axon-persisting-query-model)
|
||||
- [Using and Testing Axon Applications via REST](https://www.baeldung.com/axon-using-and-testing-rest)
|
||||
@@ -0,0 +1,119 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>axon</artifactId>
|
||||
<name>axon</name>
|
||||
<description>Basic Axon Framework with Spring Boot configuration tutorial</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.axonframework</groupId>
|
||||
<artifactId>axon-bom</artifactId>
|
||||
<version>${axon-bom.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.axonframework</groupId>
|
||||
<artifactId>axon-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-autoconfigure</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.axonframework.extensions.mongo</groupId>
|
||||
<artifactId>axon-mongo</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.axonframework</groupId>
|
||||
<artifactId>axon-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.flapdoodle.embed</groupId>
|
||||
<artifactId>de.flapdoodle.embed.mongo</artifactId>
|
||||
<version>${de.flapdoodle.embed.mongo.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webflux</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.projectreactor.netty</groupId>
|
||||
<artifactId>reactor-netty-http</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>
|
||||
--add-opens java.base/java.util=ALL-UNNAMED
|
||||
--add-opens
|
||||
java.base/java.util.concurrent=ALL-UNNAMED
|
||||
</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<axon-bom.version>4.6.3</axon-bom.version>
|
||||
<de.flapdoodle.embed.mongo.version>3.4.8</de.flapdoodle.embed.mongo.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.axon;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class OrderApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(OrderApplication.class, args);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.axon;
|
||||
|
||||
import org.axonframework.eventsourcing.EventCountSnapshotTriggerDefinition;
|
||||
import org.axonframework.eventsourcing.SnapshotTriggerDefinition;
|
||||
import org.axonframework.eventsourcing.Snapshotter;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class OrderApplicationConfiguration {
|
||||
|
||||
@Bean
|
||||
public SnapshotTriggerDefinition orderAggregateSnapshotTriggerDefinition(Snapshotter snapshotter, @Value("${axon.aggregate.order.snapshot-threshold:250}") int threshold) {
|
||||
return new EventCountSnapshotTriggerDefinition(snapshotter, threshold);
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.baeldung.axon.commandmodel.order;
|
||||
|
||||
import com.baeldung.axon.coreapi.commands.AddProductCommand;
|
||||
import com.baeldung.axon.coreapi.commands.ConfirmOrderCommand;
|
||||
import com.baeldung.axon.coreapi.commands.CreateOrderCommand;
|
||||
import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
|
||||
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
|
||||
import com.baeldung.axon.coreapi.events.OrderCreatedEvent;
|
||||
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductAddedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductRemovedEvent;
|
||||
import com.baeldung.axon.coreapi.exceptions.DuplicateOrderLineException;
|
||||
import com.baeldung.axon.coreapi.exceptions.OrderAlreadyConfirmedException;
|
||||
import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
|
||||
|
||||
import org.axonframework.commandhandling.CommandHandler;
|
||||
import org.axonframework.eventsourcing.EventSourcingHandler;
|
||||
import org.axonframework.modelling.command.AggregateIdentifier;
|
||||
import org.axonframework.modelling.command.AggregateMember;
|
||||
import org.axonframework.spring.stereotype.Aggregate;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.axonframework.modelling.command.AggregateLifecycle.apply;
|
||||
|
||||
@Aggregate(snapshotTriggerDefinition = "orderAggregateSnapshotTriggerDefinition")
|
||||
public class OrderAggregate {
|
||||
|
||||
@AggregateIdentifier
|
||||
private String orderId;
|
||||
private boolean orderConfirmed;
|
||||
|
||||
@AggregateMember
|
||||
private Map<String, OrderLine> orderLines;
|
||||
|
||||
@CommandHandler
|
||||
public OrderAggregate(CreateOrderCommand command) {
|
||||
apply(new OrderCreatedEvent(command.getOrderId()));
|
||||
}
|
||||
|
||||
@CommandHandler
|
||||
public void handle(AddProductCommand command) {
|
||||
if (orderConfirmed) {
|
||||
throw new OrderAlreadyConfirmedException(orderId);
|
||||
}
|
||||
|
||||
String productId = command.getProductId();
|
||||
if (orderLines.containsKey(productId)) {
|
||||
throw new DuplicateOrderLineException(productId);
|
||||
}
|
||||
apply(new ProductAddedEvent(orderId, productId));
|
||||
}
|
||||
|
||||
@CommandHandler
|
||||
public void handle(ConfirmOrderCommand command) {
|
||||
if (orderConfirmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
apply(new OrderConfirmedEvent(orderId));
|
||||
}
|
||||
|
||||
@CommandHandler
|
||||
public void handle(ShipOrderCommand command) {
|
||||
if (!orderConfirmed) {
|
||||
throw new UnconfirmedOrderException();
|
||||
}
|
||||
|
||||
apply(new OrderShippedEvent(orderId));
|
||||
}
|
||||
|
||||
@EventSourcingHandler
|
||||
public void on(OrderCreatedEvent event) {
|
||||
this.orderId = event.getOrderId();
|
||||
this.orderConfirmed = false;
|
||||
this.orderLines = new HashMap<>();
|
||||
}
|
||||
|
||||
@EventSourcingHandler
|
||||
public void on(OrderConfirmedEvent event) {
|
||||
this.orderConfirmed = true;
|
||||
}
|
||||
|
||||
@EventSourcingHandler
|
||||
public void on(ProductAddedEvent event) {
|
||||
String productId = event.getProductId();
|
||||
this.orderLines.put(productId, new OrderLine(productId));
|
||||
}
|
||||
|
||||
@EventSourcingHandler
|
||||
public void on(ProductRemovedEvent event) {
|
||||
this.orderLines.remove(event.getProductId());
|
||||
}
|
||||
|
||||
protected OrderAggregate() {
|
||||
// Required by Axon to build a default Aggregate prior to Event Sourcing
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package com.baeldung.axon.commandmodel.order;
|
||||
|
||||
import com.baeldung.axon.coreapi.commands.DecrementProductCountCommand;
|
||||
import com.baeldung.axon.coreapi.commands.IncrementProductCountCommand;
|
||||
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountDecrementedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountIncrementedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductRemovedEvent;
|
||||
import com.baeldung.axon.coreapi.exceptions.OrderAlreadyConfirmedException;
|
||||
|
||||
import org.axonframework.commandhandling.CommandHandler;
|
||||
import org.axonframework.eventsourcing.EventSourcingHandler;
|
||||
import org.axonframework.modelling.command.EntityId;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.axonframework.modelling.command.AggregateLifecycle.apply;
|
||||
|
||||
public class OrderLine {
|
||||
|
||||
@EntityId
|
||||
private final String productId;
|
||||
private Integer count;
|
||||
private boolean orderConfirmed;
|
||||
|
||||
public OrderLine(String productId) {
|
||||
this.productId = productId;
|
||||
this.count = 1;
|
||||
}
|
||||
|
||||
@CommandHandler
|
||||
public void handle(IncrementProductCountCommand command) {
|
||||
if (orderConfirmed) {
|
||||
throw new OrderAlreadyConfirmedException(command.getOrderId());
|
||||
}
|
||||
|
||||
apply(new ProductCountIncrementedEvent(command.getOrderId(), productId));
|
||||
}
|
||||
|
||||
@CommandHandler
|
||||
public void handle(DecrementProductCountCommand command) {
|
||||
if (orderConfirmed) {
|
||||
throw new OrderAlreadyConfirmedException(command.getOrderId());
|
||||
}
|
||||
|
||||
if (count <= 1) {
|
||||
apply(new ProductRemovedEvent(command.getOrderId(), productId));
|
||||
} else {
|
||||
apply(new ProductCountDecrementedEvent(command.getOrderId(), productId));
|
||||
}
|
||||
}
|
||||
|
||||
@EventSourcingHandler
|
||||
public void on(ProductCountIncrementedEvent event) {
|
||||
this.count++;
|
||||
}
|
||||
|
||||
@EventSourcingHandler
|
||||
public void on(ProductCountDecrementedEvent event) {
|
||||
this.count--;
|
||||
}
|
||||
|
||||
@EventSourcingHandler
|
||||
public void on(OrderConfirmedEvent event) {
|
||||
this.orderConfirmed = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
OrderLine orderLine = (OrderLine) o;
|
||||
return Objects.equals(productId, orderLine.productId) && Objects.equals(count, orderLine.count);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(productId, count);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.axon.coreapi.commands;
|
||||
|
||||
import org.axonframework.modelling.command.TargetAggregateIdentifier;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class AddProductCommand {
|
||||
|
||||
@TargetAggregateIdentifier
|
||||
private final String orderId;
|
||||
private final String productId;
|
||||
|
||||
public AddProductCommand(String orderId, String productId) {
|
||||
this.orderId = orderId;
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public String getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
AddProductCommand that = (AddProductCommand) o;
|
||||
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId, productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "AddProductCommand{" + "orderId='" + orderId + '\'' + ", productId='" + productId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.axon.coreapi.commands;
|
||||
|
||||
import org.axonframework.modelling.command.TargetAggregateIdentifier;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class ConfirmOrderCommand {
|
||||
|
||||
@TargetAggregateIdentifier
|
||||
private final String orderId;
|
||||
|
||||
public ConfirmOrderCommand(String orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null || getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
final ConfirmOrderCommand other = (ConfirmOrderCommand) obj;
|
||||
return Objects.equals(this.orderId, other.orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ConfirmOrderCommand{" + "orderId='" + orderId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.axon.coreapi.commands;
|
||||
|
||||
import org.axonframework.modelling.command.TargetAggregateIdentifier;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class CreateOrderCommand {
|
||||
|
||||
@TargetAggregateIdentifier
|
||||
private final String orderId;
|
||||
|
||||
public CreateOrderCommand(String orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
CreateOrderCommand that = (CreateOrderCommand) o;
|
||||
return Objects.equals(orderId, that.orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CreateOrderCommand{" + "orderId='" + orderId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.axon.coreapi.commands;
|
||||
|
||||
import org.axonframework.modelling.command.TargetAggregateIdentifier;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class DecrementProductCountCommand {
|
||||
|
||||
@TargetAggregateIdentifier
|
||||
private final String orderId;
|
||||
private final String productId;
|
||||
|
||||
public DecrementProductCountCommand(String orderId, String productId) {
|
||||
this.orderId = orderId;
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public String getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
DecrementProductCountCommand that = (DecrementProductCountCommand) o;
|
||||
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId, productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DecrementProductCountCommand{" + "orderId='" + orderId + '\'' + ", productId='" + productId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.axon.coreapi.commands;
|
||||
|
||||
import org.axonframework.modelling.command.TargetAggregateIdentifier;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class IncrementProductCountCommand {
|
||||
|
||||
@TargetAggregateIdentifier
|
||||
private final String orderId;
|
||||
private final String productId;
|
||||
|
||||
public IncrementProductCountCommand(String orderId, String productId) {
|
||||
this.orderId = orderId;
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public String getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
IncrementProductCountCommand that = (IncrementProductCountCommand) o;
|
||||
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId, productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "IncrementProductCountCommand{" + "orderId='" + orderId + '\'' + ", productId='" + productId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.axon.coreapi.commands;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import org.axonframework.modelling.command.TargetAggregateIdentifier;
|
||||
|
||||
public class ShipOrderCommand {
|
||||
|
||||
@TargetAggregateIdentifier
|
||||
private final String orderId;
|
||||
|
||||
public ShipOrderCommand(String orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null || getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
final ShipOrderCommand other = (ShipOrderCommand) obj;
|
||||
return Objects.equals(this.orderId, other.orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ShipOrderCommand{" + "orderId='" + orderId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.axon.coreapi.events;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class OrderConfirmedEvent {
|
||||
|
||||
private final String orderId;
|
||||
|
||||
public OrderConfirmedEvent(String orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null || getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
final OrderConfirmedEvent other = (OrderConfirmedEvent) obj;
|
||||
return Objects.equals(this.orderId, other.orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "OrderConfirmedEvent{" + "orderId='" + orderId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.axon.coreapi.events;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class OrderCreatedEvent {
|
||||
|
||||
private final String orderId;
|
||||
|
||||
public OrderCreatedEvent(String orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
OrderCreatedEvent that = (OrderCreatedEvent) o;
|
||||
return Objects.equals(orderId, that.orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "OrderCreatedEvent{" + "orderId='" + orderId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.axon.coreapi.events;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class OrderShippedEvent {
|
||||
|
||||
private final String orderId;
|
||||
|
||||
public OrderShippedEvent(String orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null || getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
final OrderShippedEvent other = (OrderShippedEvent) obj;
|
||||
return Objects.equals(this.orderId, other.orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "OrderShippedEvent{" + "orderId='" + orderId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.axon.coreapi.events;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class ProductAddedEvent {
|
||||
|
||||
private final String orderId;
|
||||
private final String productId;
|
||||
|
||||
public ProductAddedEvent(String orderId, String productId) {
|
||||
this.orderId = orderId;
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public String getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
ProductAddedEvent that = (ProductAddedEvent) o;
|
||||
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId, productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ProductAddedEvent{" + "orderId='" + orderId + '\'' + ", productId='" + productId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.axon.coreapi.events;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class ProductCountDecrementedEvent {
|
||||
|
||||
private final String orderId;
|
||||
private final String productId;
|
||||
|
||||
public ProductCountDecrementedEvent(String orderId, String productId) {
|
||||
this.orderId = orderId;
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public String getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
ProductCountDecrementedEvent that = (ProductCountDecrementedEvent) o;
|
||||
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId, productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ProductCountDecrementedEvent{" + "orderId='" + orderId + '\'' + ", productId='" + productId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.axon.coreapi.events;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class ProductCountIncrementedEvent {
|
||||
|
||||
private final String orderId;
|
||||
private final String productId;
|
||||
|
||||
public ProductCountIncrementedEvent(String orderId, String productId) {
|
||||
this.orderId = orderId;
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public String getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
ProductCountIncrementedEvent that = (ProductCountIncrementedEvent) o;
|
||||
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId, productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ProductCountIncrementedEvent{" + "orderId='" + orderId + '\'' + ", productId='" + productId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.axon.coreapi.events;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class ProductRemovedEvent {
|
||||
|
||||
private final String orderId;
|
||||
private final String productId;
|
||||
|
||||
public ProductRemovedEvent(String orderId, String productId) {
|
||||
this.orderId = orderId;
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public String getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
ProductRemovedEvent that = (ProductRemovedEvent) o;
|
||||
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId, productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ProductRemovedEvent{" + "orderId='" + orderId + '\'' + ", productId='" + productId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.axon.coreapi.exceptions;
|
||||
|
||||
public class DuplicateOrderLineException extends IllegalStateException {
|
||||
|
||||
public DuplicateOrderLineException(String productId) {
|
||||
super("Cannot duplicate order line for product identifier [" + productId + "]");
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.axon.coreapi.exceptions;
|
||||
|
||||
public class OrderAlreadyConfirmedException extends IllegalStateException {
|
||||
|
||||
public OrderAlreadyConfirmedException(String orderId) {
|
||||
super("Cannot perform operation because order [" + orderId + "] is already confirmed.");
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.axon.coreapi.exceptions;
|
||||
|
||||
public class UnconfirmedOrderException extends IllegalStateException {
|
||||
|
||||
public UnconfirmedOrderException() {
|
||||
super("Cannot ship an order which has not been confirmed yet.");
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.axon.coreapi.queries;
|
||||
|
||||
public class FindAllOrderedProductsQuery {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.axon.coreapi.queries;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public class Order {
|
||||
|
||||
private final String orderId;
|
||||
private final Map<String, Integer> products;
|
||||
private OrderStatus orderStatus;
|
||||
|
||||
public Order(String orderId) {
|
||||
this.orderId = orderId;
|
||||
this.products = new HashMap<>();
|
||||
orderStatus = OrderStatus.CREATED;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getProducts() {
|
||||
return products;
|
||||
}
|
||||
|
||||
public OrderStatus getOrderStatus() {
|
||||
return orderStatus;
|
||||
}
|
||||
|
||||
public void addProduct(String productId) {
|
||||
products.putIfAbsent(productId, 1);
|
||||
}
|
||||
|
||||
public void incrementProductInstance(String productId) {
|
||||
products.computeIfPresent(productId, (id, count) -> ++count);
|
||||
}
|
||||
|
||||
public void decrementProductInstance(String productId) {
|
||||
products.computeIfPresent(productId, (id, count) -> --count);
|
||||
}
|
||||
|
||||
public void removeProduct(String productId) {
|
||||
products.remove(productId);
|
||||
}
|
||||
|
||||
public void setOrderConfirmed() {
|
||||
this.orderStatus = OrderStatus.CONFIRMED;
|
||||
}
|
||||
|
||||
public void setOrderShipped() {
|
||||
this.orderStatus = OrderStatus.SHIPPED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
Order that = (Order) o;
|
||||
return Objects.equals(orderId, that.orderId) && Objects.equals(products, that.products) && orderStatus == that.orderStatus;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId, products, orderStatus);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Order{" + "orderId='" + orderId + '\'' + ", products=" + products + ", orderStatus=" + orderStatus + '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.axon.coreapi.queries;
|
||||
|
||||
public enum OrderStatus {
|
||||
|
||||
CREATED, CONFIRMED, SHIPPED
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.axon.coreapi.queries;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class OrderUpdatesQuery {
|
||||
|
||||
private final String orderId;
|
||||
|
||||
public OrderUpdatesQuery(String orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
OrderUpdatesQuery that = (OrderUpdatesQuery) o;
|
||||
return Objects.equals(orderId, that.orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "OrderUpdatesQuery{" + "orderId='" + orderId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.axon.coreapi.queries;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class TotalProductsShippedQuery {
|
||||
|
||||
private final String productId;
|
||||
|
||||
public TotalProductsShippedQuery(String productId) {
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public String getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
TotalProductsShippedQuery that = (TotalProductsShippedQuery) o;
|
||||
return Objects.equals(productId, that.productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "TotalProductsShippedQuery{" + "productId='" + productId + '\'' + '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.baeldung.axon.gui;
|
||||
|
||||
import com.baeldung.axon.coreapi.commands.AddProductCommand;
|
||||
import com.baeldung.axon.coreapi.commands.ConfirmOrderCommand;
|
||||
import com.baeldung.axon.coreapi.commands.CreateOrderCommand;
|
||||
import com.baeldung.axon.coreapi.commands.DecrementProductCountCommand;
|
||||
import com.baeldung.axon.coreapi.commands.IncrementProductCountCommand;
|
||||
import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
|
||||
import com.baeldung.axon.querymodel.OrderQueryService;
|
||||
import com.baeldung.axon.querymodel.OrderResponse;
|
||||
|
||||
import org.axonframework.commandhandling.gateway.CommandGateway;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@RestController
|
||||
public class OrderRestEndpoint {
|
||||
|
||||
private final CommandGateway commandGateway;
|
||||
private final OrderQueryService orderQueryService;
|
||||
|
||||
public OrderRestEndpoint(CommandGateway commandGateway, OrderQueryService orderQueryService) {
|
||||
this.commandGateway = commandGateway;
|
||||
this.orderQueryService = orderQueryService;
|
||||
}
|
||||
|
||||
@PostMapping("/ship-order")
|
||||
public CompletableFuture<Void> shipOrder() {
|
||||
String orderId = UUID.randomUUID()
|
||||
.toString();
|
||||
return commandGateway.send(new CreateOrderCommand(orderId))
|
||||
.thenCompose(result -> commandGateway.send(new AddProductCommand(orderId, "Deluxe Chair")))
|
||||
.thenCompose(result -> commandGateway.send(new ConfirmOrderCommand(orderId)))
|
||||
.thenCompose(result -> commandGateway.send(new ShipOrderCommand(orderId)));
|
||||
}
|
||||
|
||||
@PostMapping("/ship-unconfirmed-order")
|
||||
public CompletableFuture<Void> shipUnconfirmedOrder() {
|
||||
String orderId = UUID.randomUUID()
|
||||
.toString();
|
||||
return commandGateway.send(new CreateOrderCommand(orderId))
|
||||
.thenCompose(result -> commandGateway.send(new AddProductCommand(orderId, "Deluxe Chair")))
|
||||
// This throws an exception, as an Order cannot be shipped if it has not been confirmed yet.
|
||||
.thenCompose(result -> commandGateway.send(new ShipOrderCommand(orderId)));
|
||||
}
|
||||
|
||||
@PostMapping("/order")
|
||||
public CompletableFuture<String> createOrder() {
|
||||
return createOrder(UUID.randomUUID()
|
||||
.toString());
|
||||
}
|
||||
|
||||
@PostMapping("/order/{order-id}")
|
||||
public CompletableFuture<String> createOrder(@PathVariable("order-id") String orderId) {
|
||||
return commandGateway.send(new CreateOrderCommand(orderId));
|
||||
}
|
||||
|
||||
@PostMapping("/order/{order-id}/product/{product-id}")
|
||||
public CompletableFuture<Void> addProduct(@PathVariable("order-id") String orderId, @PathVariable("product-id") String productId) {
|
||||
return commandGateway.send(new AddProductCommand(orderId, productId));
|
||||
}
|
||||
|
||||
@PostMapping("/order/{order-id}/product/{product-id}/increment")
|
||||
public CompletableFuture<Void> incrementProduct(@PathVariable("order-id") String orderId, @PathVariable("product-id") String productId) {
|
||||
return commandGateway.send(new IncrementProductCountCommand(orderId, productId));
|
||||
}
|
||||
|
||||
@PostMapping("/order/{order-id}/product/{product-id}/decrement")
|
||||
public CompletableFuture<Void> decrementProduct(@PathVariable("order-id") String orderId, @PathVariable("product-id") String productId) {
|
||||
return commandGateway.send(new DecrementProductCountCommand(orderId, productId));
|
||||
}
|
||||
|
||||
@PostMapping("/order/{order-id}/confirm")
|
||||
public CompletableFuture<Void> confirmOrder(@PathVariable("order-id") String orderId) {
|
||||
return commandGateway.send(new ConfirmOrderCommand(orderId));
|
||||
}
|
||||
|
||||
@PostMapping("/order/{order-id}/ship")
|
||||
public CompletableFuture<Void> shipOrder(@PathVariable("order-id") String orderId) {
|
||||
return commandGateway.send(new ShipOrderCommand(orderId));
|
||||
}
|
||||
|
||||
@GetMapping("/all-orders")
|
||||
public CompletableFuture<List<OrderResponse>> findAllOrders() {
|
||||
return orderQueryService.findAllOrders();
|
||||
}
|
||||
|
||||
@GetMapping(path = "/all-orders-streaming", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public Flux<OrderResponse> allOrdersStreaming() {
|
||||
return orderQueryService.allOrdersStreaming();
|
||||
}
|
||||
|
||||
@GetMapping("/total-shipped/{product-id}")
|
||||
public Integer totalShipped(@PathVariable("product-id") String productId) {
|
||||
return orderQueryService.totalShipped(productId);
|
||||
}
|
||||
|
||||
@GetMapping(path = "/order-updates/{order-id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public Flux<OrderResponse> orderUpdates(@PathVariable("order-id") String orderId) {
|
||||
return orderQueryService.orderUpdates(orderId);
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
package com.baeldung.axon.querymodel;
|
||||
|
||||
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
|
||||
import com.baeldung.axon.coreapi.events.OrderCreatedEvent;
|
||||
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductAddedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountDecrementedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountIncrementedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductRemovedEvent;
|
||||
import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
|
||||
import com.baeldung.axon.coreapi.queries.Order;
|
||||
import com.baeldung.axon.coreapi.queries.OrderStatus;
|
||||
import com.baeldung.axon.coreapi.queries.OrderUpdatesQuery;
|
||||
import com.baeldung.axon.coreapi.queries.TotalProductsShippedQuery;
|
||||
|
||||
import org.axonframework.config.ProcessingGroup;
|
||||
import org.axonframework.eventhandling.EventHandler;
|
||||
import org.axonframework.queryhandling.QueryHandler;
|
||||
import org.axonframework.queryhandling.QueryUpdateEmitter;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@ProcessingGroup("orders")
|
||||
@Profile("!mongo")
|
||||
public class InMemoryOrdersEventHandler implements OrdersEventHandler {
|
||||
|
||||
private final Map<String, Order> orders = new HashMap<>();
|
||||
private final QueryUpdateEmitter emitter;
|
||||
|
||||
public InMemoryOrdersEventHandler(QueryUpdateEmitter emitter) {
|
||||
this.emitter = emitter;
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(OrderCreatedEvent event) {
|
||||
String orderId = event.getOrderId();
|
||||
orders.put(orderId, new Order(orderId));
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(ProductAddedEvent event) {
|
||||
orders.computeIfPresent(event.getOrderId(), (orderId, order) -> {
|
||||
order.addProduct(event.getProductId());
|
||||
emitUpdate(order);
|
||||
return order;
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(ProductCountIncrementedEvent event) {
|
||||
orders.computeIfPresent(event.getOrderId(), (orderId, order) -> {
|
||||
order.incrementProductInstance(event.getProductId());
|
||||
emitUpdate(order);
|
||||
return order;
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(ProductCountDecrementedEvent event) {
|
||||
orders.computeIfPresent(event.getOrderId(), (orderId, order) -> {
|
||||
order.decrementProductInstance(event.getProductId());
|
||||
emitUpdate(order);
|
||||
return order;
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(ProductRemovedEvent event) {
|
||||
orders.computeIfPresent(event.getOrderId(), (orderId, order) -> {
|
||||
order.removeProduct(event.getProductId());
|
||||
emitUpdate(order);
|
||||
return order;
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(OrderConfirmedEvent event) {
|
||||
orders.computeIfPresent(event.getOrderId(), (orderId, order) -> {
|
||||
order.setOrderConfirmed();
|
||||
emitUpdate(order);
|
||||
return order;
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(OrderShippedEvent event) {
|
||||
orders.computeIfPresent(event.getOrderId(), (orderId, order) -> {
|
||||
order.setOrderShipped();
|
||||
emitUpdate(order);
|
||||
return order;
|
||||
});
|
||||
}
|
||||
|
||||
@QueryHandler
|
||||
public List<Order> handle(FindAllOrderedProductsQuery query) {
|
||||
return new ArrayList<>(orders.values());
|
||||
}
|
||||
|
||||
@QueryHandler
|
||||
public Publisher<Order> handleStreaming(FindAllOrderedProductsQuery query) {
|
||||
return Mono.fromCallable(orders::values)
|
||||
.flatMapMany(Flux::fromIterable);
|
||||
}
|
||||
|
||||
@QueryHandler
|
||||
public Integer handle(TotalProductsShippedQuery query) {
|
||||
return orders.values()
|
||||
.stream()
|
||||
.filter(o -> o.getOrderStatus() == OrderStatus.SHIPPED)
|
||||
.map(o -> Optional.ofNullable(o.getProducts()
|
||||
.get(query.getProductId()))
|
||||
.orElse(0))
|
||||
.reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
@QueryHandler
|
||||
public Order handle(OrderUpdatesQuery query) {
|
||||
return orders.get(query.getOrderId());
|
||||
}
|
||||
|
||||
private void emitUpdate(Order order) {
|
||||
emitter.emit(OrderUpdatesQuery.class, q -> order.getOrderId()
|
||||
.equals(q.getOrderId()), order);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset(List<Order> orderList) {
|
||||
orders.clear();
|
||||
orderList.forEach(o -> orders.put(o.getOrderId(), o));
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.axon.querymodel;
|
||||
|
||||
import com.baeldung.axon.coreapi.queries.TotalProductsShippedQuery;
|
||||
|
||||
import org.axonframework.queryhandling.QueryHandler;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class LegacyQueryHandler {
|
||||
|
||||
@QueryHandler
|
||||
public Integer handle(TotalProductsShippedQuery query) {
|
||||
switch (query.getProductId()) {
|
||||
case "Deluxe Chair":
|
||||
return 234;
|
||||
case "a6aa01eb-4e38-4dfb-b53b-b5b82961fbf3":
|
||||
return 10;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.axon.querymodel;
|
||||
|
||||
import com.mongodb.client.MongoClient;
|
||||
|
||||
import org.axonframework.eventhandling.tokenstore.TokenStore;
|
||||
import org.axonframework.extensions.mongo.DefaultMongoTemplate;
|
||||
import org.axonframework.extensions.mongo.eventsourcing.tokenstore.MongoTokenStore;
|
||||
import org.axonframework.serialization.Serializer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
@Configuration
|
||||
@Profile("mongo")
|
||||
public class MongoConfiguration {
|
||||
|
||||
@Bean
|
||||
public TokenStore getTokenStore(MongoClient client, Serializer serializer) {
|
||||
return MongoTokenStore.builder()
|
||||
.mongoTemplate(DefaultMongoTemplate.builder()
|
||||
.mongoDatabase(client)
|
||||
.build())
|
||||
.serializer(serializer)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
package com.baeldung.axon.querymodel;
|
||||
|
||||
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
|
||||
import com.baeldung.axon.coreapi.events.OrderCreatedEvent;
|
||||
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductAddedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountDecrementedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountIncrementedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductRemovedEvent;
|
||||
import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
|
||||
import com.baeldung.axon.coreapi.queries.Order;
|
||||
import com.baeldung.axon.coreapi.queries.OrderStatus;
|
||||
import com.baeldung.axon.coreapi.queries.OrderUpdatesQuery;
|
||||
import com.baeldung.axon.coreapi.queries.TotalProductsShippedQuery;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.model.IndexOptions;
|
||||
import com.mongodb.client.model.Indexes;
|
||||
import com.mongodb.client.result.UpdateResult;
|
||||
|
||||
import groovyjarjarantlr4.v4.runtime.misc.NotNull;
|
||||
|
||||
import org.axonframework.config.ProcessingGroup;
|
||||
import org.axonframework.eventhandling.EventHandler;
|
||||
import org.axonframework.queryhandling.QueryHandler;
|
||||
import org.axonframework.queryhandling.QueryUpdateEmitter;
|
||||
import org.bson.Document;
|
||||
import org.bson.conversions.Bson;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static com.mongodb.client.model.Filters.*;
|
||||
|
||||
@Service
|
||||
@ProcessingGroup("orders")
|
||||
@Profile("mongo")
|
||||
public class MongoOrdersEventHandler implements OrdersEventHandler {
|
||||
|
||||
static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup()
|
||||
.lookupClass());
|
||||
|
||||
private final MongoCollection<Document> orders;
|
||||
private final QueryUpdateEmitter emitter;
|
||||
private static final String ORDER_COLLECTION_NAME = "orders";
|
||||
private static final String AXON_FRAMEWORK_DATABASE_NAME = "axonframework";
|
||||
|
||||
private static final String ORDER_ID_PROPERTY_NAME = "orderId";
|
||||
private static final String PRODUCTS_PROPERTY_NAME = "products";
|
||||
private static final String ORDER_STATUS_PROPERTY_NAME = "orderStatus";
|
||||
|
||||
public MongoOrdersEventHandler(MongoClient client, QueryUpdateEmitter emitter) {
|
||||
orders = client.getDatabase(AXON_FRAMEWORK_DATABASE_NAME)
|
||||
.getCollection(ORDER_COLLECTION_NAME);
|
||||
orders.createIndex(Indexes.ascending(ORDER_ID_PROPERTY_NAME), new IndexOptions().unique(true));
|
||||
this.emitter = emitter;
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(OrderCreatedEvent event) {
|
||||
orders.insertOne(orderToDocument(new Order(event.getOrderId())));
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(ProductAddedEvent event) {
|
||||
update(event.getOrderId(), o -> o.addProduct(event.getProductId()));
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(ProductCountIncrementedEvent event) {
|
||||
update(event.getOrderId(), o -> o.incrementProductInstance(event.getProductId()));
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(ProductCountDecrementedEvent event) {
|
||||
update(event.getOrderId(), o -> o.decrementProductInstance(event.getProductId()));
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(ProductRemovedEvent event) {
|
||||
update(event.getOrderId(), o -> o.removeProduct(event.getProductId()));
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(OrderConfirmedEvent event) {
|
||||
update(event.getOrderId(), Order::setOrderConfirmed);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void on(OrderShippedEvent event) {
|
||||
update(event.getOrderId(), Order::setOrderShipped);
|
||||
}
|
||||
|
||||
@QueryHandler
|
||||
public List<Order> handle(FindAllOrderedProductsQuery query) {
|
||||
List<Order> orderList = new ArrayList<>();
|
||||
orders.find()
|
||||
.forEach(d -> orderList.add(documentToOrder(d)));
|
||||
return orderList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Publisher<Order> handleStreaming(FindAllOrderedProductsQuery query) {
|
||||
return Flux.fromIterable(orders.find())
|
||||
.map(this::documentToOrder);
|
||||
}
|
||||
|
||||
@QueryHandler
|
||||
public Integer handle(TotalProductsShippedQuery query) {
|
||||
AtomicInteger result = new AtomicInteger();
|
||||
orders.find(shippedProductFilter(query.getProductId()))
|
||||
.map(d -> d.get(PRODUCTS_PROPERTY_NAME, Document.class))
|
||||
.map(d -> d.getInteger(query.getProductId(), 0))
|
||||
.forEach(result::addAndGet);
|
||||
return result.get();
|
||||
}
|
||||
|
||||
@QueryHandler
|
||||
public Order handle(OrderUpdatesQuery query) {
|
||||
return getOrder(query.getOrderId()).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset(List<Order> orderList) {
|
||||
orders.deleteMany(new Document());
|
||||
orderList.forEach(o -> orders.insertOne(orderToDocument(o)));
|
||||
}
|
||||
|
||||
private Optional<Order> getOrder(String orderId) {
|
||||
return Optional.ofNullable(orders.find(eq(ORDER_ID_PROPERTY_NAME, orderId))
|
||||
.first())
|
||||
.map(this::documentToOrder);
|
||||
}
|
||||
|
||||
private Order emitUpdate(Order order) {
|
||||
emitter.emit(OrderUpdatesQuery.class, q -> order.getOrderId()
|
||||
.equals(q.getOrderId()), order);
|
||||
return order;
|
||||
}
|
||||
|
||||
private Order updateOrder(Order order, Consumer<Order> updateFunction) {
|
||||
updateFunction.accept(order);
|
||||
return order;
|
||||
}
|
||||
|
||||
private UpdateResult persistUpdate(Order order) {
|
||||
return orders.replaceOne(eq(ORDER_ID_PROPERTY_NAME, order.getOrderId()), orderToDocument(order));
|
||||
}
|
||||
|
||||
private void update(String orderId, Consumer<Order> updateFunction) {
|
||||
UpdateResult result = getOrder(orderId).map(o -> updateOrder(o, updateFunction))
|
||||
.map(this::emitUpdate)
|
||||
.map(this::persistUpdate)
|
||||
.orElse(null);
|
||||
logger.info("Result of updating order with orderId '{}': {}", orderId, result);
|
||||
}
|
||||
|
||||
private Document orderToDocument(Order order) {
|
||||
return new Document(ORDER_ID_PROPERTY_NAME, order.getOrderId()).append(PRODUCTS_PROPERTY_NAME, order.getProducts())
|
||||
.append(ORDER_STATUS_PROPERTY_NAME, order.getOrderStatus()
|
||||
.toString());
|
||||
}
|
||||
|
||||
private Order documentToOrder(@NotNull Document document) {
|
||||
Order order = new Order(document.getString(ORDER_ID_PROPERTY_NAME));
|
||||
Document products = document.get(PRODUCTS_PROPERTY_NAME, Document.class);
|
||||
products.forEach((k, v) -> order.getProducts()
|
||||
.put(k, (Integer) v));
|
||||
String status = document.getString(ORDER_STATUS_PROPERTY_NAME);
|
||||
if (OrderStatus.CONFIRMED.toString()
|
||||
.equals(status)) {
|
||||
order.setOrderConfirmed();
|
||||
} else if (OrderStatus.SHIPPED.toString()
|
||||
.equals(status)) {
|
||||
order.setOrderShipped();
|
||||
}
|
||||
return order;
|
||||
}
|
||||
|
||||
private Bson shippedProductFilter(String productId) {
|
||||
return and(eq(ORDER_STATUS_PROPERTY_NAME, OrderStatus.SHIPPED.toString()), exists(String.format(PRODUCTS_PROPERTY_NAME + ".%s", productId)));
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.axon.querymodel;
|
||||
|
||||
import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
|
||||
import com.baeldung.axon.coreapi.queries.Order;
|
||||
import com.baeldung.axon.coreapi.queries.OrderUpdatesQuery;
|
||||
import com.baeldung.axon.coreapi.queries.TotalProductsShippedQuery;
|
||||
|
||||
import org.axonframework.messaging.responsetypes.ResponseType;
|
||||
import org.axonframework.messaging.responsetypes.ResponseTypes;
|
||||
import org.axonframework.queryhandling.QueryGateway;
|
||||
import org.axonframework.queryhandling.SubscriptionQueryResult;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class OrderQueryService {
|
||||
|
||||
private final QueryGateway queryGateway;
|
||||
|
||||
public OrderQueryService(QueryGateway queryGateway) {
|
||||
this.queryGateway = queryGateway;
|
||||
}
|
||||
|
||||
public CompletableFuture<List<OrderResponse>> findAllOrders() {
|
||||
return queryGateway.query(new FindAllOrderedProductsQuery(), ResponseTypes.multipleInstancesOf(Order.class))
|
||||
.thenApply(r -> r.stream()
|
||||
.map(OrderResponse::new)
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
public Flux<OrderResponse> allOrdersStreaming() {
|
||||
Publisher<Order> publisher = queryGateway.streamingQuery(new FindAllOrderedProductsQuery(), Order.class);
|
||||
return Flux.from(publisher)
|
||||
.map(OrderResponse::new);
|
||||
}
|
||||
|
||||
public Integer totalShipped(String productId) {
|
||||
return queryGateway.scatterGather(new TotalProductsShippedQuery(productId), ResponseTypes.instanceOf(Integer.class), 10L, TimeUnit.SECONDS)
|
||||
.reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
public Flux<OrderResponse> orderUpdates(String orderId) {
|
||||
return subscriptionQuery(new OrderUpdatesQuery(orderId), ResponseTypes.instanceOf(Order.class)).map(OrderResponse::new);
|
||||
}
|
||||
|
||||
private <Q, R> Flux<R> subscriptionQuery(Q query, ResponseType<R> resultType) {
|
||||
SubscriptionQueryResult<R, R> result = queryGateway.subscriptionQuery(query, resultType, resultType);
|
||||
return result.initialResult()
|
||||
.concatWith(result.updates())
|
||||
.doFinally(signal -> result.close());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.axon.querymodel;
|
||||
|
||||
import com.baeldung.axon.coreapi.queries.Order;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static com.baeldung.axon.querymodel.OrderStatusResponse.toResponse;
|
||||
|
||||
public class OrderResponse {
|
||||
|
||||
private String orderId;
|
||||
private Map<String, Integer> products;
|
||||
private OrderStatusResponse orderStatus;
|
||||
|
||||
OrderResponse(Order order) {
|
||||
this.orderId = order.getOrderId();
|
||||
this.products = order.getProducts();
|
||||
this.orderStatus = toResponse(order.getOrderStatus());
|
||||
}
|
||||
|
||||
/**
|
||||
* Added for the integration test, since it's using Jackson for the response
|
||||
*/
|
||||
OrderResponse() {
|
||||
}
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getProducts() {
|
||||
return products;
|
||||
}
|
||||
|
||||
public OrderStatusResponse getOrderStatus() {
|
||||
return orderStatus;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.axon.querymodel;
|
||||
|
||||
import com.baeldung.axon.coreapi.queries.OrderStatus;
|
||||
|
||||
public enum OrderStatusResponse {
|
||||
CREATED, CONFIRMED, SHIPPED, UNKNOWN;
|
||||
|
||||
static OrderStatusResponse toResponse(OrderStatus status) {
|
||||
for (OrderStatusResponse response : values()) {
|
||||
if (response.toString()
|
||||
.equals(status.toString())) {
|
||||
return response;
|
||||
}
|
||||
}
|
||||
return UNKNOWN;
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.axon.querymodel;
|
||||
|
||||
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
|
||||
import com.baeldung.axon.coreapi.events.OrderCreatedEvent;
|
||||
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductAddedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountDecrementedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountIncrementedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductRemovedEvent;
|
||||
import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
|
||||
import com.baeldung.axon.coreapi.queries.Order;
|
||||
import com.baeldung.axon.coreapi.queries.OrderUpdatesQuery;
|
||||
import com.baeldung.axon.coreapi.queries.TotalProductsShippedQuery;
|
||||
|
||||
import org.reactivestreams.Publisher;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface OrdersEventHandler {
|
||||
|
||||
void on(OrderCreatedEvent event);
|
||||
|
||||
void on(ProductAddedEvent event);
|
||||
|
||||
void on(ProductCountIncrementedEvent event);
|
||||
|
||||
void on(ProductCountDecrementedEvent event);
|
||||
|
||||
void on(ProductRemovedEvent event);
|
||||
|
||||
void on(OrderConfirmedEvent event);
|
||||
|
||||
void on(OrderShippedEvent event);
|
||||
|
||||
List<Order> handle(FindAllOrderedProductsQuery query);
|
||||
|
||||
Publisher<Order> handleStreaming(FindAllOrderedProductsQuery query);
|
||||
|
||||
Integer handle(TotalProductsShippedQuery query);
|
||||
|
||||
Order handle(OrderUpdatesQuery query);
|
||||
|
||||
void reset(List<Order> orderList);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
spring.data.mongodb.host=localhost
|
||||
spring.data.mongodb.port=27017
|
||||
spring.data.mongodb.authentication-database=admin
|
||||
spring.data.mongodb.username=admin1234
|
||||
spring.data.mongodb.password=somepassword
|
||||
spring.data.mongodb.database=order-projection
|
||||
@@ -0,0 +1 @@
|
||||
spring.application.name=Order Management Service
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,53 @@
|
||||
### Create Order, Add Product, Confirm and Ship Order
|
||||
|
||||
POST http://localhost:8080/ship-order
|
||||
|
||||
### Create Order, Add Product and Ship Order
|
||||
|
||||
POST http://localhost:8080/ship-unconfirmed-order
|
||||
|
||||
### Retrieve all existing Orders
|
||||
|
||||
GET http://localhost:8080/all-orders
|
||||
|
||||
### Receive all existing orders using a stream
|
||||
|
||||
GET http://localhost:8080/all-orders-streaming
|
||||
|
||||
### Create Order with id 666a1661-474d-4046-8b12-8b5896312768
|
||||
|
||||
POST http://localhost:8080/order/666a1661-474d-4046-8b12-8b5896312768
|
||||
|
||||
### Add Product a6aa01eb-4e38-4dfb-b53b-b5b82961fbf3 to Order 666a1661-474d-4046-8b12-8b5896312768
|
||||
|
||||
POST http://localhost:8080/order/666a1661-474d-4046-8b12-8b5896312768/product/a6aa01eb-4e38-4dfb-b53b-b5b82961fbf3
|
||||
|
||||
### Increment Product a6aa01eb-4e38-4dfb-b53b-b5b82961fbf3 to Order 666a1661-474d-4046-8b12-8b5896312768
|
||||
|
||||
POST http://localhost:8080/order/666a1661-474d-4046-8b12-8b5896312768/product/a6aa01eb-4e38-4dfb-b53b-b5b82961fbf3/increment
|
||||
|
||||
### Decrement Product a6aa01eb-4e38-4dfb-b53b-b5b82961fbf3 to Order 666a1661-474d-4046-8b12-8b5896312768
|
||||
|
||||
POST http://localhost:8080/order/666a1661-474d-4046-8b12-8b5896312768/product/a6aa01eb-4e38-4dfb-b53b-b5b82961fbf3/decrement
|
||||
|
||||
### Confirm Order 666a1661-474d-4046-8b12-8b5896312768
|
||||
|
||||
POST http://localhost:8080/order/666a1661-474d-4046-8b12-8b5896312768/confirm
|
||||
|
||||
### Ship Order 666a1661-474d-4046-8b12-8b5896312768
|
||||
|
||||
POST http://localhost:8080/order/666a1661-474d-4046-8b12-8b5896312768/ship
|
||||
|
||||
### Retrieve shipped Deluxe Chairs
|
||||
|
||||
GET http://localhost:8080/total-shipped/Deluxe Chair
|
||||
|
||||
### Retrieve shipped a6aa01eb-4e38-4dfb-b53b-b5b82961fbf3
|
||||
|
||||
GET http://localhost:8080/total-shipped/a6aa01eb-4e38-4dfb-b53b-b5b82961fbf3
|
||||
|
||||
### Receive updates for 666a1661-474d-4046-8b12-8b5896312768
|
||||
|
||||
GET http://localhost:8080/order-updates/666a1661-474d-4046-8b12-8b5896312768
|
||||
|
||||
###
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
package com.baeldung.axon.commandmodel;
|
||||
|
||||
import com.baeldung.axon.commandmodel.order.OrderAggregate;
|
||||
import com.baeldung.axon.coreapi.commands.AddProductCommand;
|
||||
import com.baeldung.axon.coreapi.commands.ConfirmOrderCommand;
|
||||
import com.baeldung.axon.coreapi.commands.CreateOrderCommand;
|
||||
import com.baeldung.axon.coreapi.commands.DecrementProductCountCommand;
|
||||
import com.baeldung.axon.coreapi.commands.IncrementProductCountCommand;
|
||||
import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
|
||||
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
|
||||
import com.baeldung.axon.coreapi.events.OrderCreatedEvent;
|
||||
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductAddedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountDecrementedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountIncrementedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductRemovedEvent;
|
||||
import com.baeldung.axon.coreapi.exceptions.DuplicateOrderLineException;
|
||||
import com.baeldung.axon.coreapi.exceptions.OrderAlreadyConfirmedException;
|
||||
import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
|
||||
|
||||
import org.axonframework.test.aggregate.AggregateTestFixture;
|
||||
import org.axonframework.test.aggregate.FixtureConfiguration;
|
||||
import org.axonframework.test.matchers.Matchers;
|
||||
import org.junit.jupiter.api.*;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
class OrderAggregateUnitTest {
|
||||
|
||||
private static final String ORDER_ID = UUID.randomUUID()
|
||||
.toString();
|
||||
private static final String PRODUCT_ID = UUID.randomUUID()
|
||||
.toString();
|
||||
|
||||
private FixtureConfiguration<OrderAggregate> fixture;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
fixture = new AggregateTestFixture<>(OrderAggregate.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void giveNoPriorActivity_whenCreateOrderCommand_thenShouldPublishOrderCreatedEvent() {
|
||||
fixture.givenNoPriorActivity()
|
||||
.when(new CreateOrderCommand(ORDER_ID))
|
||||
.expectEvents(new OrderCreatedEvent(ORDER_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEvent_whenAddProductCommand_thenShouldPublishProductAddedEvent() {
|
||||
fixture.given(new OrderCreatedEvent(ORDER_ID))
|
||||
.when(new AddProductCommand(ORDER_ID, PRODUCT_ID))
|
||||
.expectEvents(new ProductAddedEvent(ORDER_ID, PRODUCT_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEventAndProductAddedEvent_whenAddProductCommandForSameProductId_thenShouldThrowDuplicateOrderLineException() {
|
||||
fixture.given(new OrderCreatedEvent(ORDER_ID), new ProductAddedEvent(ORDER_ID, PRODUCT_ID))
|
||||
.when(new AddProductCommand(ORDER_ID, PRODUCT_ID))
|
||||
.expectException(DuplicateOrderLineException.class)
|
||||
.expectExceptionMessage(Matchers.predicate(message -> ((String) message).contains(PRODUCT_ID)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEventAndProductAddedEvent_whenIncrementProductCountCommand_thenShouldPublishProductCountIncrementedEvent() {
|
||||
fixture.given(new OrderCreatedEvent(ORDER_ID), new ProductAddedEvent(ORDER_ID, PRODUCT_ID))
|
||||
.when(new IncrementProductCountCommand(ORDER_ID, PRODUCT_ID))
|
||||
.expectEvents(new ProductCountIncrementedEvent(ORDER_ID, PRODUCT_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEventProductAddedEventAndProductCountIncrementedEvent_whenDecrementProductCountCommand_thenShouldPublishProductCountDecrementedEvent() {
|
||||
fixture.given(new OrderCreatedEvent(ORDER_ID), new ProductAddedEvent(ORDER_ID, PRODUCT_ID), new ProductCountIncrementedEvent(ORDER_ID, PRODUCT_ID))
|
||||
.when(new DecrementProductCountCommand(ORDER_ID, PRODUCT_ID))
|
||||
.expectEvents(new ProductCountDecrementedEvent(ORDER_ID, PRODUCT_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEventAndProductAddedEvent_whenDecrementProductCountCommand_thenShouldPublishProductRemovedEvent() {
|
||||
fixture.given(new OrderCreatedEvent(ORDER_ID), new ProductAddedEvent(ORDER_ID, PRODUCT_ID))
|
||||
.when(new DecrementProductCountCommand(ORDER_ID, PRODUCT_ID))
|
||||
.expectEvents(new ProductRemovedEvent(ORDER_ID, PRODUCT_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEvent_whenConfirmOrderCommand_thenShouldPublishOrderConfirmedEvent() {
|
||||
fixture.given(new OrderCreatedEvent(ORDER_ID))
|
||||
.when(new ConfirmOrderCommand(ORDER_ID))
|
||||
.expectEvents(new OrderConfirmedEvent(ORDER_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEventAndOrderConfirmedEvent_whenConfirmOrderCommand_thenExpectNoEvents() {
|
||||
fixture.given(new OrderCreatedEvent(ORDER_ID), new OrderConfirmedEvent(ORDER_ID))
|
||||
.when(new ConfirmOrderCommand(ORDER_ID))
|
||||
.expectNoEvents();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEvent_whenShipOrderCommand_thenShouldThrowUnconfirmedOrderException() {
|
||||
fixture.given(new OrderCreatedEvent(ORDER_ID))
|
||||
.when(new ShipOrderCommand(ORDER_ID))
|
||||
.expectException(UnconfirmedOrderException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEventAndOrderConfirmedEvent_whenShipOrderCommand_thenShouldPublishOrderShippedEvent() {
|
||||
fixture.given(new OrderCreatedEvent(ORDER_ID), new OrderConfirmedEvent(ORDER_ID))
|
||||
.when(new ShipOrderCommand(ORDER_ID))
|
||||
.expectEvents(new OrderShippedEvent(ORDER_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEventProductAndOrderConfirmedEvent_whenAddProductCommand_thenShouldThrowOrderAlreadyConfirmedException() {
|
||||
fixture.given(new OrderCreatedEvent(ORDER_ID), new OrderConfirmedEvent(ORDER_ID))
|
||||
.when(new AddProductCommand(ORDER_ID, PRODUCT_ID))
|
||||
.expectException(OrderAlreadyConfirmedException.class)
|
||||
.expectExceptionMessage(Matchers.predicate(message -> ((String) message).contains(ORDER_ID)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEventProductAddedEventAndOrderConfirmedEvent_whenIncrementProductCountCommand_thenShouldThrowOrderAlreadyConfirmedException() {
|
||||
fixture.given(new OrderCreatedEvent(ORDER_ID), new ProductAddedEvent(ORDER_ID, PRODUCT_ID), new OrderConfirmedEvent(ORDER_ID))
|
||||
.when(new IncrementProductCountCommand(ORDER_ID, PRODUCT_ID))
|
||||
.expectException(OrderAlreadyConfirmedException.class)
|
||||
.expectExceptionMessage(Matchers.predicate(message -> ((String) message).contains(ORDER_ID)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEventProductAddedEventAndOrderConfirmedEvent_whenDecrementProductCountCommand_thenShouldThrowOrderAlreadyConfirmedException() {
|
||||
fixture.given(new OrderCreatedEvent(ORDER_ID), new ProductAddedEvent(ORDER_ID, PRODUCT_ID), new OrderConfirmedEvent(ORDER_ID))
|
||||
.when(new DecrementProductCountCommand(ORDER_ID, PRODUCT_ID))
|
||||
.expectException(OrderAlreadyConfirmedException.class)
|
||||
.expectExceptionMessage(Matchers.predicate(message -> ((String) message).contains(ORDER_ID)));
|
||||
}
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
package com.baeldung.axon.gui;
|
||||
|
||||
import com.baeldung.axon.OrderApplication;
|
||||
import com.baeldung.axon.querymodel.OrderResponse;
|
||||
import com.baeldung.axon.querymodel.OrderStatusResponse;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import org.springframework.web.reactive.function.client.WebClientResponseException;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.netty.http.client.HttpClient;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@SpringBootTest(classes = OrderApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
//marked as manual as the test is unstable on Jenkins due to low resources
|
||||
class OrderRestEndpointManualTest {
|
||||
|
||||
@LocalServerPort
|
||||
private int port;
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
void givenCreateOrderCalled_whenCallingAllOrders_thenOneCreatedOrderIsReturned() {
|
||||
WebClient client = WebClient.builder()
|
||||
.clientConnector(httpConnector())
|
||||
.build();
|
||||
createRandomNewOrder(client);
|
||||
StepVerifier.create(retrieveListResponse(client.get()
|
||||
.uri("http://localhost:" + port + "/all-orders")))
|
||||
.expectNextMatches(list -> 1 == list.size() && list.get(0)
|
||||
.getOrderStatus() == OrderStatusResponse.CREATED)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
void givenCreateOrderCalledThreeTimesAnd_whenCallingAllOrdersStreaming_thenTwoCreatedOrdersAreReturned() {
|
||||
WebClient client = WebClient.builder()
|
||||
.clientConnector(httpConnector())
|
||||
.build();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
createRandomNewOrder(client);
|
||||
}
|
||||
StepVerifier.create(retrieveStreamingResponse(client.get()
|
||||
.uri("http://localhost:" + port + "/all-orders-streaming")))
|
||||
.expectNextMatches(o -> o.getOrderStatus() == OrderStatusResponse.CREATED)
|
||||
.expectNextMatches(o -> o.getOrderStatus() == OrderStatusResponse.CREATED)
|
||||
.expectNextMatches(o -> o.getOrderStatus() == OrderStatusResponse.CREATED)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
void givenRuleExistThatNeedConfirmationBeforeShipping_whenCallingShipUnconfirmed_thenErrorReturned() {
|
||||
WebClient client = WebClient.builder()
|
||||
.clientConnector(httpConnector())
|
||||
.build();
|
||||
StepVerifier.create(retrieveResponse(client.post()
|
||||
.uri("http://localhost:" + port + "/ship-unconfirmed-order")))
|
||||
.verifyError(WebClientResponseException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
void givenShipOrderCalled_whenCallingAllShippedChairs_then234PlusOneIsReturned() {
|
||||
WebClient client = WebClient.builder()
|
||||
.clientConnector(httpConnector())
|
||||
.build();
|
||||
verifyVoidPost(client, "http://localhost:" + port + "/ship-order");
|
||||
StepVerifier.create(retrieveIntegerResponse(client.get()
|
||||
.uri("http://localhost:" + port + "/total-shipped/Deluxe Chair")))
|
||||
.assertNext(r -> assertEquals(235, r))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
void givenOrdersAreUpdated_whenCallingOrderUpdates_thenUpdatesReturned() {
|
||||
WebClient updaterClient = WebClient.builder()
|
||||
.clientConnector(httpConnector())
|
||||
.build();
|
||||
WebClient receiverClient = WebClient.builder()
|
||||
.clientConnector(httpConnector())
|
||||
.build();
|
||||
String orderId = UUID.randomUUID()
|
||||
.toString();
|
||||
String productId = UUID.randomUUID()
|
||||
.toString();
|
||||
StepVerifier.create(retrieveResponse(updaterClient.post()
|
||||
.uri("http://localhost:" + port + "/order/" + orderId)))
|
||||
.assertNext(Assertions::assertNotNull)
|
||||
.verifyComplete();
|
||||
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
|
||||
executor.schedule(() -> addIncrementDecrementConfirmAndShipProduct(orderId, productId), 1L, TimeUnit.SECONDS);
|
||||
try {
|
||||
StepVerifier.create(retrieveStreamingResponse(receiverClient.get()
|
||||
.uri("http://localhost:" + port + "/order-updates/" + orderId)))
|
||||
.assertNext(p -> assertTrue(p.getProducts()
|
||||
.isEmpty()))
|
||||
.assertNext(p -> assertEquals(1, p.getProducts()
|
||||
.get(productId)))
|
||||
.assertNext(p -> assertEquals(2, p.getProducts()
|
||||
.get(productId)))
|
||||
.assertNext(p -> assertEquals(1, p.getProducts()
|
||||
.get(productId)))
|
||||
.assertNext(p -> assertEquals(OrderStatusResponse.CONFIRMED, p.getOrderStatus()))
|
||||
.assertNext(p -> assertEquals(OrderStatusResponse.SHIPPED, p.getOrderStatus()))
|
||||
.thenCancel()
|
||||
.verify();
|
||||
} finally {
|
||||
executor.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
private void addIncrementDecrementConfirmAndShipProduct(String orderId, String productId) {
|
||||
WebClient client = WebClient.builder()
|
||||
.clientConnector(httpConnector())
|
||||
.build();
|
||||
String base = "http://localhost:" + port + "/order/" + orderId;
|
||||
verifyVoidPost(client, base + "/product/" + productId);
|
||||
verifyVoidPost(client, base + "/product/" + productId + "/increment");
|
||||
verifyVoidPost(client, base + "/product/" + productId + "/decrement");
|
||||
verifyVoidPost(client, base + "/confirm");
|
||||
verifyVoidPost(client, base + "/ship");
|
||||
}
|
||||
|
||||
private void createRandomNewOrder(WebClient client){
|
||||
StepVerifier.create(retrieveResponse(client.post()
|
||||
.uri("http://localhost:" + port + "/order")))
|
||||
.assertNext(Assertions::assertNotNull)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
private void verifyVoidPost(WebClient client, String uri) {
|
||||
StepVerifier.create(retrieveResponse(client.post()
|
||||
.uri(uri)))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
private static ReactorClientHttpConnector httpConnector() {
|
||||
HttpClient httpClient = HttpClient.create()
|
||||
.wiretap(true);
|
||||
return new ReactorClientHttpConnector(httpClient);
|
||||
}
|
||||
|
||||
private Mono<String> retrieveResponse(WebClient.RequestBodySpec spec) {
|
||||
return spec.retrieve()
|
||||
.bodyToMono(String.class);
|
||||
}
|
||||
|
||||
private Mono<ResponseList> retrieveListResponse(WebClient.RequestHeadersSpec<?> spec) {
|
||||
return spec.accept(MediaType.APPLICATION_JSON)
|
||||
.retrieve()
|
||||
.bodyToMono(ResponseList.class);
|
||||
}
|
||||
|
||||
private Mono<Integer> retrieveIntegerResponse(WebClient.RequestHeadersSpec<?> spec) {
|
||||
return spec.retrieve()
|
||||
.bodyToMono(Integer.class);
|
||||
}
|
||||
|
||||
private Flux<OrderResponse> retrieveStreamingResponse(WebClient.RequestHeadersSpec<?> spec) {
|
||||
return spec.retrieve()
|
||||
.bodyToFlux(OrderResponse.class);
|
||||
}
|
||||
|
||||
private static class ResponseList extends ArrayList<OrderResponse> {
|
||||
|
||||
private ResponseList() {
|
||||
super();
|
||||
}
|
||||
}
|
||||
}
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
package com.baeldung.axon.querymodel;
|
||||
|
||||
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
|
||||
import com.baeldung.axon.coreapi.events.OrderCreatedEvent;
|
||||
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductAddedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountDecrementedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountIncrementedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductRemovedEvent;
|
||||
import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
|
||||
import com.baeldung.axon.coreapi.queries.Order;
|
||||
import com.baeldung.axon.coreapi.queries.OrderStatus;
|
||||
import com.baeldung.axon.coreapi.queries.OrderUpdatesQuery;
|
||||
import com.baeldung.axon.coreapi.queries.TotalProductsShippedQuery;
|
||||
|
||||
import org.axonframework.queryhandling.QueryUpdateEmitter;
|
||||
import org.junit.jupiter.api.*;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public abstract class AbstractOrdersEventHandlerUnitTest {
|
||||
|
||||
private static final String ORDER_ID_1 = UUID.randomUUID()
|
||||
.toString();
|
||||
private static final String ORDER_ID_2 = UUID.randomUUID()
|
||||
.toString();
|
||||
private static final String PRODUCT_ID_1 = UUID.randomUUID()
|
||||
.toString();
|
||||
private static final String PRODUCT_ID_2 = UUID.randomUUID()
|
||||
.toString();
|
||||
private OrdersEventHandler handler;
|
||||
private static Order orderOne;
|
||||
private static Order orderTwo;
|
||||
QueryUpdateEmitter emitter = mock(QueryUpdateEmitter.class);
|
||||
|
||||
@BeforeAll
|
||||
static void createOrders() {
|
||||
orderOne = new Order(ORDER_ID_1);
|
||||
orderOne.getProducts()
|
||||
.put(PRODUCT_ID_1, 3);
|
||||
orderOne.setOrderShipped();
|
||||
|
||||
orderTwo = new Order(ORDER_ID_2);
|
||||
orderTwo.getProducts()
|
||||
.put(PRODUCT_ID_1, 1);
|
||||
orderTwo.getProducts()
|
||||
.put(PRODUCT_ID_2, 1);
|
||||
orderTwo.setOrderConfirmed();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
handler = getHandler();
|
||||
}
|
||||
|
||||
protected abstract OrdersEventHandler getHandler();
|
||||
|
||||
@Test
|
||||
void givenTwoOrdersPlacedOfWhichOneNotShipped_whenFindAllOrderedProductsQuery_thenCorrectOrdersAreReturned() {
|
||||
resetWithTwoOrders();
|
||||
|
||||
List<Order> result = handler.handle(new FindAllOrderedProductsQuery());
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(2, result.size());
|
||||
|
||||
Order order_1 = result.stream()
|
||||
.filter(o -> o.getOrderId()
|
||||
.equals(ORDER_ID_1))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
assertEquals(orderOne, order_1);
|
||||
|
||||
Order order_2 = result.stream()
|
||||
.filter(o -> o.getOrderId()
|
||||
.equals(ORDER_ID_2))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
assertEquals(orderTwo, order_2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTwoOrdersPlacedOfWhichOneNotShipped_whenFindAllOrderedProductsQueryStreaming_thenCorrectOrdersAreReturned() {
|
||||
resetWithTwoOrders();
|
||||
final Consumer<Order> orderVerifier = order -> {
|
||||
if (order.getOrderId()
|
||||
.equals(orderOne.getOrderId())) {
|
||||
assertEquals(orderOne, order);
|
||||
} else if (order.getOrderId()
|
||||
.equals(orderTwo.getOrderId())) {
|
||||
assertEquals(orderTwo, order);
|
||||
} else {
|
||||
throw new RuntimeException("Would expect either order one or order two");
|
||||
}
|
||||
};
|
||||
|
||||
StepVerifier.create(Flux.from(handler.handleStreaming(new FindAllOrderedProductsQuery())))
|
||||
.assertNext(orderVerifier)
|
||||
.assertNext(orderVerifier)
|
||||
.expectComplete()
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNoOrdersPlaced_whenTotalProductsShippedQuery_thenZeroReturned() {
|
||||
assertEquals(0, handler.handle(new TotalProductsShippedQuery(PRODUCT_ID_1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTwoOrdersPlacedOfWhichOneNotShipped_whenTotalProductsShippedQuery_thenOnlyCountProductsFirstOrder() {
|
||||
resetWithTwoOrders();
|
||||
|
||||
assertEquals(3, handler.handle(new TotalProductsShippedQuery(PRODUCT_ID_1)));
|
||||
assertEquals(0, handler.handle(new TotalProductsShippedQuery(PRODUCT_ID_2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTwoOrdersPlacedAndShipped_whenTotalProductsShippedQuery_thenCountBothOrders() {
|
||||
resetWithTwoOrders();
|
||||
handler.on(new OrderShippedEvent(ORDER_ID_2));
|
||||
|
||||
assertEquals(4, handler.handle(new TotalProductsShippedQuery(PRODUCT_ID_1)));
|
||||
assertEquals(1, handler.handle(new TotalProductsShippedQuery(PRODUCT_ID_2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderExist_whenOrderUpdatesQuery_thenOrderReturned() {
|
||||
resetWithTwoOrders();
|
||||
|
||||
Order result = handler.handle(new OrderUpdatesQuery(ORDER_ID_1));
|
||||
assertNotNull(result);
|
||||
assertEquals(ORDER_ID_1, result.getOrderId());
|
||||
assertEquals(3, result.getProducts()
|
||||
.get(PRODUCT_ID_1));
|
||||
assertEquals(OrderStatus.SHIPPED, result.getOrderStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderExist_whenProductAddedEvent_thenUpdateEmittedOnce() {
|
||||
handler.on(new OrderCreatedEvent(ORDER_ID_1));
|
||||
|
||||
handler.on(new ProductAddedEvent(ORDER_ID_1, PRODUCT_ID_1));
|
||||
|
||||
verify(emitter, times(1)).emit(eq(OrderUpdatesQuery.class), any(), any(Order.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderWithProductExist_whenProductCountDecrementedEvent_thenUpdateEmittedOnce() {
|
||||
handler.on(new OrderCreatedEvent(ORDER_ID_1));
|
||||
handler.on(new ProductAddedEvent(ORDER_ID_1, PRODUCT_ID_1));
|
||||
reset(emitter);
|
||||
|
||||
handler.on(new ProductCountDecrementedEvent(ORDER_ID_1, PRODUCT_ID_1));
|
||||
|
||||
verify(emitter, times(1)).emit(eq(OrderUpdatesQuery.class), any(), any(Order.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderWithProductExist_whenProductRemovedEvent_thenUpdateEmittedOnce() {
|
||||
handler.on(new OrderCreatedEvent(ORDER_ID_1));
|
||||
handler.on(new ProductAddedEvent(ORDER_ID_1, PRODUCT_ID_1));
|
||||
reset(emitter);
|
||||
|
||||
handler.on(new ProductRemovedEvent(ORDER_ID_1, PRODUCT_ID_1));
|
||||
|
||||
verify(emitter, times(1)).emit(eq(OrderUpdatesQuery.class), any(), any(Order.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderWithProductExist_whenProductCountIncrementedEvent_thenUpdateEmittedOnce() {
|
||||
handler.on(new OrderCreatedEvent(ORDER_ID_1));
|
||||
handler.on(new ProductAddedEvent(ORDER_ID_1, PRODUCT_ID_1));
|
||||
reset(emitter);
|
||||
|
||||
handler.on(new ProductCountIncrementedEvent(ORDER_ID_1, PRODUCT_ID_1));
|
||||
|
||||
verify(emitter, times(1)).emit(eq(OrderUpdatesQuery.class), any(), any(Order.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderWithProductExist_whenOrderConfirmedEvent_thenUpdateEmittedOnce() {
|
||||
handler.on(new OrderCreatedEvent(ORDER_ID_1));
|
||||
handler.on(new ProductAddedEvent(ORDER_ID_1, PRODUCT_ID_1));
|
||||
reset(emitter);
|
||||
|
||||
handler.on(new OrderConfirmedEvent(ORDER_ID_1));
|
||||
|
||||
verify(emitter, times(1)).emit(eq(OrderUpdatesQuery.class), any(), any(Order.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderWithProductAndConfirmationExist_whenOrderShippedEvent_thenUpdateEmittedOnce() {
|
||||
handler.on(new OrderCreatedEvent(ORDER_ID_1));
|
||||
handler.on(new ProductAddedEvent(ORDER_ID_1, PRODUCT_ID_1));
|
||||
reset(emitter);
|
||||
|
||||
handler.on(new OrderShippedEvent(ORDER_ID_1));
|
||||
|
||||
verify(emitter, times(1)).emit(eq(OrderUpdatesQuery.class), any(), any(Order.class));
|
||||
}
|
||||
|
||||
private void resetWithTwoOrders() {
|
||||
handler.reset(Arrays.asList(orderOne, orderTwo));
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.axon.querymodel;
|
||||
|
||||
public class InMemoryOrdersEventHandlerUnitTest extends AbstractOrdersEventHandlerUnitTest {
|
||||
|
||||
@Override
|
||||
protected OrdersEventHandler getHandler() {
|
||||
return new InMemoryOrdersEventHandler(emitter);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.axon.querymodel;
|
||||
|
||||
import com.mongodb.client.MongoClient;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
|
||||
|
||||
@DataMongoTest
|
||||
public class MongoOrdersEventHandlerUnitTest extends AbstractOrdersEventHandlerUnitTest {
|
||||
|
||||
@Autowired
|
||||
MongoClient mongoClient;
|
||||
|
||||
@Override
|
||||
protected OrdersEventHandler getHandler() {
|
||||
mongoClient.getDatabase("axonframework")
|
||||
.drop();
|
||||
return new MongoOrdersEventHandler(mongoClient, emitter);
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package com.baeldung.axon.querymodel;
|
||||
|
||||
import com.baeldung.axon.OrderApplication;
|
||||
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
|
||||
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductAddedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountDecrementedEvent;
|
||||
import com.baeldung.axon.coreapi.events.ProductCountIncrementedEvent;
|
||||
import com.baeldung.axon.coreapi.queries.Order;
|
||||
|
||||
import org.axonframework.eventhandling.gateway.EventGateway;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@SpringBootTest(classes = OrderApplication.class)
|
||||
class OrderQueryServiceIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
OrderQueryService queryService;
|
||||
|
||||
@Autowired
|
||||
EventGateway eventGateway;
|
||||
|
||||
@Autowired
|
||||
OrdersEventHandler handler;
|
||||
|
||||
private String orderId;
|
||||
private final String productId = "Deluxe Chair";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
orderId = UUID.randomUUID()
|
||||
.toString();
|
||||
Order order = new Order(orderId);
|
||||
handler.reset(Collections.singletonList(order));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEventSend_whenCallingAllOrders_thenOneCreatedOrderIsReturned() throws ExecutionException, InterruptedException {
|
||||
List<OrderResponse> result = queryService.findAllOrders()
|
||||
.get();
|
||||
assertEquals(1, result.size());
|
||||
OrderResponse response = result.get(0);
|
||||
assertEquals(orderId, response.getOrderId());
|
||||
assertEquals(OrderStatusResponse.CREATED, response.getOrderStatus());
|
||||
assertTrue(response.getProducts()
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrderCreatedEventSend_whenCallingAllOrdersStreaming_thenOneOrderIsReturned() {
|
||||
Flux<OrderResponse> result = queryService.allOrdersStreaming();
|
||||
StepVerifier.create(result)
|
||||
.assertNext(order -> assertEquals(orderId, order.getOrderId()))
|
||||
.expectComplete()
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenThreeDeluxeChairsShipped_whenCallingAllShippedChairs_then234PlusTreeIsReturned() {
|
||||
Order order = new Order(orderId);
|
||||
order.getProducts()
|
||||
.put(productId, 3);
|
||||
order.setOrderShipped();
|
||||
handler.reset(Collections.singletonList(order));
|
||||
|
||||
assertEquals(237, queryService.totalShipped(productId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOrdersAreUpdated_whenCallingOrderUpdates_thenUpdatesReturned() {
|
||||
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
|
||||
executor.schedule(this::addIncrementDecrementConfirmAndShip, 100L, TimeUnit.MILLISECONDS);
|
||||
try {
|
||||
StepVerifier.create(queryService.orderUpdates(orderId))
|
||||
.assertNext(order -> assertTrue(order.getProducts()
|
||||
.isEmpty()))
|
||||
.assertNext(order -> assertEquals(1, order.getProducts()
|
||||
.get(productId)))
|
||||
.assertNext(order -> assertEquals(2, order.getProducts()
|
||||
.get(productId)))
|
||||
.assertNext(order -> assertEquals(1, order.getProducts()
|
||||
.get(productId)))
|
||||
.assertNext(order -> assertEquals(OrderStatusResponse.CONFIRMED, order.getOrderStatus()))
|
||||
.assertNext(order -> assertEquals(OrderStatusResponse.SHIPPED, order.getOrderStatus()))
|
||||
.thenCancel()
|
||||
.verify();
|
||||
} finally {
|
||||
executor.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
private void addIncrementDecrementConfirmAndShip() {
|
||||
sendProductAddedEvent();
|
||||
sendProductCountIncrementEvent();
|
||||
sendProductCountDecrementEvent();
|
||||
sendOrderConfirmedEvent();
|
||||
sendOrderShippedEvent();
|
||||
}
|
||||
|
||||
private void sendProductAddedEvent() {
|
||||
ProductAddedEvent event = new ProductAddedEvent(orderId, productId);
|
||||
eventGateway.publish(event);
|
||||
}
|
||||
|
||||
private void sendProductCountIncrementEvent() {
|
||||
ProductCountIncrementedEvent event = new ProductCountIncrementedEvent(orderId, productId);
|
||||
eventGateway.publish(event);
|
||||
}
|
||||
|
||||
private void sendProductCountDecrementEvent() {
|
||||
ProductCountDecrementedEvent event = new ProductCountDecrementedEvent(orderId, productId);
|
||||
eventGateway.publish(event);
|
||||
}
|
||||
|
||||
private void sendOrderConfirmedEvent() {
|
||||
OrderConfirmedEvent event = new OrderConfirmedEvent(orderId);
|
||||
eventGateway.publish(event);
|
||||
}
|
||||
|
||||
private void sendOrderShippedEvent() {
|
||||
OrderShippedEvent event = new OrderShippedEvent(orderId);
|
||||
eventGateway.publish(event);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
spring.mongodb.embedded.version=5.0.6
|
||||
axon.axonserver.enabled=false
|
||||
@@ -0,0 +1,7 @@
|
||||
docker run \
|
||||
-d \
|
||||
--name axon_server \
|
||||
-p 8024:8024 \
|
||||
-p 8124:8124 \
|
||||
-e AXONIQ_AXONSERVER_NAME=order_demo \
|
||||
axoniq/axonserver
|
||||
@@ -0,0 +1,7 @@
|
||||
docker run \
|
||||
-d \
|
||||
--name order_projection \
|
||||
-p 27017:27017 \
|
||||
-e MONGO_INITDB_ROOT_USERNAME=admin1234 \
|
||||
-e MONGO_INITDB_ROOT_PASSWORD=somepassword \
|
||||
mongo
|
||||
@@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [DDD Bounded Contexts and Java Modules](https://www.baeldung.com/java-modules-ddd-bounded-contexts)
|
||||
@@ -0,0 +1,54 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.dddcontexts.infrastructure</groupId>
|
||||
<artifactId>ddd-contexts-infrastructure</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.dddcontexts</groupId>
|
||||
<artifactId>ddd-contexts</artifactId>
|
||||
<version>1.0</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.dddcontexts.shippingcontext</groupId>
|
||||
<artifactId>ddd-contexts-shippingcontext</artifactId>
|
||||
<version>${appmodules.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.dddcontexts.ordercontext</groupId>
|
||||
<artifactId>ddd-contexts-ordercontext</artifactId>
|
||||
<version>${appmodules.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.dddcontexts.sharedkernel</groupId>
|
||||
<artifactId>ddd-contexts-sharedkernel</artifactId>
|
||||
<version>${appmodules.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${source.version}</source>
|
||||
<target>${target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<source.version>9</source.version>
|
||||
<target.version>9</target.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.dddcontexts.infrastructure.db;
|
||||
|
||||
import com.baeldung.dddcontexts.ordercontext.model.CustomerOrder;
|
||||
import com.baeldung.dddcontexts.ordercontext.repository.CustomerOrderRepository;
|
||||
import com.baeldung.dddcontexts.shippingcontext.model.PackageItem;
|
||||
import com.baeldung.dddcontexts.shippingcontext.model.ShippableOrder;
|
||||
import com.baeldung.dddcontexts.shippingcontext.repository.ShippingOrderRepository;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class InMemoryOrderStore implements CustomerOrderRepository, ShippingOrderRepository {
|
||||
private Map<Integer, PersistenceOrder> ordersDb = new HashMap<>();
|
||||
private volatile static InMemoryOrderStore instance = new InMemoryOrderStore();
|
||||
|
||||
@Override
|
||||
public void saveCustomerOrder(CustomerOrder order) {
|
||||
this.ordersDb.put(order.getOrderId(), new PersistenceOrder(order.getOrderId(),
|
||||
order.getPaymentMethod(),
|
||||
order.getAddress(),
|
||||
order
|
||||
.getOrderItems()
|
||||
.stream()
|
||||
.map(orderItem ->
|
||||
new PersistenceOrder.OrderItem(orderItem.getProductId(),
|
||||
orderItem.getQuantity(),
|
||||
orderItem.getUnitWeight(),
|
||||
orderItem.getUnitPrice()))
|
||||
.collect(Collectors.toList())
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ShippableOrder> findShippableOrder(int orderId) {
|
||||
if (!this.ordersDb.containsKey(orderId)) return Optional.empty();
|
||||
PersistenceOrder orderRecord = this.ordersDb.get(orderId);
|
||||
return Optional.of(
|
||||
new ShippableOrder(orderRecord.orderId, orderRecord.orderItems
|
||||
.stream().map(orderItem -> new PackageItem(orderItem.productId,
|
||||
orderItem.itemWeight,
|
||||
orderItem.quantity * orderItem.unitPrice)
|
||||
).collect(Collectors.toList())));
|
||||
}
|
||||
|
||||
public static InMemoryOrderStore provider() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static class PersistenceOrder {
|
||||
public int orderId;
|
||||
public String paymentMethod;
|
||||
public String address;
|
||||
public List<OrderItem> orderItems;
|
||||
|
||||
public PersistenceOrder(int orderId, String paymentMethod, String address, List<OrderItem> orderItems) {
|
||||
this.orderId = orderId;
|
||||
this.paymentMethod = paymentMethod;
|
||||
this.address = address;
|
||||
this.orderItems = orderItems;
|
||||
}
|
||||
|
||||
public static class OrderItem {
|
||||
public int productId;
|
||||
public float unitPrice;
|
||||
public float itemWeight;
|
||||
public int quantity;
|
||||
|
||||
public OrderItem(int productId, int quantity, float unitWeight, float unitPrice) {
|
||||
this.itemWeight = unitWeight;
|
||||
this.quantity = quantity;
|
||||
this.unitPrice = unitPrice;
|
||||
this.productId = productId;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.dddcontexts.infrastructure.events;
|
||||
|
||||
import com.baeldung.dddcontexts.sharedkernel.events.ApplicationEvent;
|
||||
import com.baeldung.dddcontexts.sharedkernel.events.EventBus;
|
||||
import com.baeldung.dddcontexts.sharedkernel.events.EventSubscriber;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArraySet;
|
||||
|
||||
public class SimpleEventBus implements EventBus {
|
||||
private final Map<String, Set<EventSubscriber>> subscribers = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public <E extends ApplicationEvent> void publish(E event) {
|
||||
if (subscribers.containsKey(event.getType())) {
|
||||
subscribers.get(event.getType())
|
||||
.forEach(subscriber -> subscriber.onEvent(event));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E extends ApplicationEvent> void subscribe(String eventType, EventSubscriber subscriber) {
|
||||
Set<EventSubscriber> eventSubscribers = subscribers.get(eventType);
|
||||
if (eventSubscribers == null) {
|
||||
eventSubscribers = new CopyOnWriteArraySet<>();
|
||||
subscribers.put(eventType, eventSubscribers);
|
||||
}
|
||||
eventSubscribers.add(subscriber);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E extends ApplicationEvent> void unsubscribe(String eventType, EventSubscriber subscriber) {
|
||||
if (subscribers.containsKey(eventType)) {
|
||||
subscribers.get(eventType).remove(subscriber);
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import com.baeldung.dddcontexts.infrastructure.db.InMemoryOrderStore;
|
||||
import com.baeldung.dddcontexts.infrastructure.events.SimpleEventBus;
|
||||
|
||||
module com.baeldung.dddcontexts.infrastructure {
|
||||
requires transitive com.baeldung.dddcontexts.sharedkernel;
|
||||
requires transitive com.baeldung.dddcontexts.ordercontext;
|
||||
requires transitive com.baeldung.dddcontexts.shippingcontext;
|
||||
provides com.baeldung.dddcontexts.sharedkernel.events.EventBus
|
||||
with SimpleEventBus;
|
||||
provides com.baeldung.dddcontexts.ordercontext.repository.CustomerOrderRepository
|
||||
with InMemoryOrderStore;
|
||||
provides com.baeldung.dddcontexts.shippingcontext.repository.ShippingOrderRepository
|
||||
with InMemoryOrderStore;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.dddcontexts.mainapp</groupId>
|
||||
<artifactId>ddd-contexts-mainapp</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.dddcontexts</groupId>
|
||||
<artifactId>ddd-contexts</artifactId>
|
||||
<version>1.0</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.dddcontexts.infrastructure</groupId>
|
||||
<artifactId>ddd-contexts-infrastructure</artifactId>
|
||||
<version>${appmodules.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<enableAssertions>true</enableAssertions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${compiler.plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${source.version}</source>
|
||||
<target>${target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<source.version>9</source.version>
|
||||
<target.version>9</target.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.dddcontexts.mainapp;
|
||||
|
||||
import com.baeldung.dddcontexts.ordercontext.model.CustomerOrder;
|
||||
import com.baeldung.dddcontexts.ordercontext.model.OrderItem;
|
||||
import com.baeldung.dddcontexts.ordercontext.repository.CustomerOrderRepository;
|
||||
import com.baeldung.dddcontexts.ordercontext.service.OrderService;
|
||||
import com.baeldung.dddcontexts.sharedkernel.events.EventBus;
|
||||
import com.baeldung.dddcontexts.shippingcontext.repository.ShippingOrderRepository;
|
||||
import com.baeldung.dddcontexts.shippingcontext.service.ShippingService;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String args[]) {
|
||||
Map<Class<?>, Object> container = createContainer();
|
||||
OrderService orderService = (OrderService) container.get(OrderService.class);
|
||||
ShippingService shippingService = (ShippingService) container.get(ShippingService.class);
|
||||
shippingService.listenToOrderEvents();
|
||||
|
||||
CustomerOrder customerOrder = new CustomerOrder();
|
||||
int orderId = 1;
|
||||
customerOrder.setOrderId(orderId);
|
||||
List<OrderItem> orderItems = new ArrayList<OrderItem>();
|
||||
orderItems.add(new OrderItem(1, 2, 3, 1));
|
||||
orderItems.add(new OrderItem(2, 1, 1, 1));
|
||||
orderItems.add(new OrderItem(3, 4, 11, 21));
|
||||
customerOrder.setOrderItems(orderItems);
|
||||
customerOrder.setPaymentMethod("PayPal");
|
||||
customerOrder.setAddress("Full address here");
|
||||
orderService.placeOrder(customerOrder);
|
||||
|
||||
if (orderId == shippingService.getParcelByOrderId(orderId).get().getOrderId()) {
|
||||
System.out.println("Order has been processed and shipped successfully");
|
||||
}
|
||||
}
|
||||
|
||||
public static Map<Class<?>, Object> createContainer() {
|
||||
EventBus eventBus = ServiceLoader.load(EventBus.class).findFirst().get();
|
||||
CustomerOrderRepository customerOrderRepository = ServiceLoader.load(CustomerOrderRepository.class).findFirst().get();
|
||||
ShippingOrderRepository shippingOrderRepository = ServiceLoader.load(ShippingOrderRepository.class).findFirst().get();
|
||||
ShippingService shippingService = ServiceLoader.load(ShippingService.class).findFirst().get();
|
||||
shippingService.setEventBus(eventBus);
|
||||
shippingService.setOrderRepository(shippingOrderRepository);
|
||||
OrderService orderService = ServiceLoader.load(OrderService.class).findFirst().get();
|
||||
orderService.setEventBus(eventBus);
|
||||
orderService.setOrderRepository(customerOrderRepository);
|
||||
HashMap<Class<?>, Object> container = new HashMap<>();
|
||||
container.put(OrderService.class, orderService);
|
||||
container.put(ShippingService.class, shippingService);
|
||||
return container;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
module com.baeldung.dddcontexts.mainapp {
|
||||
uses com.baeldung.dddcontexts.sharedkernel.events.EventBus;
|
||||
uses com.baeldung.dddcontexts.ordercontext.service.OrderService;
|
||||
uses com.baeldung.dddcontexts.ordercontext.repository.CustomerOrderRepository;
|
||||
uses com.baeldung.dddcontexts.shippingcontext.repository.ShippingOrderRepository;
|
||||
uses com.baeldung.dddcontexts.shippingcontext.service.ShippingService;
|
||||
requires transitive com.baeldung.dddcontexts.infrastructure;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.dddcontexts.ordercontext</groupId>
|
||||
<artifactId>ddd-contexts-ordercontext</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.dddcontexts</groupId>
|
||||
<artifactId>ddd-contexts</artifactId>
|
||||
<version>1.0</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.dddcontexts.sharedkernel</groupId>
|
||||
<artifactId>ddd-contexts-sharedkernel</artifactId>
|
||||
<version>${appmodules.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${source.version}</source>
|
||||
<target>${target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<source.version>9</source.version>
|
||||
<target.version>9</target.version>
|
||||
<entitymodule.version>1.0</entitymodule.version>
|
||||
<daomodule.version>1.0</daomodule.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.dddcontexts.ordercontext.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class CustomerOrder {
|
||||
private int orderId;
|
||||
private String paymentMethod;
|
||||
private String address;
|
||||
private List<OrderItem> orderItems;
|
||||
|
||||
public CustomerOrder() {
|
||||
|
||||
}
|
||||
|
||||
public float calculateTotalPrice() {
|
||||
return orderItems.stream().map(OrderItem::getTotalPrice)
|
||||
.reduce(0F, Float::sum);
|
||||
}
|
||||
|
||||
public void setOrderItems(List<OrderItem> orderItems) {
|
||||
this.orderItems = orderItems;
|
||||
}
|
||||
|
||||
public int getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public List<OrderItem> getOrderItems() {
|
||||
return orderItems;
|
||||
}
|
||||
|
||||
public void setOrderId(int orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public String getPaymentMethod() {
|
||||
return paymentMethod;
|
||||
}
|
||||
|
||||
public void setPaymentMethod(String paymentMethod) {
|
||||
this.paymentMethod = paymentMethod;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.dddcontexts.ordercontext.model;
|
||||
|
||||
public class OrderItem {
|
||||
private int productId;
|
||||
private int quantity;
|
||||
private float unitPrice;
|
||||
private float unitWeight;
|
||||
|
||||
public OrderItem(int productId, int quantity, float unitPrice, float unitWeight) {
|
||||
this.productId = productId;
|
||||
this.quantity = quantity;
|
||||
this.unitPrice = unitPrice;
|
||||
this.unitWeight = unitWeight;
|
||||
}
|
||||
|
||||
public int getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
public void setProductId(int productId) {
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public int getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(int quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public float getTotalPrice() {
|
||||
return this.quantity * this.unitPrice;
|
||||
}
|
||||
|
||||
public void setUnitPrice(float unitPrice) {
|
||||
this.unitPrice = unitPrice;
|
||||
}
|
||||
|
||||
public float getUnitWeight() {
|
||||
return unitWeight;
|
||||
}
|
||||
|
||||
public float getUnitPrice() {
|
||||
return unitPrice;
|
||||
}
|
||||
|
||||
public void setUnitWeight(float unitWeight) {
|
||||
this.unitWeight = unitWeight;
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.dddcontexts.ordercontext.repository;
|
||||
|
||||
import com.baeldung.dddcontexts.ordercontext.model.CustomerOrder;
|
||||
|
||||
public interface CustomerOrderRepository {
|
||||
void saveCustomerOrder(CustomerOrder order);
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.dddcontexts.ordercontext.service;
|
||||
|
||||
import com.baeldung.dddcontexts.ordercontext.model.CustomerOrder;
|
||||
import com.baeldung.dddcontexts.ordercontext.repository.CustomerOrderRepository;
|
||||
import com.baeldung.dddcontexts.sharedkernel.events.ApplicationEvent;
|
||||
import com.baeldung.dddcontexts.sharedkernel.events.EventBus;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class CustomerOrderService implements OrderService {
|
||||
public static final String EVENT_ORDER_READY_FOR_SHIPMENT = "OrderReadyForShipmentEvent";
|
||||
|
||||
private CustomerOrderRepository orderRepository;
|
||||
private EventBus eventBus;
|
||||
|
||||
@Override
|
||||
public void placeOrder(CustomerOrder order) {
|
||||
this.orderRepository.saveCustomerOrder(order);
|
||||
Map<String, String> payload = new HashMap<>();
|
||||
payload.put("order_id", String.valueOf(order.getOrderId()));
|
||||
ApplicationEvent event = new ApplicationEvent(payload) {
|
||||
@Override
|
||||
public String getType() {
|
||||
return EVENT_ORDER_READY_FOR_SHIPMENT;
|
||||
}
|
||||
};
|
||||
this.eventBus.publish(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EventBus getEventBus() {
|
||||
return eventBus;
|
||||
}
|
||||
|
||||
public void setOrderRepository(CustomerOrderRepository orderRepository) {
|
||||
this.orderRepository = orderRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setEventBus(EventBus eventBus) {
|
||||
this.eventBus = eventBus;
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.dddcontexts.ordercontext.service;
|
||||
|
||||
import com.baeldung.dddcontexts.ordercontext.model.CustomerOrder;
|
||||
import com.baeldung.dddcontexts.ordercontext.repository.CustomerOrderRepository;
|
||||
import com.baeldung.dddcontexts.sharedkernel.service.ApplicationService;
|
||||
|
||||
public interface OrderService extends ApplicationService {
|
||||
void placeOrder(CustomerOrder order);
|
||||
|
||||
void setOrderRepository(CustomerOrderRepository orderRepository);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
module com.baeldung.dddcontexts.ordercontext {
|
||||
requires com.baeldung.dddcontexts.sharedkernel;
|
||||
exports com.baeldung.dddcontexts.ordercontext.service;
|
||||
exports com.baeldung.dddcontexts.ordercontext.model;
|
||||
exports com.baeldung.dddcontexts.ordercontext.repository;
|
||||
provides com.baeldung.dddcontexts.ordercontext.service.OrderService
|
||||
with com.baeldung.dddcontexts.ordercontext.service.CustomerOrderService;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.dddcontexts.sharedkernel</groupId>
|
||||
<artifactId>ddd-contexts-sharedkernel</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.dddcontexts</groupId>
|
||||
<artifactId>ddd-contexts</artifactId>
|
||||
<version>1.0</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${source.version}</source>
|
||||
<target>${target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<source.version>9</source.version>
|
||||
<target.version>9</target.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.dddcontexts.sharedkernel.events;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public abstract class ApplicationEvent {
|
||||
protected Map<String, String> payload;
|
||||
|
||||
public abstract String getType();
|
||||
|
||||
public String getPayloadValue(String key) {
|
||||
if (this.payload.containsKey(key)) {
|
||||
return this.payload.get(key);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public ApplicationEvent(Map<String, String> payload) {
|
||||
this.payload = payload;
|
||||
}
|
||||
}
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.dddcontexts.sharedkernel.events;
|
||||
|
||||
public interface EventBus {
|
||||
<E extends ApplicationEvent> void publish(E event);
|
||||
|
||||
<E extends ApplicationEvent> void subscribe(String eventType, EventSubscriber subscriber);
|
||||
|
||||
<E extends ApplicationEvent> void unsubscribe(String eventType, EventSubscriber subscriber);
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.dddcontexts.sharedkernel.events;
|
||||
|
||||
public interface EventSubscriber {
|
||||
<E extends ApplicationEvent> void onEvent(E event);
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.dddcontexts.sharedkernel.service;
|
||||
|
||||
import com.baeldung.dddcontexts.sharedkernel.events.ApplicationEvent;
|
||||
import com.baeldung.dddcontexts.sharedkernel.events.EventBus;
|
||||
import com.baeldung.dddcontexts.sharedkernel.events.EventSubscriber;
|
||||
|
||||
public interface ApplicationService {
|
||||
|
||||
default <E extends ApplicationEvent> void publishEvent(E event) {
|
||||
EventBus eventBus = getEventBus();
|
||||
if (eventBus != null) {
|
||||
eventBus.publish(event);
|
||||
}
|
||||
}
|
||||
|
||||
default <E extends ApplicationEvent> void subscribe(String eventType, EventSubscriber subscriber) {
|
||||
EventBus eventBus = getEventBus();
|
||||
if (eventBus != null) {
|
||||
eventBus.subscribe(eventType, subscriber);
|
||||
}
|
||||
}
|
||||
|
||||
default <E extends ApplicationEvent> void unsubscribe(String eventType, EventSubscriber subscriber) {
|
||||
EventBus eventBus = getEventBus();
|
||||
if (eventBus != null) {
|
||||
eventBus.unsubscribe(eventType, subscriber);
|
||||
}
|
||||
}
|
||||
|
||||
EventBus getEventBus();
|
||||
|
||||
void setEventBus(EventBus eventBus);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
module com.baeldung.dddcontexts.sharedkernel {
|
||||
exports com.baeldung.dddcontexts.sharedkernel.events;
|
||||
exports com.baeldung.dddcontexts.sharedkernel.service;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.dddcontexts.shippingcontext</groupId>
|
||||
<artifactId>ddd-contexts-shippingcontext</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.dddcontexts</groupId>
|
||||
<artifactId>ddd-contexts</artifactId>
|
||||
<version>1.0</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.dddcontexts.sharedkernel</groupId>
|
||||
<artifactId>ddd-contexts-sharedkernel</artifactId>
|
||||
<version>${appmodules.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${source.version}</source>
|
||||
<target>${target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<source.version>9</source.version>
|
||||
<target.version>9</target.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.dddcontexts.shippingcontext.model;
|
||||
|
||||
public class PackageItem {
|
||||
private int productId;
|
||||
private float weight;
|
||||
private float estimatedValue;
|
||||
|
||||
public PackageItem(int productId, float weight, float estimatedValue) {
|
||||
this.productId = productId;
|
||||
this.weight = weight;
|
||||
this.estimatedValue = estimatedValue;
|
||||
}
|
||||
|
||||
public int getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
public void setProductId(int productId) {
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public float getWeight() {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public void setWeight(float weight) {
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public float getEstimatedValue() {
|
||||
return estimatedValue;
|
||||
}
|
||||
|
||||
public void setEstimatedValue(float estimatedValue) {
|
||||
this.estimatedValue = estimatedValue;
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.dddcontexts.shippingcontext.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Parcel {
|
||||
private int orderId;
|
||||
private String address;
|
||||
private String trackingId;
|
||||
private List<PackageItem> packageItems;
|
||||
|
||||
public Parcel(int orderId, String address, List<PackageItem> packageItems) {
|
||||
this.orderId = orderId;
|
||||
this.address = address;
|
||||
this.packageItems = packageItems;
|
||||
}
|
||||
|
||||
public float calculateTotalWeight() {
|
||||
return packageItems.stream().map(PackageItem::getWeight)
|
||||
.reduce(0F, Float::sum);
|
||||
}
|
||||
|
||||
public boolean isTaxable() {
|
||||
return calculateEstimatedValue() > 100;
|
||||
}
|
||||
|
||||
public float calculateEstimatedValue() {
|
||||
return packageItems.stream().map(PackageItem::getWeight)
|
||||
.reduce(0F, Float::sum);
|
||||
}
|
||||
|
||||
public int getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public void setOrderId(int orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public String getTrackingId() {
|
||||
return trackingId;
|
||||
}
|
||||
|
||||
public void setTrackingId(String trackingId) {
|
||||
this.trackingId = trackingId;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.dddcontexts.shippingcontext.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ShippableOrder {
|
||||
private int orderId;
|
||||
private String address;
|
||||
private List<PackageItem> packageItems;
|
||||
|
||||
public ShippableOrder(int orderId, List<PackageItem> packageItems) {
|
||||
this.orderId = orderId;
|
||||
this.packageItems = packageItems;
|
||||
}
|
||||
|
||||
public int getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public void setOrderId(int orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public List<PackageItem> getPackageItems() {
|
||||
return packageItems;
|
||||
}
|
||||
|
||||
public void setPackageItems(List<PackageItem> packageItems) {
|
||||
this.packageItems = packageItems;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.dddcontexts.shippingcontext.repository;
|
||||
|
||||
import com.baeldung.dddcontexts.shippingcontext.model.ShippableOrder;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface ShippingOrderRepository {
|
||||
Optional<ShippableOrder> findShippableOrder(int orderId);
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.dddcontexts.shippingcontext.service;
|
||||
|
||||
import com.baeldung.dddcontexts.sharedkernel.events.ApplicationEvent;
|
||||
import com.baeldung.dddcontexts.sharedkernel.events.EventBus;
|
||||
import com.baeldung.dddcontexts.sharedkernel.events.EventSubscriber;
|
||||
import com.baeldung.dddcontexts.shippingcontext.model.Parcel;
|
||||
import com.baeldung.dddcontexts.shippingcontext.model.ShippableOrder;
|
||||
import com.baeldung.dddcontexts.shippingcontext.repository.ShippingOrderRepository;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public class ParcelShippingService implements ShippingService {
|
||||
public static final String EVENT_ORDER_READY_FOR_SHIPMENT = "OrderReadyForShipmentEvent";
|
||||
private ShippingOrderRepository orderRepository;
|
||||
private EventBus eventBus;
|
||||
private Map<Integer, Parcel> shippedParcels = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public void shipOrder(int orderId) {
|
||||
Optional<ShippableOrder> order = this.orderRepository.findShippableOrder(orderId);
|
||||
order.ifPresent(completedOrder -> {
|
||||
Parcel parcel = new Parcel(completedOrder.getOrderId(), completedOrder.getAddress(), completedOrder.getPackageItems());
|
||||
if (parcel.isTaxable()) {
|
||||
// Calculate additional taxes
|
||||
}
|
||||
// Ship parcel
|
||||
this.shippedParcels.put(completedOrder.getOrderId(), parcel);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void listenToOrderEvents() {
|
||||
this.eventBus.subscribe(EVENT_ORDER_READY_FOR_SHIPMENT, new EventSubscriber() {
|
||||
@Override
|
||||
public <E extends ApplicationEvent> void onEvent(E event) {
|
||||
shipOrder(Integer.parseInt(event.getPayloadValue("order_id")));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Parcel> getParcelByOrderId(int orderId) {
|
||||
return Optional.ofNullable(this.shippedParcels.get(orderId));
|
||||
}
|
||||
|
||||
public void setOrderRepository(ShippingOrderRepository orderRepository) {
|
||||
this.orderRepository = orderRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EventBus getEventBus() {
|
||||
return eventBus;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setEventBus(EventBus eventBus) {
|
||||
this.eventBus = eventBus;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.dddcontexts.shippingcontext.service;
|
||||
|
||||
import com.baeldung.dddcontexts.sharedkernel.service.ApplicationService;
|
||||
import com.baeldung.dddcontexts.shippingcontext.model.Parcel;
|
||||
import com.baeldung.dddcontexts.shippingcontext.repository.ShippingOrderRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface ShippingService extends ApplicationService {
|
||||
void shipOrder(int orderId);
|
||||
|
||||
void listenToOrderEvents();
|
||||
|
||||
Optional<Parcel> getParcelByOrderId(int orderId);
|
||||
|
||||
void setOrderRepository(ShippingOrderRepository orderRepository);
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
module com.baeldung.dddcontexts.shippingcontext {
|
||||
requires com.baeldung.dddcontexts.sharedkernel;
|
||||
exports com.baeldung.dddcontexts.shippingcontext.service;
|
||||
exports com.baeldung.dddcontexts.shippingcontext.model;
|
||||
exports com.baeldung.dddcontexts.shippingcontext.repository;
|
||||
provides com.baeldung.dddcontexts.shippingcontext.service.ShippingService
|
||||
with com.baeldung.dddcontexts.shippingcontext.service.ParcelShippingService;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.dddcontexts</groupId>
|
||||
<artifactId>ddd-contexts</artifactId>
|
||||
<version>1.0</version>
|
||||
<name>ddd-contexts</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>patterns-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>ddd-contexts-sharedkernel</module>
|
||||
<module>ddd-contexts-infrastructure</module>
|
||||
<module>ddd-contexts-shippingcontext</module>
|
||||
<module>ddd-contexts-ordercontext</module>
|
||||
<module>ddd-contexts-mainapp</module>
|
||||
</modules>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${compiler.plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${source.version}</source>
|
||||
<target>${target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<forkCount>0</forkCount>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<source.version>9</source.version>
|
||||
<target.version>9</target.version>
|
||||
<compiler.plugin.version>3.8.1</compiler.plugin.version>
|
||||
<appmodules.version>1.0</appmodules.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,9 @@
|
||||
## Domain-driven Design (DDD)
|
||||
|
||||
This module contains articles about Domain-driven Design (DDD)
|
||||
|
||||
### Relevant articles
|
||||
|
||||
- [Persisting DDD Aggregates](https://www.baeldung.com/spring-persisting-ddd-aggregates)
|
||||
- [Double Dispatch in DDD](https://www.baeldung.com/ddd-double-dispatch)
|
||||
- [Organizing Layers Using Hexagonal Architecture, DDD, and Spring](https://www.baeldung.com/hexagonal-architecture-ddd-spring)
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>ddd</artifactId>
|
||||
<name>ddd</name>
|
||||
<packaging>jar</packaging>
|
||||
<description>DDD series examples</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit</groupId>
|
||||
<artifactId>junit-bom</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-mongodb</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-cassandra</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.joda</groupId>
|
||||
<artifactId>joda-money</artifactId>
|
||||
<version>${joda-money.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.flapdoodle.embed</groupId>
|
||||
<artifactId>de.flapdoodle.embed.mongo</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<joda-money.version>1.0.1</joda-money.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.ddd;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication(scanBasePackages = "com.baeldung.ddd.order")
|
||||
public class PersistingDddAggregatesApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(PersistingDddAggregatesApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.ddd.order;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.joda.money.Money;
|
||||
|
||||
public class Order {
|
||||
private final List<OrderLine> orderLines;
|
||||
private Money totalCost;
|
||||
|
||||
public Order(List<OrderLine> orderLines) {
|
||||
checkNotNull(orderLines);
|
||||
if (orderLines.isEmpty()) {
|
||||
throw new IllegalArgumentException("Order must have at least one order line item");
|
||||
}
|
||||
this.orderLines = new ArrayList<>(orderLines);
|
||||
totalCost = calculateTotalCost();
|
||||
}
|
||||
|
||||
public void addLineItem(OrderLine orderLine) {
|
||||
checkNotNull(orderLine);
|
||||
orderLines.add(orderLine);
|
||||
totalCost = totalCost.plus(orderLine.cost());
|
||||
}
|
||||
|
||||
public List<OrderLine> getOrderLines() {
|
||||
return new ArrayList<>(orderLines);
|
||||
}
|
||||
|
||||
public void removeLineItem(int line) {
|
||||
OrderLine removedLine = orderLines.remove(line);
|
||||
totalCost = totalCost.minus(removedLine.cost());
|
||||
}
|
||||
|
||||
public Money totalCost() {
|
||||
return totalCost;
|
||||
}
|
||||
|
||||
private Money calculateTotalCost() {
|
||||
return orderLines.stream()
|
||||
.map(OrderLine::cost)
|
||||
.reduce(Money::plus)
|
||||
.get();
|
||||
}
|
||||
|
||||
private static void checkNotNull(Object par) {
|
||||
if (par == null) {
|
||||
throw new NullPointerException("Parameter cannot be null");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.ddd.order;
|
||||
|
||||
import org.joda.money.Money;
|
||||
|
||||
public class OrderLine {
|
||||
private final Product product;
|
||||
private final int quantity;
|
||||
|
||||
public OrderLine(Product product, int quantity) {
|
||||
super();
|
||||
this.product = product;
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
OrderLine other = (OrderLine) obj;
|
||||
if (product == null) {
|
||||
if (other.product != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!product.equals(other.product)) {
|
||||
return false;
|
||||
}
|
||||
if (quantity != other.quantity) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((product == null) ? 0 : product.hashCode());
|
||||
result = prime * result + quantity;
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "OrderLine [product=" + product + ", quantity=" + quantity + "]";
|
||||
}
|
||||
|
||||
Money cost() {
|
||||
return product.getPrice()
|
||||
.multipliedBy(quantity);
|
||||
}
|
||||
|
||||
Product getProduct() {
|
||||
return product;
|
||||
}
|
||||
|
||||
int getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.ddd.order;
|
||||
|
||||
import org.joda.money.Money;
|
||||
|
||||
public class Product {
|
||||
private final Money price;
|
||||
|
||||
public Product(Money price) {
|
||||
super();
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
Product other = (Product) obj;
|
||||
if (price == null) {
|
||||
if (other.price != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!price.equals(other.price)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((price == null) ? 0 : price.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Product [price=" + price + "]";
|
||||
}
|
||||
|
||||
Money getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.ddd.order.config;
|
||||
|
||||
import org.bson.Document;
|
||||
import org.joda.money.CurrencyUnit;
|
||||
import org.joda.money.Money;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.data.convert.ReadingConverter;
|
||||
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Collections;
|
||||
|
||||
@Configuration
|
||||
public class CustomMongoConfiguration {
|
||||
|
||||
@Bean
|
||||
public MongoCustomConversions customConversions() {
|
||||
return new MongoCustomConversions(Collections.singletonList(DocumentToMoneyConverter.INSTANCE));
|
||||
}
|
||||
|
||||
@ReadingConverter
|
||||
enum DocumentToMoneyConverter implements Converter<Document, Money> {
|
||||
|
||||
INSTANCE;
|
||||
|
||||
@Override
|
||||
public Money convert(Document source) {
|
||||
Document money = source.get("money", Document.class);
|
||||
|
||||
return Money.of(getCurrency(money), getAmount(money));
|
||||
}
|
||||
|
||||
private CurrencyUnit getCurrency(Document money) {
|
||||
Document currency = money.get("currency", Document.class);
|
||||
String currencyCode = currency.getString("code");
|
||||
return CurrencyUnit.of(currencyCode);
|
||||
}
|
||||
|
||||
private BigDecimal getAmount(Document money) {
|
||||
String amount = money.getString("amount");
|
||||
return BigDecimal.valueOf(Double.parseDouble(amount));
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
import org.joda.money.CurrencyUnit;
|
||||
import org.joda.money.Money;
|
||||
|
||||
public class AmountBasedDiscountPolicy implements DiscountPolicy {
|
||||
@Override
|
||||
public double discount(Order order) {
|
||||
if (order.totalCost()
|
||||
.isGreaterThan(Money.of(CurrencyUnit.USD, 500.00))) {
|
||||
return 0.10;
|
||||
} else
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
public interface DiscountPolicy {
|
||||
double discount(Order order);
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
public class FlatDiscountPolicy implements DiscountPolicy {
|
||||
@Override
|
||||
public double discount(Order order) {
|
||||
return 0.01;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
import java.math.RoundingMode;
|
||||
import java.util.List;
|
||||
|
||||
import org.joda.money.Money;
|
||||
|
||||
import com.baeldung.ddd.order.OrderLine;
|
||||
import com.baeldung.ddd.order.doubledispatch.visitor.OrderVisitor;
|
||||
import com.baeldung.ddd.order.doubledispatch.visitor.Visitable;
|
||||
|
||||
public class Order extends com.baeldung.ddd.order.Order implements Visitable<OrderVisitor> {
|
||||
public Order(List<OrderLine> orderLines) {
|
||||
super(orderLines);
|
||||
}
|
||||
|
||||
public Money totalCost(SpecialDiscountPolicy discountPolicy) {
|
||||
return totalCost().multipliedBy(1 - applyDiscountPolicy(discountPolicy), RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
protected double applyDiscountPolicy(SpecialDiscountPolicy discountPolicy) {
|
||||
return discountPolicy.discount(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(OrderVisitor visitor) {
|
||||
visitor.visit(this);
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
public interface SpecialDiscountPolicy extends DiscountPolicy {
|
||||
double discount(SpecialOrder order);
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.ddd.order.OrderLine;
|
||||
import com.baeldung.ddd.order.doubledispatch.visitor.OrderVisitor;
|
||||
|
||||
public class SpecialOrder extends Order {
|
||||
|
||||
private boolean eligibleForExtraDiscount;
|
||||
|
||||
public SpecialOrder(List<OrderLine> orderLines) {
|
||||
super(orderLines);
|
||||
this.eligibleForExtraDiscount = false;
|
||||
}
|
||||
|
||||
public SpecialOrder(List<OrderLine> orderLines, boolean eligibleForSpecialDiscount) {
|
||||
super(orderLines);
|
||||
this.eligibleForExtraDiscount = eligibleForSpecialDiscount;
|
||||
}
|
||||
|
||||
public boolean isEligibleForExtraDiscount() {
|
||||
return eligibleForExtraDiscount;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected double applyDiscountPolicy(SpecialDiscountPolicy discountPolicy) {
|
||||
return discountPolicy.discount(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(OrderVisitor visitor) {
|
||||
visitor.visit(this);
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.ddd.order.doubledispatch.visitor;
|
||||
|
||||
import com.baeldung.ddd.order.doubledispatch.Order;
|
||||
import com.baeldung.ddd.order.doubledispatch.SpecialOrder;
|
||||
|
||||
public class HtmlOrderViewCreator implements OrderVisitor {
|
||||
|
||||
private String html;
|
||||
|
||||
public String getHtml() {
|
||||
return html;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(Order order) {
|
||||
html = String.format("<p>Regular order total cost: %s</p>", order.totalCost());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(SpecialOrder order) {
|
||||
html = String.format("<h1>Special Order</h1><p>total cost: %s</p>", order.totalCost());
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.ddd.order.doubledispatch.visitor;
|
||||
|
||||
import com.baeldung.ddd.order.doubledispatch.Order;
|
||||
import com.baeldung.ddd.order.doubledispatch.SpecialOrder;
|
||||
|
||||
public interface OrderVisitor {
|
||||
void visit(Order order);
|
||||
void visit(SpecialOrder order);
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.ddd.order.doubledispatch.visitor;
|
||||
|
||||
public interface Visitable<V> {
|
||||
void accept(V visitor);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.baeldung.ddd.order.jpa;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.ElementCollection;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "order_table")
|
||||
class JpaOrder {
|
||||
private String currencyUnit;
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
@ElementCollection(fetch = FetchType.EAGER)
|
||||
private final List<JpaOrderLine> orderLines;
|
||||
private BigDecimal totalCost;
|
||||
|
||||
JpaOrder() {
|
||||
totalCost = null;
|
||||
orderLines = new ArrayList<>();
|
||||
}
|
||||
|
||||
JpaOrder(List<JpaOrderLine> orderLines) {
|
||||
checkNotNull(orderLines);
|
||||
if (orderLines.isEmpty()) {
|
||||
throw new IllegalArgumentException("Order must have at least one order line item");
|
||||
}
|
||||
this.orderLines = new ArrayList<>(orderLines);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
JpaOrder other = (JpaOrder) obj;
|
||||
if (id == null) {
|
||||
if (other.id != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!id.equals(other.id)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((id == null) ? 0 : id.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "JpaOrder [currencyUnit=" + currencyUnit + ", id=" + id + ", orderLines=" + orderLines + ", totalCost=" + totalCost + "]";
|
||||
}
|
||||
|
||||
void addLineItem(JpaOrderLine orderLine) {
|
||||
checkNotNull(orderLine);
|
||||
orderLines.add(orderLine);
|
||||
}
|
||||
|
||||
String getCurrencyUnit() {
|
||||
return currencyUnit;
|
||||
}
|
||||
|
||||
Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
List<JpaOrderLine> getOrderLines() {
|
||||
return new ArrayList<>(orderLines);
|
||||
}
|
||||
|
||||
BigDecimal getTotalCost() {
|
||||
return totalCost;
|
||||
}
|
||||
|
||||
void removeLineItem(int line) {
|
||||
orderLines.remove(line);
|
||||
}
|
||||
|
||||
void setCurrencyUnit(String currencyUnit) {
|
||||
this.currencyUnit = currencyUnit;
|
||||
}
|
||||
|
||||
void setTotalCost(BigDecimal totalCost) {
|
||||
this.totalCost = totalCost;
|
||||
}
|
||||
|
||||
private static void checkNotNull(Object par) {
|
||||
if (par == null) {
|
||||
throw new NullPointerException("Parameter cannot be null");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.ddd.order.jpa;
|
||||
|
||||
import javax.persistence.Embeddable;
|
||||
import javax.persistence.Embedded;
|
||||
|
||||
@Embeddable
|
||||
class JpaOrderLine {
|
||||
@Embedded
|
||||
private final JpaProduct product;
|
||||
private final int quantity;
|
||||
|
||||
JpaOrderLine() {
|
||||
quantity = 0;
|
||||
product = null;
|
||||
}
|
||||
|
||||
JpaOrderLine(JpaProduct product, int quantity) {
|
||||
super();
|
||||
this.product = product;
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
JpaOrderLine other = (JpaOrderLine) obj;
|
||||
if (product == null) {
|
||||
if (other.product != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!product.equals(other.product)) {
|
||||
return false;
|
||||
}
|
||||
if (quantity != other.quantity) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((product == null) ? 0 : product.hashCode());
|
||||
result = prime * result + quantity;
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "JpaOrderLine [product=" + product + ", quantity=" + quantity + "]";
|
||||
}
|
||||
|
||||
JpaProduct getProduct() {
|
||||
return product;
|
||||
}
|
||||
|
||||
int getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.ddd.order.jpa;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface JpaOrderRepository extends JpaRepository<JpaOrder, Long> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.ddd.order.jpa;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import javax.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
class JpaProduct {
|
||||
private String currencyUnit;
|
||||
private BigDecimal price;
|
||||
|
||||
public JpaProduct() {
|
||||
}
|
||||
|
||||
public JpaProduct(BigDecimal price, String currencyUnit) {
|
||||
super();
|
||||
this.price = price;
|
||||
this.currencyUnit = currencyUnit;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
JpaProduct other = (JpaProduct) obj;
|
||||
if (currencyUnit == null) {
|
||||
if (other.currencyUnit != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!currencyUnit.equals(other.currencyUnit)) {
|
||||
return false;
|
||||
}
|
||||
if (price == null) {
|
||||
if (other.price != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!price.equals(other.price)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public String getCurrencyUnit() {
|
||||
return currencyUnit;
|
||||
}
|
||||
|
||||
public BigDecimal getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((currencyUnit == null) ? 0 : currencyUnit.hashCode());
|
||||
result = prime * result + ((price == null) ? 0 : price.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
public void setCurrencyUnit(String currencyUnit) {
|
||||
this.currencyUnit = currencyUnit;
|
||||
}
|
||||
|
||||
public void setPrice(BigDecimal price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "JpaProduct [currencyUnit=" + currencyUnit + ", price=" + price + "]";
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.ddd.order.mongo;
|
||||
|
||||
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||
|
||||
import com.baeldung.ddd.order.Order;
|
||||
|
||||
public interface OrderMongoRepository extends MongoRepository<Order, String> {
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user