@CommandHandler
public void handle(StockItemFCStockSupplyCommand command) throws Exception {
LOGGER.info("Handling StockItemFCStockSupplyCommand ...");
Aggregate<StockItem> stockItem = null;
String sku = command.getSku();
try {
stockItem = repository.load(sku);
}
catch (AggregateNotFoundException e) {
stockItem = repository.newInstance(()-> new StockItem(sku));
}
catch (Exception e) {
LOGGER.error(e.getMessage());
throw e;
}
stockItem.execute(aggregateRoot -> aggregateRoot.addAdjustment(command.getQuantity()));
//Publish the Latest Supply Record to NOSQL Implementation
publisher.publish(stockItem.invoke(x -> x.getSupply()));
}
@AggregateRoot
@Revision("1.0")
public class StockItem {
private static final Logger LOGGER = LoggerFactory.getLogger(StockItem.class);
@AggregateIdentifier
private String aggregateIdentifier;
private int supply;
public StockItem() { }
public StockItem(String aggregateIdentifier) {
LOGGER.info("Creating a new Aggregate " + aggregateIdentifier);
apply(new StockItemCreatedEvent(aggregateIdentifier, 0));
}
public void addAdjustment(Integer quantity) {
LOGGER.trace("addAdjustment - Raising StockItemSupplyEvent");
apply(new StockItemAdjustmentEvent(this.aggregateIdentifier, quantity));
//Add something here or use andThen or andThenApply?
}
@EventSourcingHandler
private void on(StockItemCreatedEvent event) {
LOGGER.info("StockItemCreatedEvent ..." + event.getAggregateIdentifier());
this.aggregateIdentifier = event.getAggregateIdentifier();
this.supply = event.getQuantity();
}
@EventSourcingHandler
private void on(StockItemAdjustmentEvent event) {
LOGGER.trace(String.format("StockItemAdjustmentEvent {%s},{%s}", event.getAggregateIdentifier(), event.getQuantity()));
this.supply += event.getQuantity();
}
public int getSupply() {
return this.supply;
}
}