Java 26392 Move modules to patterns-module (#15060)
* JAVA-26392 Move axon module and ddd module to patterns-modules * JAVA-26292 Move ddd-contexts to patterns-module
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user