Merge pull request #610 from radresian/event-sourcing

Event sourcing
This commit is contained in:
Ilkka Seppälä 2017-09-03 11:46:11 +03:00 committed by GitHub
commit efc6eb8828
16 changed files with 1441 additions and 1 deletions

33
event-sourcing/README.md Normal file
View File

@ -0,0 +1,33 @@
---
layout: pattern
title: Event Sourcing
folder: event-sourcing
permalink: /patterns/event-sourcing/
categories: Architectural
tags:
- Java
- Difficulty Intermediate
- Performance
---
## Intent
Instead of storing just the current state of the data in a domain, use an append-only store to record the full series of actions taken on that data. The store acts as the system of record and can be used to materialize the domain objects. This can simplify tasks in complex domains, by avoiding the need to synchronize the data model and the business domain, while improving performance, scalability, and responsiveness. It can also provide consistency for transactional data, and maintain full audit trails and history that can enable compensating actions.
![alt text](./etc/event-sourcing.png "Event Sourcing")
## Applicability
Use the Event Sourcing pattern when
* You need very high performance on persisting your application state even your application state have a complex relational data structure
* You need log of changes of your application state and ability to restore a state of any moment in time.
* You need to debug production problems by replaying the past events.
## Real world examples
* [The Lmax Architecture] (https://martinfowler.com/articles/lmax.html)
## Credits
* [Martin Fowler - Event Sourcing] (https://martinfowler.com/eaaDev/EventSourcing.html)
* [Event Sourcing | Microsoft Docs] (https://docs.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)
* [Reference 3: Introducing Event Sourcing] (https://msdn.microsoft.com/en-us/library/jj591559.aspx)

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.2.0" icons="true" automaticImage="PNG" always-add-relationships="true" generalizations="true"
realizations="true" associations="true" dependencies="false" nesting-relationships="true" router="FAN">
<class id="1" language="java" name="com.iluwatar.event.sourcing.event.DomainEvent" project="event-sourcing"
file="/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/DomainEvent.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="809" y="161"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="2" language="java" name="com.iluwatar.event.sourcing.event.AccountCreateEvent" project="event-sourcing"
file="/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="145" y="455"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="3" language="java" name="com.iluwatar.event.sourcing.event.MoneyDepositEvent" project="event-sourcing"
file="/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="480" y="451"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="4" language="java" name="com.iluwatar.event.sourcing.event.MoneyTransferEvent" project="event-sourcing"
file="/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="809" y="472"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="5" language="java" name="com.iluwatar.event.sourcing.state.AccountAggregate" project="event-sourcing"
file="/event-sourcing/src/main/java/com/iluwatar/event/sourcing/state/AccountAggregate.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="104" y="826"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="6" language="java" name="com.iluwatar.event.sourcing.processor.DomainEventProcessor"
project="event-sourcing"
file="/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="458" y="121"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="7" language="java" name="com.iluwatar.event.sourcing.processor.JsonFileJournal" project="event-sourcing"
file="/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="189" width="171" x="69" y="26"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="8" language="java" name="com.iluwatar.event.sourcing.domain.Account" project="event-sourcing"
file="/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="472" y="827"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<generalization id="9">
<end type="SOURCE" refId="2"/>
<end type="TARGET" refId="1"/>
</generalization>
<generalization id="10">
<end type="SOURCE" refId="4"/>
<end type="TARGET" refId="1"/>
</generalization>
<association id="11">
<end type="SOURCE" refId="6" navigable="false">
<attribute id="12" name="processorJournal">
<position height="0" width="0" x="0" y="0"/>
</attribute>
<multiplicity id="13" minimum="0" maximum="1">
<position height="0" width="0" x="0" y="0"/>
</multiplicity>
</end>
<end type="TARGET" refId="7" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<generalization id="14">
<end type="SOURCE" refId="3"/>
<end type="TARGET" refId="1"/>
</generalization>
<association id="15">
<end type="SOURCE" refId="5" navigable="false">
<attribute id="16" name="accounts"/>
<multiplicity id="17" minimum="0" maximum="2147483647"/>
</end>
<end type="TARGET" refId="8" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</classifier-display>
<association-display labels="true" multiplicity="true"/>
</class-diagram>

View File

@ -0,0 +1,184 @@
@startuml
package com.iluwatar.event.sourcing.journal {
class JsonFileJournal {
- aFile : File
- events : List<String>
- index : int
+ JsonFileJournal()
+ readNext() : DomainEvent
+ reset()
+ write(domainEvent : DomainEvent)
}
}
package com.iluwatar.event.sourcing.processor {
class DomainEventProcessor {
- precessorJournal : ProcessorJournal
+ DomainEventProcessor()
+ process(domainEvent : DomainEvent)
+ recover()
+ setPrecessorJournal(precessorJournal : ProcessorJournal)
}
}
package com.iluwatar.event.sourcing.service {
class AccountService {
- eventProcessor : EventProcessor
+ AccountService(eventProcessor : EventProcessor)
+ createAccount(accountNo : int, owner : String)
}
class MoneyTransactionService {
- eventProcessor : EventProcessor
+ MoneyTransactionService(eventProcessor : EventProcessor)
+ depositMoney(accountNo : int, money : BigDecimal)
+ transferMoney(accountNoFrom : int, accountNoTo : int, money : BigDecimal)
+ withdrawalMoney(accountNo : int, money : BigDecimal)
}
class SequenceIdGenerator {
- sequenceId : long {static}
+ SequenceIdGenerator()
+ nextSequenceId() : long {static}
}
}
package com.iluwatar.event.sourcing.event {
class AccountCreateEvent {
- accountNo : int
- owner : String
+ AccountCreateEvent(sequenceId : long, createdTime : long, accountNo : int, owner : String)
+ getAccountNo() : int
+ getOwner() : String
+ process()
}
class MoneyDepositEvent {
- accountNo : int
- money : BigDecimal
+ MoneyDepositEvent(sequenceId : long, createdTime : long, accountNo : int, money : BigDecimal)
+ getAccountNo() : int
+ getMoney() : BigDecimal
+ process()
}
class MoneyTransferEvent {
- accountNoFrom : int
- accountNoTo : int
- money : BigDecimal
+ MoneyTransferEvent(sequenceId : long, createdTime : long, money : BigDecimal, accountNoFrom : int, accountNoTo : int)
+ getAccountNoFrom() : int
+ getAccountNoTo() : int
+ getMoney() : BigDecimal
+ process()
}
class MoneyWithdrawalEvent {
- accountNo : int
- money : BigDecimal
+ MoneyWithdrawalEvent(sequenceId : long, createdTime : long, accountNo : int, money : BigDecimal)
+ getAccountNo() : int
+ getMoney() : BigDecimal
+ process()
}
}
package com.iluwatar.event.sourcing.gateway {
class AccountCreateContractSender {
+ AccountCreateContractSender()
+ sendContractInfo(account : Account)
}
class Gateways {
- accountCreateContractSender : AccountCreateContractSender {static}
- transactionLogger : TransactionLogger {static}
+ Gateways()
+ getAccountCreateContractSender() : AccountCreateContractSender {static}
+ getTransactionLogger() : TransactionLogger {static}
}
class TransactionLogger {
+ TransactionLogger()
+ log(transaction : Transaction)
}
}
package com.iluwatar.event.sourcing.app {
class App {
+ App()
+ main(args : String[]) {static}
}
}
package com.iluwatar.event.sourcing.state {
class AccountAggregate {
- accounts : Map<Integer, Account> {static}
+ AccountAggregate()
+ getAccount(accountNo : int) : Account {static}
+ putAccount(account : Account) {static}
+ resetState() {static}
}
}
package com.iluwatar.event.sourcing.domain {
class Account {
- accountNo : int
- money : BigDecimal
- owner : String
- transactions : List<Transaction>
+ Account(accountNo : int, owner : String)
+ copy() : Account
- depositMoney(money : BigDecimal) : Transaction
+ getAccountNo() : int
+ getMoney() : BigDecimal
+ getOwner() : String
+ getTransactions() : List<Transaction>
- handleDeposit(money : BigDecimal, realTime : boolean)
+ handleEvent(accountCreateEvent : AccountCreateEvent)
+ handleEvent(moneyDepositEvent : MoneyDepositEvent)
+ handleEvent(moneyWithdrawalEvent : MoneyWithdrawalEvent)
+ handleTransferFromEvent(moneyTransferEvent : MoneyTransferEvent)
+ handleTransferToEvent(moneyTransferEvent : MoneyTransferEvent)
- handleWithdrawal(money : BigDecimal, realTime : boolean)
+ setMoney(money : BigDecimal)
+ setTransactions(transactions : List<Transaction>)
+ toString() : String
- withdrawMoney(money : BigDecimal) : Transaction
}
class Transaction {
- accountNo : int
- lastBalance : BigDecimal
- moneyIn : BigDecimal
- moneyOut : BigDecimal
+ Transaction(accountNo : int, moneyIn : BigDecimal, moneyOut : BigDecimal, lastBalance : BigDecimal)
+ getAccountNo() : int
+ getLastBalance() : BigDecimal
+ getMoneyIn() : BigDecimal
+ getMoneyOut() : BigDecimal
+ toString() : String
}
}
package com.iluwatar.event.sourcing.api {
abstract class DomainEvent {
- createdTime : long
- eventClassName : String
- realTime : boolean
- sequenceId : long
+ DomainEvent(sequenceId : long, createdTime : long, eventClassName : String)
+ getCreatedTime() : long
+ getEventClassName() : String
+ getSequenceId() : long
+ isRealTime() : boolean
+ process() {abstract}
+ setRealTime(realTime : boolean)
}
interface EventProcessor {
+ process(DomainEvent) {abstract}
+ recover() {abstract}
+ setPrecessorJournal(ProcessorJournal) {abstract}
}
interface ProcessorJournal {
+ readNext() : DomainEvent {abstract}
+ reset() {abstract}
+ write(DomainEvent) {abstract}
}
}
Gateways --> "-accountCreateContractSender" AccountCreateContractSender
DomainEventProcessor --> "-precessorJournal" ProcessorJournal
Account --> "-transactions" Transaction
Gateways --> "-transactionLogger" TransactionLogger
AccountService --> "-eventProcessor" EventProcessor
MoneyTransactionService --> "-eventProcessor" EventProcessor
AccountCreateEvent --|> DomainEvent
MoneyDepositEvent --|> DomainEvent
MoneyTransferEvent --|> DomainEvent
MoneyWithdrawalEvent --|> DomainEvent
JsonFileJournal ..|> ProcessorJournal
DomainEventProcessor ..|> EventProcessor
@enduml

50
event-sourcing/pom.xml Normal file
View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
The MIT License
Copyright (c) 2014-2016 Ilkka Sepp<70>l<EFBFBD>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<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>
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.17.0-SNAPSHOT</version>
</parent>
<artifactId>event-sourcing</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.1</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,115 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.event.sourcing.app;
import com.iluwatar.event.sourcing.event.AccountCreateEvent;
import com.iluwatar.event.sourcing.event.MoneyDepositEvent;
import com.iluwatar.event.sourcing.event.MoneyTransferEvent;
import com.iluwatar.event.sourcing.processor.DomainEventProcessor;
import com.iluwatar.event.sourcing.state.AccountAggregate;
import java.math.BigDecimal;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Event Sourcing : Instead of storing just the current state of the data in a domain, use an
* append-only store to record the full series of actions taken on that data. The store acts as the
* system of record and can be used to materialize the domain objects. This can simplify tasks in
* complex domains, by avoiding the need to synchronize the data model and the business domain,
* while improving performance, scalability, and responsiveness. It can also provide consistency for
* transactional data, and maintain full audit trails and history that can enable compensating
* actions.
*
* This App class is an example usage of Event Sourcing pattern. As an example, two bank account is
* created, then some money deposit and transfer actions are taken so a new state of accounts is
* created. At that point, state is cleared in order to represent a system shot down. After the shot
* down, system state is recovered by re-creating the past events from event journal. Then state is
* printed so a user can view the last state is same with the state before system shot down.
*
* Created by Serdar Hamzaogullari on 06.08.2017.
*/
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
* The constant ACCOUNT OF DAENERYS.
*/
public static final int ACCOUNT_OF_DAENERYS = 1;
/**
* The constant ACCOUNT OF JON.
*/
public static final int ACCOUNT_OF_JON = 2;
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void main(String[] args) {
DomainEventProcessor eventProcessor = new DomainEventProcessor();
LOGGER.info("Running the system first time............");
eventProcessor.reset();
LOGGER.info("Creating th accounts............");
eventProcessor.process(new AccountCreateEvent(
0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen"));
eventProcessor.process(new AccountCreateEvent(
1, new Date().getTime(), ACCOUNT_OF_JON, "Jon Snow"));
LOGGER.info("Do some money operations............");
eventProcessor.process(new MoneyDepositEvent(
2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000")));
eventProcessor.process(new MoneyDepositEvent(
3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100")));
eventProcessor.process(new MoneyTransferEvent(
4, new Date().getTime(), new BigDecimal("10000"), ACCOUNT_OF_DAENERYS,
ACCOUNT_OF_JON));
LOGGER.info("...............State:............");
LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS).toString());
LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_JON).toString());
LOGGER.info("At that point system had a shot down, state in memory is cleared............");
AccountAggregate.resetState();
LOGGER.info("Recover the system by the events in journal file............");
eventProcessor = new DomainEventProcessor();
eventProcessor.recover();
LOGGER.info("...............Recovered State:............");
LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS).toString());
LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_JON).toString());
}
}

View File

@ -0,0 +1,186 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.event.sourcing.domain;
import com.iluwatar.event.sourcing.event.AccountCreateEvent;
import com.iluwatar.event.sourcing.event.MoneyDepositEvent;
import com.iluwatar.event.sourcing.event.MoneyTransferEvent;
import com.iluwatar.event.sourcing.state.AccountAggregate;
import java.math.BigDecimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is the Account class that holds the account info, the account number,
* account owner name and money of the account. Account class also have the business logic of events
* that effects this account.
*
* Created by Serdar Hamzaogullari on 06.08.2017.
*/
public class Account {
private static final Logger LOGGER = LoggerFactory.getLogger(Account.class);
private final int accountNo;
private final String owner;
private BigDecimal money;
/**
* Instantiates a new Account.
*
* @param accountNo the account no
* @param owner the owner
*/
public Account(int accountNo, String owner) {
this.accountNo = accountNo;
this.owner = owner;
money = BigDecimal.ZERO;
}
/**
* Gets account no.
*
* @return the account no
*/
public int getAccountNo() {
return accountNo;
}
/**
* Gets owner.
*
* @return the owner
*/
public String getOwner() {
return owner;
}
/**
* Gets money.
*
* @return the money
*/
public BigDecimal getMoney() {
return money;
}
/**
* Sets money.
*
* @param money the money
*/
public void setMoney(BigDecimal money) {
this.money = money;
}
/**
* Copy account.
*
* @return the account
*/
public Account copy() {
Account account = new Account(accountNo, owner);
account.setMoney(money);
return account;
}
@Override
public String toString() {
return "Account{"
+ "accountNo=" + accountNo
+ ", owner='" + owner + '\''
+ ", money=" + money
+ '}';
}
private void depositMoney(BigDecimal money) {
this.money = this.money.add(money);
}
private void withdrawMoney(BigDecimal money) {
this.money = this.money.subtract(money);
}
private void handleDeposit(BigDecimal money, boolean realTime) {
depositMoney(money);
AccountAggregate.putAccount(this);
if (realTime) {
LOGGER.info("Some external api for only realtime execution could be called here.");
}
}
private void handleWithdrawal(BigDecimal money, boolean realTime) {
if (this.money.compareTo(money) == -1) {
throw new RuntimeException("Insufficient Account Balance");
}
withdrawMoney(money);
AccountAggregate.putAccount(this);
if (realTime) {
LOGGER.info("Some external api for only realtime execution could be called here.");
}
}
/**
* Handles the MoneyDepositEvent.
*
* @param moneyDepositEvent the money deposit event
*/
public void handleEvent(MoneyDepositEvent moneyDepositEvent) {
handleDeposit(moneyDepositEvent.getMoney(), moneyDepositEvent.isRealTime());
}
/**
* Handles the AccountCreateEvent.
*
* @param accountCreateEvent the account create event
*/
public void handleEvent(AccountCreateEvent accountCreateEvent) {
AccountAggregate.putAccount(this);
if (accountCreateEvent.isRealTime()) {
LOGGER.info("Some external api for only realtime execution could be called here.");
}
}
/**
* Handles transfer from account event.
*
* @param moneyTransferEvent the money transfer event
*/
public void handleTransferFromEvent(MoneyTransferEvent moneyTransferEvent) {
handleWithdrawal(moneyTransferEvent.getMoney(), moneyTransferEvent.isRealTime());
}
/**
* Handles transfer to account event.
*
* @param moneyTransferEvent the money transfer event
*/
public void handleTransferToEvent(MoneyTransferEvent moneyTransferEvent) {
handleDeposit(moneyTransferEvent.getMoney(), moneyTransferEvent.isRealTime());
}
}

View File

@ -0,0 +1,82 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.event.sourcing.event;
import com.iluwatar.event.sourcing.domain.Account;
import com.iluwatar.event.sourcing.state.AccountAggregate;
/**
* This is the class that implements account create event.
* Holds the necessary info for an account create event.
* Implements the process function that finds the event related
* domain objects and calls the related domain object's handle event functions
*
* Created by Serdar Hamzaogullari on 06.08.2017.
*/
public class AccountCreateEvent extends DomainEvent {
private final int accountNo;
private final String owner;
/**
* Instantiates a new Account create event.
*
* @param sequenceId the sequence id
* @param createdTime the created time
* @param accountNo the account no
* @param owner the owner
*/
public AccountCreateEvent(long sequenceId, long createdTime, int accountNo, String owner) {
super(sequenceId, createdTime, "AccountCreateEvent");
this.accountNo = accountNo;
this.owner = owner;
}
/**
* Gets account no.
*
* @return the account no
*/
public int getAccountNo() {
return accountNo;
}
/**
* Gets owner.
*
* @return the owner
*/
public String getOwner() {
return owner;
}
@Override
public void process() {
Account account = AccountAggregate.getAccount(accountNo);
if (account != null) {
throw new RuntimeException("Account already exists");
}
account = new Account(accountNo, owner);
account.handleEvent(this);
}
}

View File

@ -0,0 +1,101 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.event.sourcing.event;
import java.io.Serializable;
/**
* This is the base class for domain events. All events must extend this class.
*
* Created by Serdar Hamzaogullari on 06.08.2017.
*/
public abstract class DomainEvent implements Serializable {
private final long sequenceId;
private final long createdTime;
private final String eventClassName;
private boolean realTime = true;
/**
* Instantiates a new Domain event.
*
* @param sequenceId the sequence id
* @param createdTime the created time
* @param eventClassName the event class name
*/
public DomainEvent(long sequenceId, long createdTime, String eventClassName) {
this.sequenceId = sequenceId;
this.createdTime = createdTime;
this.eventClassName = eventClassName;
}
/**
* Gets sequence id.
*
* @return the sequence id
*/
public long getSequenceId() {
return sequenceId;
}
/**
* Gets created time.
*
* @return the created time
*/
public long getCreatedTime() {
return createdTime;
}
/**
* Is real time boolean.
*
* @return the boolean
*/
public boolean isRealTime() {
return realTime;
}
/**
* Sets real time.
*
* @param realTime the real time
*/
public void setRealTime(boolean realTime) {
this.realTime = realTime;
}
/**
* Process.
*/
public abstract void process();
/**
* Gets event class name.
*
* @return the event class name
*/
public String getEventClassName() {
return eventClassName;
}
}

View File

@ -0,0 +1,82 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.event.sourcing.event;
import com.iluwatar.event.sourcing.domain.Account;
import com.iluwatar.event.sourcing.state.AccountAggregate;
import java.math.BigDecimal;
/**
* This is the class that implements money deposit event.
* Holds the necessary info for a money deposit event.
* Implements the process function that finds the event related
* domain objects and calls the related domain object's handle event functions
*
* Created by Serdar Hamzaogullari on 06.08.2017.
*/
public class MoneyDepositEvent extends DomainEvent {
private final BigDecimal money;
private final int accountNo;
/**
* Instantiates a new Money deposit event.
*
* @param sequenceId the sequence id
* @param createdTime the created time
* @param accountNo the account no
* @param money the money
*/
public MoneyDepositEvent(long sequenceId, long createdTime, int accountNo, BigDecimal money) {
super(sequenceId, createdTime, "MoneyDepositEvent");
this.money = money;
this.accountNo = accountNo;
}
/**
* Gets money.
*
* @return the money
*/
public BigDecimal getMoney() {
return money;
}
/**
* Gets account no.
*
* @return the account no
*/
public int getAccountNo() {
return accountNo;
}
@Override
public void process() {
Account account = AccountAggregate.getAccount(accountNo);
if (account == null) {
throw new RuntimeException("Account not found");
}
account.handleEvent(this);
}
}

View File

@ -0,0 +1,101 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.event.sourcing.event;
import com.iluwatar.event.sourcing.domain.Account;
import com.iluwatar.event.sourcing.state.AccountAggregate;
import java.math.BigDecimal;
/**
* This is the class that implements money transfer event.
* Holds the necessary info for a money transfer event.
* Implements the process function that finds the event related
* domain objects and calls the related domain object's handle event functions
*
* Created by Serdar Hamzaogullari on 06.08.2017.
*/
public class MoneyTransferEvent extends DomainEvent {
private final BigDecimal money;
private final int accountNoFrom;
private final int accountNoTo;
/**
* Instantiates a new Money transfer event.
*
* @param sequenceId the sequence id
* @param createdTime the created time
* @param money the money
* @param accountNoFrom the account no from
* @param accountNoTo the account no to
*/
public MoneyTransferEvent(long sequenceId, long createdTime, BigDecimal money, int accountNoFrom,
int accountNoTo) {
super(sequenceId, createdTime, "MoneyTransferEvent");
this.money = money;
this.accountNoFrom = accountNoFrom;
this.accountNoTo = accountNoTo;
}
/**
* Gets money.
*
* @return the money
*/
public BigDecimal getMoney() {
return money;
}
/**
* Gets account no which the money comes from.
*
* @return the account no from
*/
public int getAccountNoFrom() {
return accountNoFrom;
}
/**
* Gets account no which the money goes to.
*
* @return the account no to
*/
public int getAccountNoTo() {
return accountNoTo;
}
@Override
public void process() {
Account accountFrom = AccountAggregate.getAccount(accountNoFrom);
if (accountFrom == null) {
throw new RuntimeException("Account not found " + accountNoFrom);
}
Account accountTo = AccountAggregate.getAccount(accountNoTo);
if (accountTo == null) {
throw new RuntimeException("Account not found" + accountTo);
}
accountFrom.handleTransferFromEvent(this);
accountTo.handleTransferToEvent(this);
}
}

View File

@ -0,0 +1,69 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.event.sourcing.processor;
import com.iluwatar.event.sourcing.event.DomainEvent;
/**
* This is the implementation of event processor.
* All events are processed by this class.
* This processor uses processorJournal to persist and recover events.
*
* Created by Serdar Hamzaogullari on 06.08.2017.
*/
public class DomainEventProcessor {
private final JsonFileJournal processorJournal = new JsonFileJournal();
/**
* Process.
*
* @param domainEvent the domain event
*/
public void process(DomainEvent domainEvent) {
domainEvent.process();
processorJournal.write(domainEvent);
}
/**
* Reset.
*/
public void reset() {
processorJournal.reset();
}
/**
* Recover.
*/
public void recover() {
DomainEvent domainEvent;
while (true) {
domainEvent = processorJournal.readNext();
if (domainEvent == null) {
break;
} else {
domainEvent.process();
}
}
}
}

View File

@ -0,0 +1,144 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.event.sourcing.processor;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.iluwatar.event.sourcing.event.AccountCreateEvent;
import com.iluwatar.event.sourcing.event.DomainEvent;
import com.iluwatar.event.sourcing.event.MoneyDepositEvent;
import com.iluwatar.event.sourcing.event.MoneyTransferEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
/**
* This is the implementation of event journal.
* This implementation serialize/deserialize the events with JSON
* and writes/reads them on a Journal.json file at the working directory.
*
* Created by Serdar Hamzaogullari on 06.08.2017.
*/
public class JsonFileJournal {
private final File aFile;
private final List<String> events = new ArrayList<>();
private int index = 0;
/**
* Instantiates a new Json file journal.
*/
public JsonFileJournal() {
aFile = new File("Journal.json");
if (aFile.exists()) {
try (BufferedReader input = new BufferedReader(
new InputStreamReader(new FileInputStream(aFile), "UTF-8"))) {
String line;
while ((line = input.readLine()) != null) {
events.add(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
reset();
}
}
/**
* Write.
*
* @param domainEvent the domain event
*/
public void write(DomainEvent domainEvent) {
Gson gson = new Gson();
JsonElement jsonElement;
if (domainEvent instanceof AccountCreateEvent) {
jsonElement = gson.toJsonTree(domainEvent, AccountCreateEvent.class);
} else if (domainEvent instanceof MoneyDepositEvent) {
jsonElement = gson.toJsonTree(domainEvent, MoneyDepositEvent.class);
} else if (domainEvent instanceof MoneyTransferEvent) {
jsonElement = gson.toJsonTree(domainEvent, MoneyTransferEvent.class);
} else {
throw new RuntimeException("Journal Event not recegnized");
}
try (Writer output = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(aFile, true), "UTF-8"))) {
String eventString = jsonElement.toString();
output.write(eventString + "\r\n");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Reset.
*/
public void reset() {
aFile.delete();
}
/**
* Read next domain event.
*
* @return the domain event
*/
public DomainEvent readNext() {
if (index >= events.size()) {
return null;
}
String event = events.get(index);
index++;
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(event);
String eventClassName = jsonElement.getAsJsonObject().get("eventClassName").getAsString();
Gson gson = new Gson();
DomainEvent domainEvent;
if (eventClassName.equals("AccountCreateEvent")) {
domainEvent = gson.fromJson(jsonElement, AccountCreateEvent.class);
} else if (eventClassName.equals("MoneyDepositEvent")) {
domainEvent = gson.fromJson(jsonElement, MoneyDepositEvent.class);
} else if (eventClassName.equals("MoneyTransferEvent")) {
domainEvent = gson.fromJson(jsonElement, MoneyTransferEvent.class);
} else {
throw new RuntimeException("Journal Event not recegnized");
}
domainEvent.setRealTime(false);
return domainEvent;
}
}

View File

@ -0,0 +1,71 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.event.sourcing.state;
import com.iluwatar.event.sourcing.domain.Account;
import java.util.HashMap;
import java.util.Map;
/**
* This is the static accounts map holder class.
* This class holds the state of the accounts.
*
* Created by Serdar Hamzaogullari on 06.08.2017.
*/
public class AccountAggregate {
private static Map<Integer, Account> accounts = new HashMap<>();
private AccountAggregate() {
}
/**
* Put account.
*
* @param account the account
*/
public static void putAccount(Account account) {
accounts.put(account.getAccountNo(), account);
}
/**
* Gets account.
*
* @param accountNo the account no
* @return the copy of the account or null if not found
*/
public static Account getAccount(int accountNo) {
Account account = accounts.get(accountNo);
if (account == null) {
return null;
}
return account.copy();
}
/**
* Reset state.
*/
public static void resetState() {
accounts = new HashMap<>();
}
}

View File

@ -0,0 +1,99 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_DAENERYS;
import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_JON;
import com.iluwatar.event.sourcing.domain.Account;
import com.iluwatar.event.sourcing.event.AccountCreateEvent;
import com.iluwatar.event.sourcing.event.MoneyDepositEvent;
import com.iluwatar.event.sourcing.event.MoneyTransferEvent;
import com.iluwatar.event.sourcing.processor.DomainEventProcessor;
import com.iluwatar.event.sourcing.state.AccountAggregate;
import java.math.BigDecimal;
import java.util.Date;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Intergartion Test for Event Sourcing state recovery
*
* Created by Serdar Hamzaogullari on 19.08.2017.
*/
public class IntegrationTest {
/**
* The Domain event processor.
*/
private DomainEventProcessor eventProcessor;
/**
* Initialize.
*/
@Before
public void initialize() {
eventProcessor = new DomainEventProcessor();
}
/**
* Test state recovery.
*/
@Test
public void testStateRecovery() {
eventProcessor.reset();
eventProcessor.process(new AccountCreateEvent(
0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen"));
eventProcessor.process(new AccountCreateEvent(
1, new Date().getTime(), ACCOUNT_OF_JON, "Jon Snow"));
eventProcessor.process(new MoneyDepositEvent(
2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000")));
eventProcessor.process(new MoneyDepositEvent(
3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100")));
eventProcessor.process(new MoneyTransferEvent(
4, new Date().getTime(), new BigDecimal("10000"), ACCOUNT_OF_DAENERYS,
ACCOUNT_OF_JON));
Account accountOfDaenerysBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS);
Account accountOfJonBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON);
AccountAggregate.resetState();
eventProcessor = new DomainEventProcessor();
eventProcessor.recover();
Account accountOfDaenerysAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS);
Account accountOfJonAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON);
Assert.assertEquals(accountOfDaenerysBeforeShotDown.getMoney(),
accountOfDaenerysAfterShotDown.getMoney());
Assert
.assertEquals(accountOfJonBeforeShotDown.getMoney(), accountOfJonAfterShotDown.getMoney());
}
}

View File

@ -143,8 +143,8 @@
<module>extension-objects</module>
<module>marker</module>
<module>cqrs</module>
<module>event-sourcing</module>
<module>data-transfer-object</module>
</modules>
<dependencyManagement>