Initial check in of Java/Scala Spring Boot example code
This commit is contained in:
29
scala-spring/build.gradle
Normal file
29
scala-spring/build.gradle
Normal file
@@ -0,0 +1,29 @@
|
||||
buildscript {
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.8.RELEASE")
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
group = "net.chrisrichardson.eventstore"
|
||||
}
|
||||
|
||||
|
||||
task wrapper(type: Wrapper) {
|
||||
gradleVersion = '2.0'
|
||||
}
|
||||
|
||||
subprojects {
|
||||
apply plugin: 'java'
|
||||
apply plugin: 'scala'
|
||||
sourceCompatibility = 1.7
|
||||
targetCompatibility = 1.7
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url "https://06c59145-4e83-4f22-93ef-6a7eee7aebaa.repos.chrisrichardson.net.s3.amazonaws.com" }
|
||||
}
|
||||
}
|
||||
23
scala-spring/eventstore-examples-main/build.gradle
Normal file
23
scala-spring/eventstore-examples-main/build.gradle
Normal file
@@ -0,0 +1,23 @@
|
||||
apply plugin: 'scala'
|
||||
apply plugin: 'spring-boot'
|
||||
|
||||
if (!hasProperty("eventstoreType")) {
|
||||
ext.eventstoreType="jdbc"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile "org.scala-lang:scala-library:2.10.2"
|
||||
compile project(":eventstore-examples")
|
||||
|
||||
compile "org.springframework.boot:spring-boot-starter-web"
|
||||
compile "org.springframework.boot:spring-boot-starter-actuator"
|
||||
|
||||
compile "net.chrisrichardson.eventstore.client:eventstore-jdbc:$eventStoreClientVersion"
|
||||
|
||||
testCompile "org.springframework.boot:spring-boot-starter-test"
|
||||
testCompile scalaTestDependency
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.web
|
||||
|
||||
import net.chrisrichardson.eventstore.embedded.config.EmbeddedEventStoreConfiguration
|
||||
import net.chrisrichardson.eventstore.examples.bank.accounts.AccountConfiguration
|
||||
import net.chrisrichardson.eventstore.examples.bank.queryside.QuerySideConfiguration
|
||||
import net.chrisrichardson.eventstore.examples.bank.transactions.TransactionConfiguration
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
|
||||
import org.springframework.context.annotation._
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@Import(Array(classOf[AccountConfiguration], classOf[TransactionConfiguration], classOf[QuerySideConfiguration], classOf[EmbeddedEventStoreConfiguration]))
|
||||
@ComponentScan
|
||||
class BankingWebAppConfiguration {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.web.accounts.controllers
|
||||
|
||||
import net.chrisrichardson.eventstore.EntityId
|
||||
import net.chrisrichardson.eventstore.EventStore
|
||||
import net.chrisrichardson.eventstore.examples.bank.accounts.{Account, AccountService}
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.web.bind.annotation._
|
||||
import scala.concurrent.ExecutionContext.Implicits.global
|
||||
|
||||
|
||||
@RestController
|
||||
class AccountController @Autowired() (accountService : AccountService, eventStore : EventStore) {
|
||||
|
||||
@RequestMapping(value=Array("/accounts"), method = Array(RequestMethod.POST))
|
||||
def create(@RequestBody request : CreateAccountRequest) = {
|
||||
val f = accountService.openAccount(request.initialBalance)
|
||||
WebUtil.toDeferredResult(f map(account => CreateAccountResponse(account.entityId.id)))
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.web.accounts.controllers
|
||||
|
||||
/**
|
||||
* Created by cer on 7/16/14.
|
||||
*/
|
||||
case class CreateAccountRequest(initialBalance : BigDecimal)
|
||||
@@ -0,0 +1,7 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.web.accounts.controllers
|
||||
|
||||
/**
|
||||
* Created by cer on 7/16/14.
|
||||
*/
|
||||
case class CreateAccountResponse(accountId : String)
|
||||
case class GetAccountResponse(accountId : String, balance : String)
|
||||
@@ -0,0 +1,23 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.web.accounts.controllers
|
||||
|
||||
import org.springframework.web.context.request.async.DeferredResult
|
||||
|
||||
import scala.concurrent.Future
|
||||
import scala.concurrent.ExecutionContext.Implicits.global
|
||||
|
||||
/**
|
||||
* Created by cer on 7/16/14.
|
||||
*/
|
||||
object WebUtil {
|
||||
def toDeferredResult[T](future: Future[T]): DeferredResult[T] = {
|
||||
val result = new DeferredResult[T]
|
||||
future onSuccess {
|
||||
case r => result.setResult(r)
|
||||
}
|
||||
future onFailure {
|
||||
case t => result.setErrorResult(t)
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.web.main
|
||||
|
||||
import net.chrisrichardson.eventstore.examples.bank.web.BankingWebAppConfiguration
|
||||
import org.springframework.boot.SpringApplication
|
||||
|
||||
object BankingMain {
|
||||
|
||||
def main(args: Array[String]) : Unit = SpringApplication.run(classOf[BankingWebAppConfiguration], args :_ *)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.web.queryside.controllers
|
||||
|
||||
import net.chrisrichardson.eventstore.EntityId
|
||||
import net.chrisrichardson.eventstore.EventStore
|
||||
import net.chrisrichardson.eventstore.examples.bank.accounts.{Account, AccountService}
|
||||
import net.chrisrichardson.eventstore.examples.bank.queryside.AccountInfoQueryService
|
||||
import net.chrisrichardson.eventstore.examples.bank.web.accounts.controllers.{GetAccountResponse, WebUtil}
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.web.bind.annotation.{PathVariable, RequestMethod, RequestMapping, RestController}
|
||||
|
||||
@RestController
|
||||
class AccountQuerySideController @Autowired() (accountInfoQueryService : AccountInfoQueryService) {
|
||||
|
||||
@RequestMapping(value=Array("/accounts/{accountId}"), method = Array(RequestMethod.GET))
|
||||
def get(@PathVariable accountId : String) = accountInfoQueryService.findByAccountId(EntityId(accountId))
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.web.transactions.controllers
|
||||
|
||||
import net.chrisrichardson.eventstore.EntityId
|
||||
import net.chrisrichardson.eventstore.examples.bank.transactions.TransferStates
|
||||
|
||||
case class CreateMoneyTransferResponse(transactionId : String)
|
||||
|
||||
case class MoneyTransferRequest(fromAccountId : EntityId, toAccountId : EntityId, amount: BigDecimal)
|
||||
|
||||
case class GetMoneyTransferResponse(transactionId : String, status : String)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.web.transactions.controllers
|
||||
|
||||
import net.chrisrichardson.eventstore.EntityId
|
||||
import net.chrisrichardson.eventstore.EventStore
|
||||
import net.chrisrichardson.eventstore.examples.bank.accounts.Account
|
||||
import net.chrisrichardson.eventstore.examples.bank.transactions.{TransferDetails, MoneyTransfer, MoneyTransferService}
|
||||
import net.chrisrichardson.eventstore.examples.bank.web.accounts.controllers.{GetAccountResponse, WebUtil}
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.web.bind.annotation._
|
||||
|
||||
import scala.concurrent.ExecutionContext.Implicits.global
|
||||
|
||||
@RestController
|
||||
class MoneyTransferController @Autowired()(moneyTransferService : MoneyTransferService,
|
||||
eventStore : EventStore) {
|
||||
|
||||
@RequestMapping(value=Array("/transfers"), method = Array(RequestMethod.POST))
|
||||
def create(@RequestBody transferDetails : TransferDetails) = WebUtil.toDeferredResult {
|
||||
for (transaction <- moneyTransferService.transferMoney(transferDetails))
|
||||
yield CreateMoneyTransferResponse(transaction.entityId.id)
|
||||
}
|
||||
|
||||
@RequestMapping(value=Array("/transfers/{transferId}"), method = Array(RequestMethod.GET))
|
||||
def get(@PathVariable transferId : String) = {
|
||||
val f = eventStore.find[MoneyTransfer](EntityId(transferId))
|
||||
WebUtil.toDeferredResult(f map(transactionAggregate => GetMoneyTransferResponse(transferId, transactionAggregate.entity.state.getClass.getSimpleName)))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.web
|
||||
|
||||
import net.chrisrichardson.eventstore.EntityId
|
||||
import net.chrisrichardson.eventstore.examples.bank.queryside.AccountInfo
|
||||
import net.chrisrichardson.eventstore.examples.bank.transactions.TransferStates
|
||||
import net.chrisrichardson.eventstore.examples.bank.web.accounts.controllers.{GetAccountResponse, CreateAccountRequest, CreateAccountResponse}
|
||||
import net.chrisrichardson.eventstore.examples.bank.web.transactions.controllers.{GetMoneyTransferResponse, MoneyTransferRequest, CreateMoneyTransferResponse}
|
||||
import org.junit.runner.RunWith
|
||||
import org.scalatest.FlatSpec
|
||||
import org.scalatest.concurrent.Eventually._
|
||||
import org.scalatest.junit.JUnitRunner
|
||||
import org.scalatest.time.{Millis, Span}
|
||||
import org.springframework.boot.SpringApplication
|
||||
import org.springframework.web.client.RestTemplate
|
||||
import org.scalatest.Matchers._
|
||||
|
||||
@RunWith(classOf[JUnitRunner])
|
||||
class BankWebIntegrationTest extends FlatSpec {
|
||||
|
||||
val sa = new SpringApplication(classOf[BankingWebAppTestConfiguration])
|
||||
val ctx = sa.run()
|
||||
|
||||
// var server = ctx.getBean(classOf[EmbeddedServletContainer])
|
||||
|
||||
val port = 8080
|
||||
|
||||
val baseUrl = s"http://localhost:$port/"
|
||||
|
||||
val restTemplate = ctx.getBean(classOf[RestTemplate])
|
||||
|
||||
implicit val reallyLongPatienceConfig = PatienceConfig(timeout = Span(10 * 1000, Millis), interval = Span(1 * 1000, Millis))
|
||||
|
||||
it should "create accounts and transfer money" in {
|
||||
|
||||
val CreateAccountResponse(fromAccountId) = restTemplate.postForEntity(s"$baseUrl/accounts", CreateAccountRequest(BigDecimal(500)), classOf[CreateAccountResponse]).getBody
|
||||
val CreateAccountResponse(toAccountId) = restTemplate.postForEntity(s"$baseUrl/accounts", CreateAccountRequest(BigDecimal(100)), classOf[CreateAccountResponse]).getBody
|
||||
|
||||
val AccountInfo(accountId, initialBalance, _, _, _) = restTemplate.getForEntity(s"$baseUrl/accounts/" + fromAccountId, classOf[AccountInfo]).getBody
|
||||
|
||||
accountId should be(fromAccountId)
|
||||
initialBalance should be(500*100)
|
||||
|
||||
val CreateMoneyTransferResponse(transactionId) = restTemplate.postForEntity(s"$baseUrl/transfers",
|
||||
MoneyTransferRequest(EntityId(fromAccountId), EntityId(toAccountId), BigDecimal(150)), classOf[CreateMoneyTransferResponse]).getBody
|
||||
|
||||
eventually {
|
||||
val AccountInfo(_, newFromAccountBalance, _, _, _) = restTemplate.getForEntity(s"$baseUrl/accounts/" + fromAccountId, classOf[AccountInfo]).getBody
|
||||
newFromAccountBalance should be(350*100)
|
||||
}(reallyLongPatienceConfig)
|
||||
eventually {
|
||||
val AccountInfo(_, newToAccountBalance, _, _, _) = restTemplate.getForEntity(s"$baseUrl/accounts/" + toAccountId, classOf[AccountInfo]).getBody
|
||||
newToAccountBalance should be(250*100)
|
||||
}(reallyLongPatienceConfig)
|
||||
|
||||
eventually {
|
||||
val GetMoneyTransferResponse(_, state) = restTemplate.getForEntity(s"$baseUrl/transfers/" + transactionId, classOf[GetMoneyTransferResponse]).getBody
|
||||
state should be("COMPLETED$")
|
||||
}(reallyLongPatienceConfig)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.web
|
||||
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
|
||||
import org.springframework.context.annotation.{Bean, Import, Configuration}
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
|
||||
import org.springframework.web.client.RestTemplate
|
||||
import scala.collection.JavaConversions._
|
||||
|
||||
@Configuration
|
||||
@Import(Array(classOf[BankingWebAppConfiguration]))
|
||||
class BankingWebAppTestConfiguration {
|
||||
|
||||
@Bean
|
||||
def restTemplate(scalaObjectMapper: ObjectMapper) = {
|
||||
val restTemplate = new RestTemplate()
|
||||
restTemplate.getMessageConverters foreach {
|
||||
case mc: MappingJackson2HttpMessageConverter =>
|
||||
mc.setObjectMapper(scalaObjectMapper)
|
||||
case _ =>
|
||||
}
|
||||
restTemplate
|
||||
}
|
||||
|
||||
}
|
||||
18
scala-spring/eventstore-examples/build.gradle
Normal file
18
scala-spring/eventstore-examples/build.gradle
Normal file
@@ -0,0 +1,18 @@
|
||||
apply plugin: 'scala'
|
||||
|
||||
dependencies {
|
||||
compile "org.scala-lang:scala-library:2.10.2"
|
||||
compile "org.springframework.boot:spring-boot-starter-data-mongodb:$springBootVersion"
|
||||
|
||||
compile "net.chrisrichardson.eventstore.common:eventstore-common:$eventStoreCommonVersion"
|
||||
compile "net.chrisrichardson.eventstore.client:eventstore-client-event-handling:$eventStoreClientVersion"
|
||||
|
||||
testCompile scalaTestDependency
|
||||
|
||||
testCompile group: 'junit', name: 'junit', version:'4.11'
|
||||
// testCompile project(":testutil")
|
||||
testCompile "net.chrisrichardson.eventstore.client:eventstore-jdbc:$eventStoreClientVersion"
|
||||
//testCompile project(path: ':eventstore-dynamodb', configuration: 'tests')
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.accounts
|
||||
|
||||
import net.chrisrichardson.eventstore.{PatternMatchingCommandProcessingAggregate, CommandProcessingAggregate}
|
||||
import net.chrisrichardson.eventstore.examples.bank.accounts.AccountCommands.AccountCommand
|
||||
|
||||
case class Account(balance : BigDecimal)
|
||||
extends PatternMatchingCommandProcessingAggregate[Account, AccountCommand] {
|
||||
|
||||
def this() = this(null)
|
||||
|
||||
import net.chrisrichardson.eventstore.examples.bank.accounts.AccountCommands._
|
||||
|
||||
|
||||
def processCommand = {
|
||||
case OpenAccountCommand(initialBalance) =>
|
||||
Seq(AccountOpenedEvent(initialBalance))
|
||||
|
||||
case CreditAccountCommand(amount, transactionId) =>
|
||||
Seq(AccountCreditedEvent(amount, transactionId))
|
||||
|
||||
case DebitAccountCommand(amount, transactionId) if amount <= balance =>
|
||||
Seq(AccountDebitedEvent(amount, transactionId))
|
||||
|
||||
case DebitAccountCommand(amount, transactionId) =>
|
||||
Seq(AccountDebitFailedDueToInsufficientFundsEvent(amount, transactionId))
|
||||
}
|
||||
|
||||
def applyEvent = {
|
||||
|
||||
case AccountOpenedEvent(initialBalance) => copy(balance = initialBalance)
|
||||
|
||||
case AccountDebitedEvent(amount, _) => copy(balance = balance - amount)
|
||||
|
||||
case AccountCreditedEvent(amount, _) =>
|
||||
copy(balance = balance + amount)
|
||||
|
||||
case AccountDebitFailedDueToInsufficientFundsEvent(amount, _) =>
|
||||
this
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.accounts
|
||||
|
||||
import net.chrisrichardson.eventstore.EntityId
|
||||
import net.chrisrichardson.eventstore.Command
|
||||
|
||||
/**
|
||||
* Created by cer on 7/16/14.
|
||||
*/
|
||||
object AccountCommands {
|
||||
|
||||
sealed trait AccountCommand extends Command
|
||||
|
||||
case class OpenAccountCommand(initialBalance : BigDecimal) extends AccountCommand
|
||||
case class DebitAccountCommand(amount : BigDecimal, transactionId : EntityId) extends AccountCommand
|
||||
case class CreditAccountCommand(amount : BigDecimal, transactionId : EntityId) extends AccountCommand
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.accounts
|
||||
|
||||
import net.chrisrichardson.eventstore.EventStore
|
||||
import net.chrisrichardson.eventstore.subscriptions.EnableEventHandlers
|
||||
import net.chrisrichardson.utils.config.MetricRegistryConfiguration
|
||||
import org.springframework.context.annotation.{Bean, Configuration, Import}
|
||||
|
||||
@Configuration
|
||||
@Import(Array(classOf[MetricRegistryConfiguration]))
|
||||
@EnableEventHandlers
|
||||
class AccountConfiguration {
|
||||
|
||||
@Bean
|
||||
def accountService(eventStore : EventStore) = new AccountService()(eventStore)
|
||||
|
||||
|
||||
@Bean
|
||||
def transferWorkflow(eventStore: EventStore): TransferWorkflowAccountHandlers = {
|
||||
new TransferWorkflowAccountHandlers(eventStore)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.accounts
|
||||
|
||||
import net.chrisrichardson.eventstore.EntityId
|
||||
import net.chrisrichardson.eventstore.Event
|
||||
|
||||
trait AccountChangedEvent extends Event {
|
||||
val amount : BigDecimal
|
||||
val transactionId : EntityId
|
||||
}
|
||||
|
||||
case class AccountOpenedEvent(initialBalance : BigDecimal) extends Event
|
||||
|
||||
case class AccountCreditedEvent(amount : BigDecimal, transactionId : EntityId) extends AccountChangedEvent
|
||||
|
||||
case class AccountDebitedEvent(amount : BigDecimal, transactionId : EntityId) extends AccountChangedEvent
|
||||
|
||||
case class AccountDebitFailedDueToInsufficientFundsEvent(amount : BigDecimal, transactionId : EntityId) extends AccountChangedEvent
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.accounts
|
||||
|
||||
import net.chrisrichardson.eventstore.EventStore
|
||||
import net.chrisrichardson.eventstore.examples.bank.accounts.AccountCommands.OpenAccountCommand
|
||||
import net.chrisrichardson.eventstore.util.ServiceUtil._
|
||||
|
||||
class AccountService(implicit eventStore : EventStore) {
|
||||
|
||||
def openAccount(initialBalance : BigDecimal) =
|
||||
newEntity[Account] <== OpenAccountCommand(initialBalance)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.accounts
|
||||
|
||||
import net.chrisrichardson.eventstore.EventStore
|
||||
import net.chrisrichardson.eventstore.examples.bank.accounts.AccountCommands.{CreditAccountCommand, DebitAccountCommand}
|
||||
import net.chrisrichardson.eventstore.examples.bank.transactions.{DebitRecordedEvent, MoneyTransferCreatedEvent}
|
||||
import net.chrisrichardson.eventstore.subscriptions.{EventSubscriber, CompoundEventHandler, EventHandlerMethod}
|
||||
import net.chrisrichardson.eventstore.util.EventHandlingUtil._
|
||||
|
||||
@EventSubscriber(id = "accountEventHandlers")
|
||||
class TransferWorkflowAccountHandlers(eventStore: EventStore) extends CompoundEventHandler {
|
||||
|
||||
implicit val es = eventStore
|
||||
|
||||
@EventHandlerMethod
|
||||
val performDebit =
|
||||
handlerForEvent[MoneyTransferCreatedEvent] { de =>
|
||||
existingEntity[Account](de.event.details.fromAccountId) <==
|
||||
DebitAccountCommand(de.event.details.amount, de.entityId)
|
||||
}
|
||||
|
||||
@EventHandlerMethod
|
||||
val performCredit = handlerForEvent[DebitRecordedEvent] { de =>
|
||||
existingEntity[Account](de.event.details.toAccountId) <== CreditAccountCommand(de.event.details.amount, de.entityId)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
@net.chrisrichardson.eventstore.EventEntity(entity="net.chrisrichardson.eventstore.examples.bank.accounts.Account")
|
||||
package net.chrisrichardson.eventstore.examples.bank.accounts;
|
||||
@@ -0,0 +1,14 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.queryside
|
||||
|
||||
import org.springframework.data.mongodb.repository.MongoRepository
|
||||
|
||||
case class AccountInfo(id : String, balance : Long,
|
||||
changes : java.util.List[AccountChangeInfo],
|
||||
transactions : java.util.List[AccountTransactionInfo],
|
||||
version : String)
|
||||
|
||||
case class AccountChangeInfo(changeId : String, transactionId : String, transactionType : String, amount : Long, balanceDelta: Long)
|
||||
|
||||
case class AccountTransactionInfo(transactionId : String, fromAccountId: String, toAccountId: String, amount : Long)
|
||||
|
||||
trait AccountInfoRepository extends MongoRepository[AccountInfo, String]
|
||||
@@ -0,0 +1,9 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.queryside
|
||||
|
||||
import net.chrisrichardson.eventstore.EntityId
|
||||
|
||||
class AccountInfoQueryService(accountInfoRepository : AccountInfoRepository) {
|
||||
|
||||
def findByAccountId(accountId : EntityId) : AccountInfo = accountInfoRepository.findOne(accountId.id)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.queryside
|
||||
|
||||
import net.chrisrichardson.eventstore.EntityId
|
||||
import net.chrisrichardson.eventstore.Event
|
||||
import net.chrisrichardson.eventstore.Event.EventId
|
||||
import net.chrisrichardson.eventstore.examples.bank.transactions.{MoneyTransferCreatedEvent, MoneyTransferCommands}
|
||||
import MoneyTransferCommands.RecordCreditCommand
|
||||
import net.chrisrichardson.eventstore.examples.bank._
|
||||
import net.chrisrichardson.eventstore.examples.bank.accounts._
|
||||
import net.chrisrichardson.eventstore.subscriptions.{EventSubscriber, DispatchedEvent, EventHandlerMethod, CompoundEventHandler}
|
||||
import net.chrisrichardson.eventstore.util.ServiceUtil._
|
||||
import net.chrisrichardson.utils.logging.Logging
|
||||
import org.springframework.data.mongodb.core.MongoTemplate
|
||||
|
||||
import scala.collection.JavaConversions._
|
||||
|
||||
import org.springframework.data.mongodb.core.query.Criteria.where
|
||||
import org.springframework.data.mongodb.core.query.Query
|
||||
import org.springframework.data.mongodb.core.query.Update
|
||||
import scala.concurrent.ExecutionContext.Implicits.global
|
||||
|
||||
import scala.concurrent.Future
|
||||
|
||||
@EventSubscriber (id = "querySideEventHandlers")
|
||||
class AccountInfoUpdateService(accountInfoRepository : AccountInfoRepository, mongoTemplate : MongoTemplate) extends CompoundEventHandler with Logging {
|
||||
|
||||
|
||||
@EventHandlerMethod
|
||||
def created(de: DispatchedEvent[AccountOpenedEvent]) = Future {
|
||||
logger.info("About to save")
|
||||
try {
|
||||
|
||||
accountInfoRepository.save(AccountInfo(de.entityId.id, toIntegerRepr(de.event.initialBalance), Seq(), Seq(), de.eventId.asString))
|
||||
}
|
||||
catch {
|
||||
case t : Throwable =>
|
||||
logger.error("Error during saving: ")
|
||||
logger.error("Error during saving: ", t)
|
||||
throw t
|
||||
}
|
||||
logger.info("Saved in mongo")
|
||||
}
|
||||
|
||||
@EventHandlerMethod
|
||||
def recordDebit(de: DispatchedEvent[AccountDebitedEvent]) = saveChange(de, -1)
|
||||
|
||||
@EventHandlerMethod
|
||||
def recordCredit(de: DispatchedEvent[AccountCreditedEvent]) = saveChange(de, +1)
|
||||
|
||||
@EventHandlerMethod
|
||||
def recordDebitFailed(de: DispatchedEvent[AccountDebitFailedDueToInsufficientFundsEvent]) = saveChange(de, 0)
|
||||
|
||||
def toIntegerRepr(d : BigDecimal) = (d * 100).toLong
|
||||
def saveChange[T <: AccountChangedEvent](de : DispatchedEvent[T], delta : Int) = Future {
|
||||
val changeId = de.eventId.asString
|
||||
val transactionId = de.event.transactionId.id
|
||||
val amount = toIntegerRepr(de.event.amount)
|
||||
|
||||
val ci= AccountChangeInfo(changeId, transactionId, de.event.getClass.getSimpleName, amount, amount * delta)
|
||||
|
||||
mongoTemplate.updateMulti(new Query(where("id").is(de.entityId.id).and("version").lt(changeId)),
|
||||
new Update().
|
||||
inc("balance", amount * delta).
|
||||
push("changes", ci).
|
||||
set("version", changeId),
|
||||
classOf[AccountInfo])
|
||||
}
|
||||
|
||||
@EventHandlerMethod
|
||||
def recordTransfer(de: DispatchedEvent[MoneyTransferCreatedEvent]) = Future {
|
||||
val eventId = de.eventId.asString
|
||||
val fromAccountId = de.event.details.fromAccountId.id
|
||||
val toAccountId = de.event.details.toAccountId.id
|
||||
|
||||
val ti = AccountTransactionInfo(de.entityId.id, fromAccountId, toAccountId, toIntegerRepr(de.event.details.amount))
|
||||
|
||||
mongoTemplate.updateMulti(new Query(where("id").is(fromAccountId).and("version").lt(eventId)),
|
||||
new Update().
|
||||
push("transactions", ti).
|
||||
set("version", eventId),
|
||||
classOf[AccountInfo])
|
||||
|
||||
mongoTemplate.updateMulti(new Query(where("id").is(toAccountId).and("version").lt(eventId)),
|
||||
new Update().
|
||||
push("transactions", ti).
|
||||
set("version", eventId),
|
||||
classOf[AccountInfo])
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.queryside
|
||||
|
||||
import org.springframework.context.annotation.{Bean, Configuration}
|
||||
import org.springframework.data.mongodb.core.MongoTemplate
|
||||
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories
|
||||
|
||||
@Configuration
|
||||
@EnableMongoRepositories
|
||||
class QuerySideConfiguration {
|
||||
|
||||
@Bean
|
||||
def accountUpdateService(accountInfoRepository: AccountInfoRepository, mongoTemplate: MongoTemplate): AccountInfoUpdateService =
|
||||
new AccountInfoUpdateService(accountInfoRepository, mongoTemplate)
|
||||
|
||||
@Bean
|
||||
def accountInfoQueryService(accountInfoRepository : AccountInfoRepository) = new AccountInfoQueryService(accountInfoRepository)
|
||||
|
||||
@Bean
|
||||
def querysideDependencyChecker(mongoTemplate : MongoTemplate) = new QuerysideDependencyChecker(mongoTemplate)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.queryside
|
||||
|
||||
import javax.annotation.PostConstruct
|
||||
|
||||
import net.chrisrichardson.utils.logging.Logging
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.data.mongodb.core.MongoTemplate
|
||||
|
||||
import scala.concurrent.{TimeoutException, Await, Future}
|
||||
import scala.concurrent.duration._
|
||||
import scala.concurrent.ExecutionContext.Implicits.global
|
||||
|
||||
class QuerysideDependencyChecker (mongoTemplate : MongoTemplate) extends Logging {
|
||||
|
||||
@PostConstruct
|
||||
def checkDependencies(): Unit = {
|
||||
try {
|
||||
Await.result(Future { mongoTemplate.getDb.getCollectionNames}, 5 seconds)
|
||||
} catch {
|
||||
case e : Throwable =>
|
||||
logger.error("Error connecting to Mongo - have you set SPRING_DATA_MONGODB_URI or --spring.data.mongodb_uri?", e)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.transactions
|
||||
|
||||
import net.chrisrichardson.eventstore.{PatternMatchingCommandProcessingAggregate, EntityId, CommandProcessingAggregate}
|
||||
import net.chrisrichardson.eventstore.examples.bank.transactions.MoneyTransferCommands.MoneyTransferCommand
|
||||
|
||||
object TransferStates {
|
||||
sealed trait State
|
||||
object NEW extends State
|
||||
object INITIAL extends State
|
||||
object DEBITED extends State
|
||||
object COMPLETED extends State
|
||||
object FAILED_DUE_TO_INSUFFICIENT_FUNDS extends State
|
||||
}
|
||||
|
||||
|
||||
|
||||
case class MoneyTransfer(state : TransferStates.State, details : TransferDetails)
|
||||
extends PatternMatchingCommandProcessingAggregate[MoneyTransfer, MoneyTransferCommand] {
|
||||
|
||||
def this() = this(TransferStates.NEW, null)
|
||||
|
||||
import net.chrisrichardson.eventstore.examples.bank.transactions.MoneyTransferCommands._
|
||||
|
||||
def processCommand = {
|
||||
case CreateMoneyTransferCommand(withDetails) if state == TransferStates.NEW =>
|
||||
Seq(MoneyTransferCreatedEvent(withDetails))
|
||||
|
||||
case RecordDebitCommand(accountId) if state == TransferStates.INITIAL && accountId == details.fromAccountId =>
|
||||
Seq(DebitRecordedEvent(details))
|
||||
|
||||
case RecordDebitFailedDueToInsufficientFundsCommand(accountId) if state == TransferStates.INITIAL && accountId == details.fromAccountId =>
|
||||
Seq(TransferFailedDueToInsufficientFundsEvent())
|
||||
|
||||
case RecordCreditCommand(accountId) if state == TransferStates.DEBITED && accountId == details.toAccountId =>
|
||||
Seq(CreditRecordedEvent(details))
|
||||
}
|
||||
|
||||
def applyEvent = {
|
||||
|
||||
case MoneyTransferCreatedEvent(withDetails) => copy(state=TransferStates.INITIAL, details=withDetails)
|
||||
case DebitRecordedEvent(_) => copy(state=TransferStates.DEBITED)
|
||||
case TransferFailedDueToInsufficientFundsEvent() => copy(state=TransferStates.FAILED_DUE_TO_INSUFFICIENT_FUNDS)
|
||||
case CreditRecordedEvent(_) => copy(state=TransferStates.COMPLETED)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.transactions
|
||||
|
||||
import net.chrisrichardson.eventstore.EntityId
|
||||
import net.chrisrichardson.eventstore.Command
|
||||
|
||||
object MoneyTransferCommands {
|
||||
|
||||
sealed trait MoneyTransferCommand extends Command
|
||||
|
||||
case class CreateMoneyTransferCommand(details : TransferDetails) extends MoneyTransferCommand
|
||||
case class RecordDebitCommand(accountId : EntityId) extends MoneyTransferCommand
|
||||
case class RecordDebitFailedDueToInsufficientFundsCommand(accountId : EntityId) extends MoneyTransferCommand
|
||||
case class RecordCreditCommand(accountId : EntityId) extends MoneyTransferCommand
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.transactions
|
||||
|
||||
import net.chrisrichardson.eventstore.EventStore
|
||||
import net.chrisrichardson.eventstore.examples.bank.accounts._
|
||||
import net.chrisrichardson.eventstore.examples.bank.transactions.MoneyTransferCommands.{RecordCreditCommand, RecordDebitCommand, RecordDebitFailedDueToInsufficientFundsCommand}
|
||||
import net.chrisrichardson.eventstore.subscriptions.{EventSubscriber, CompoundEventHandler, DispatchedEvent, EventHandlerMethod}
|
||||
import net.chrisrichardson.eventstore.util.EventHandlingUtil._
|
||||
|
||||
@EventSubscriber (id = "transactionEventHandlers")
|
||||
class MoneyTransferEventHandlers(implicit eventStore: EventStore)
|
||||
extends CompoundEventHandler {
|
||||
|
||||
val recordDebit =
|
||||
handlerForEvent[AccountDebitedEvent] { de =>
|
||||
existingEntity[MoneyTransfer](de.event.transactionId) <==
|
||||
RecordDebitCommand(de.entityId)
|
||||
}
|
||||
|
||||
val recordCredit =
|
||||
handlerForEvent[AccountCreditedEvent] { de =>
|
||||
existingEntity[MoneyTransfer](de.event.transactionId) <==
|
||||
RecordCreditCommand(de.entityId)
|
||||
}
|
||||
|
||||
val recordDebitFailed =
|
||||
handlerForEvent[AccountDebitFailedDueToInsufficientFundsEvent] { de =>
|
||||
existingEntity[MoneyTransfer](de.event.transactionId) <==
|
||||
RecordDebitFailedDueToInsufficientFundsCommand(de.entityId)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.transactions
|
||||
|
||||
import net.chrisrichardson.eventstore.EventStore
|
||||
import net.chrisrichardson.eventstore.examples.bank.transactions.MoneyTransferCommands.CreateMoneyTransferCommand
|
||||
import net.chrisrichardson.eventstore.util.ServiceUtil._
|
||||
|
||||
class MoneyTransferService(implicit eventStore : EventStore) {
|
||||
|
||||
def transferMoney(transferDetails : TransferDetails) =
|
||||
newEntity[MoneyTransfer] <== CreateMoneyTransferCommand(transferDetails)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.transactions
|
||||
|
||||
import net.chrisrichardson.eventstore.EventStore
|
||||
import net.chrisrichardson.eventstore.subscriptions.EnableEventHandlers
|
||||
import org.springframework.context.annotation.{Bean, Configuration}
|
||||
|
||||
@Configuration
|
||||
@EnableEventHandlers
|
||||
class TransactionConfiguration {
|
||||
|
||||
@Bean
|
||||
def accountTransactionService(eventStore : EventStore) = new MoneyTransferService()(eventStore)
|
||||
|
||||
@Bean
|
||||
def moneyTransferWorkflow(eventStore: EventStore): MoneyTransferEventHandlers = {
|
||||
new MoneyTransferEventHandlers()(eventStore)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.transactions
|
||||
|
||||
import net.chrisrichardson.eventstore.EntityId
|
||||
import net.chrisrichardson.eventstore.Event
|
||||
|
||||
case class MoneyTransferCreatedEvent(details : TransferDetails) extends Event
|
||||
case class DebitRecordedEvent(details : TransferDetails) extends Event
|
||||
case class CreditRecordedEvent(details : TransferDetails) extends Event
|
||||
case class TransferFailedDueToInsufficientFundsEvent() extends Event
|
||||
@@ -0,0 +1,5 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.transactions
|
||||
|
||||
import net.chrisrichardson.eventstore.EntityId
|
||||
|
||||
case class TransferDetails(fromAccountId : EntityId, toAccountId : EntityId, amount : BigDecimal)
|
||||
@@ -0,0 +1,2 @@
|
||||
@net.chrisrichardson.eventstore.EventEntity(entity="net.chrisrichardson.eventstore.examples.bank.transactions.MoneyTransfer")
|
||||
package net.chrisrichardson.eventstore.examples.bank.transactions;
|
||||
@@ -0,0 +1,35 @@
|
||||
package net.chrisrichardson.eventstore.examples.customersandorders.customers
|
||||
|
||||
import net.chrisrichardson.eventstore.{PatternMatchingCommandProcessingAggregate, Command, CommandProcessingAggregate, Event}
|
||||
import CustomerCommands._
|
||||
|
||||
case class Customer(customerId: String, creditLimit: BigDecimal)
|
||||
extends PatternMatchingCommandProcessingAggregate[Customer, CustomerCommand] {
|
||||
|
||||
|
||||
def this() = this(null, null)
|
||||
|
||||
override def processCommand = {
|
||||
case CreateCustomer(customerId, creditLimit) => Seq(CustomerCreatedEvent(customerId, creditLimit))
|
||||
case UpdateCreditLimit(newLimit) if newLimit >= 0 => Seq(CustomerCreditLimitUpdatedEvent(newLimit))
|
||||
}
|
||||
|
||||
override def applyEvent = {
|
||||
|
||||
case CustomerCreatedEvent(customerId, creditLimit) => copy(customerId=customerId, creditLimit=creditLimit)
|
||||
case CustomerCreditLimitUpdatedEvent(newLimit) => copy(creditLimit=newLimit)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
object CustomerCommands {
|
||||
|
||||
trait CustomerCommand extends Command
|
||||
|
||||
case class CreateCustomer(customerId : String, creditLimit : BigDecimal) extends CustomerCommand
|
||||
case class UpdateCreditLimit(newLimit: BigDecimal) extends CustomerCommand
|
||||
|
||||
}
|
||||
|
||||
case class CustomerCreatedEvent(customerId : String, creditLimit : BigDecimal) extends Event
|
||||
case class CustomerCreditLimitUpdatedEvent(newLimit: BigDecimal) extends Event
|
||||
@@ -0,0 +1,41 @@
|
||||
package net.chrisrichardson.eventstore.examples.customersandorders.orders
|
||||
|
||||
import net.chrisrichardson.eventstore.examples.customersandorders.orders.OrderCommands.OrderCommand
|
||||
import net.chrisrichardson.eventstore.{PatternMatchingCommandProcessingAggregate, Command, CommandProcessingAggregate, Event}
|
||||
|
||||
case class Order(orderId: String, orderTotal: BigDecimal, state : OrderState)
|
||||
extends PatternMatchingCommandProcessingAggregate[Order, OrderCommand] {
|
||||
|
||||
import OrderCommands._
|
||||
|
||||
def this() = this(null, null, null)
|
||||
|
||||
override def processCommand = {
|
||||
case CreateOrder(orderId, orderTotal) => Seq(OrderCreatedEvent(orderId, orderTotal))
|
||||
case PayForOrder(orderId) => Seq(OrderPaidEvent(orderId))
|
||||
}
|
||||
|
||||
override def applyEvent = {
|
||||
|
||||
case OrderCreatedEvent(orderId, orderTotal) => copy(orderId=orderId, orderTotal=orderTotal, state=OPEN)
|
||||
case OrderPaidEvent(orderId) => copy(orderId=orderId, orderTotal=orderTotal, state=PAID)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
trait OrderState
|
||||
object OPEN extends OrderState
|
||||
object PAID extends OrderState
|
||||
|
||||
object OrderCommands {
|
||||
|
||||
trait OrderCommand extends Command
|
||||
|
||||
case class CreateOrder(orderId : String, orderTotal : BigDecimal) extends OrderCommand
|
||||
case class PayForOrder(orderId : String) extends OrderCommand
|
||||
|
||||
}
|
||||
|
||||
case class OrderCreatedEvent(orderId : String, creditLimit : BigDecimal) extends Event
|
||||
case class OrderPaidEvent(orderId : String) extends Event
|
||||
@@ -0,0 +1,62 @@
|
||||
package net.chrisrichardson.eventstore.examples.customersandorders.orders
|
||||
|
||||
import net.chrisrichardson.eventstore.examples.customersandorders.orders.OrderCustomerCommands.OrderCustomerCommand
|
||||
import net.chrisrichardson.eventstore.{PatternMatchingCommandProcessingAggregate, Command, CommandProcessingAggregate, Event}
|
||||
|
||||
|
||||
case class OrderCustomer(customerId: String, creditLimit: BigDecimal,
|
||||
openOrderTotal : BigDecimal,
|
||||
openOrders : Set[String] = Set(),
|
||||
paidOrders : Set[String] = Set())
|
||||
|
||||
extends PatternMatchingCommandProcessingAggregate[OrderCustomer, OrderCustomerCommand] {
|
||||
|
||||
import OrderCustomerCommands._
|
||||
|
||||
def this() = this(null, null, null)
|
||||
|
||||
|
||||
override def processCommand = {
|
||||
case CreateOrderCustomer(customerId, creditLimit) => Seq(OrderCustomerCreatedEvent(customerId, creditLimit))
|
||||
case UpdateCreditLimit(newLimit) => Seq(OrderCustomerCreditLimitUpdatedEvent(newLimit))
|
||||
|
||||
case RecordNewOrder(orderId, orderTotal) if !openOrders.contains(orderId) && !paidOrders.contains(orderId) =>
|
||||
Seq(NewOrderRecorded(orderId), OpenOrderTotalUpdated(openOrderTotal + orderTotal))
|
||||
|
||||
case _ : RecordNewOrder => Seq()
|
||||
|
||||
case RecordPaidOrder(orderId, orderTotal) if openOrders.contains(orderId) && !paidOrders.contains(orderId) =>
|
||||
Seq(PaidOrderRecorded(orderId), OpenOrderTotalUpdated(openOrderTotal - orderTotal))
|
||||
|
||||
case _ : PaidOrderRecorded => Seq()
|
||||
}
|
||||
|
||||
override def applyEvent = {
|
||||
|
||||
case OrderCustomerCreatedEvent(customerId, creditLimit) => copy(customerId=customerId, creditLimit=creditLimit, openOrderTotal=0)
|
||||
case OrderCustomerCreditLimitUpdatedEvent(newLimit) => copy(creditLimit=newLimit)
|
||||
|
||||
case NewOrderRecorded(orderId) => copy(openOrders=openOrders + orderId)
|
||||
case PaidOrderRecorded(orderId) => copy(paidOrders=paidOrders + orderId, openOrders=openOrders - orderId)
|
||||
|
||||
case OpenOrderTotalUpdated(orderTotal) => copy(openOrderTotal=orderTotal)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
object OrderCustomerCommands {
|
||||
|
||||
trait OrderCustomerCommand extends Command
|
||||
|
||||
case class CreateOrderCustomer(customerId : String, creditLimit : BigDecimal) extends OrderCustomerCommand
|
||||
case class UpdateCreditLimit(newLimit: BigDecimal) extends OrderCustomerCommand
|
||||
case class RecordNewOrder(orderId : String, orderTotal : BigDecimal) extends OrderCustomerCommand
|
||||
case class RecordPaidOrder(orderId : String, orderTotal : BigDecimal) extends OrderCustomerCommand
|
||||
|
||||
}
|
||||
|
||||
case class OrderCustomerCreatedEvent(customerId : String, creditLimit : BigDecimal) extends Event
|
||||
case class OrderCustomerCreditLimitUpdatedEvent(newLimit: BigDecimal) extends Event
|
||||
case class NewOrderRecorded(orderId : String) extends Event
|
||||
case class PaidOrderRecorded(orderId : String) extends Event
|
||||
case class OpenOrderTotalUpdated(orderTotal: BigDecimal) extends Event
|
||||
@@ -0,0 +1,99 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank
|
||||
|
||||
import net.chrisrichardson.eventstore.EventStore
|
||||
import net.chrisrichardson.eventstore.examples.bank.accounts.{AccountService, AccountDebitedEvent, Account}
|
||||
import net.chrisrichardson.eventstore.examples.bank.config.BankingTestConfiguration
|
||||
import net.chrisrichardson.eventstore.examples.bank.queryside.AccountInfoQueryService
|
||||
import net.chrisrichardson.eventstore.examples.bank.transactions.{TransferDetails, MoneyTransferService, MoneyTransfer, TransferStates}
|
||||
import net.chrisrichardson.eventstore.jdbc.config.JdbcEventStoreConfiguration
|
||||
import org.junit.runner.RunWith
|
||||
import org.scalatest.FlatSpec
|
||||
import org.scalatest.junit.JUnitRunner
|
||||
import org.scalatest.time.{Millis, Span}
|
||||
import org.springframework.context.annotation.Import
|
||||
|
||||
import scala.concurrent.{Await, Future}
|
||||
import scala.concurrent.duration._
|
||||
import org.scalatest.concurrent.Eventually._
|
||||
import org.scalatest.Matchers._
|
||||
import scala.collection.JavaConversions._
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext
|
||||
import scala.reflect.ClassTag
|
||||
|
||||
trait SpringTest {
|
||||
def configClasses : Seq[Class[_]]
|
||||
val ctx = new AnnotationConfigApplicationContext(configClasses :_ *)
|
||||
def bean[T](implicit m : ClassTag[T]) : T = ctx.getBean(m.runtimeClass).asInstanceOf[T]
|
||||
def bean[T](name : String)(implicit m : ClassTag[T]) : T = ctx.getBean(name, m.runtimeClass).asInstanceOf[T]
|
||||
|
||||
}
|
||||
|
||||
|
||||
@RunWith(classOf[JUnitRunner])
|
||||
class MoneyTransferIntegrationTest extends FlatSpec with SpringTest {
|
||||
|
||||
def configClasses = Seq(classOf[BankingTestConfiguration])
|
||||
|
||||
val accountService = bean[AccountService]
|
||||
val transactionService = bean[MoneyTransferService]
|
||||
val eventStore = bean[EventStore]
|
||||
val accountInfoQueryService = bean[AccountInfoQueryService]
|
||||
|
||||
def await[T](body : => Future[T]) = Await.result(body, 500 milliseconds)
|
||||
|
||||
val longWait = PatienceConfig(Span(5000, Millis), Span(50, Millis))
|
||||
|
||||
|
||||
it should "transfer money" in {
|
||||
val account1 = await { accountService.openAccount(BigDecimal(150)) }
|
||||
val account2 = await { accountService.openAccount(BigDecimal(300)) }
|
||||
|
||||
val transaction = await { transactionService.transferMoney(TransferDetails(account1.entityId, account2.entityId, BigDecimal(80))) }
|
||||
|
||||
eventually {
|
||||
val updatedTransaction = await { eventStore.find[MoneyTransfer](transaction.entityId)}
|
||||
updatedTransaction.entity.state should be(TransferStates.COMPLETED)
|
||||
}(longWait)
|
||||
|
||||
eventually {
|
||||
val updatedAccount1 = await { eventStore.find[Account](account1.entityId) }
|
||||
updatedAccount1.entity.balance should be(70)
|
||||
}(longWait)
|
||||
|
||||
eventually {
|
||||
val updatedAccount2 = await { eventStore.find[Account](account2.entityId) }
|
||||
updatedAccount2.entity.balance should be(380)
|
||||
}(longWait)
|
||||
|
||||
eventually {
|
||||
val accountInfo = accountInfoQueryService.findByAccountId(account1.entityId)
|
||||
accountInfo.balance should be(70*100)
|
||||
accountInfo.changes.map(_.transactionType) should be(Seq(classOf[AccountDebitedEvent].getSimpleName))
|
||||
}(longWait)
|
||||
|
||||
}
|
||||
|
||||
it should "fail to transfer money due to insufficient funds" in {
|
||||
val account1 = await { accountService.openAccount(BigDecimal(150)) }
|
||||
val account2 = await { accountService.openAccount(BigDecimal(300)) }
|
||||
|
||||
val transaction = await { transactionService.transferMoney(TransferDetails(account1.entityId, account2.entityId, BigDecimal(200))) }
|
||||
|
||||
eventually {
|
||||
val updatedTransaction = await { eventStore.find[MoneyTransfer](transaction.entityId)}
|
||||
updatedTransaction.entity.state should be(TransferStates.FAILED_DUE_TO_INSUFFICIENT_FUNDS)
|
||||
}(longWait)
|
||||
|
||||
eventually {
|
||||
val updatedAccount1 = await { eventStore.find[Account](account1.entityId) }
|
||||
updatedAccount1.entity.balance should be(150)
|
||||
}(longWait)
|
||||
|
||||
eventually {
|
||||
val updatedAccount2 = await { eventStore.find[Account](account2.entityId) }
|
||||
updatedAccount2.entity.balance should be(300)
|
||||
}(longWait)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package net.chrisrichardson.eventstore.examples.bank.config
|
||||
|
||||
import net.chrisrichardson.eventstore.examples.bank.accounts.AccountConfiguration
|
||||
import net.chrisrichardson.eventstore.examples.bank.queryside.QuerySideConfiguration
|
||||
import net.chrisrichardson.eventstore.examples.bank.transactions.TransactionConfiguration
|
||||
import net.chrisrichardson.eventstore.jdbc.config.JdbcEventStoreConfiguration
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
|
||||
import org.springframework.context.annotation.{Import, Configuration}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@Import(Array(classOf[JdbcEventStoreConfiguration], classOf[AccountConfiguration], classOf[TransactionConfiguration], classOf[QuerySideConfiguration]))
|
||||
class BankingTestConfiguration {
|
||||
|
||||
}
|
||||
17
scala-spring/gradle.properties
Normal file
17
scala-spring/gradle.properties
Normal file
@@ -0,0 +1,17 @@
|
||||
|
||||
org.gradle.jvmargs=-XX:MaxPermSize=512m
|
||||
# Was 3.2.4.RELEASE
|
||||
springFrameworkVersion=4.0.3.RELEASE
|
||||
#rxJavaVersion=0.13.2
|
||||
rxJavaVersion=0.20.4
|
||||
|
||||
scalaTestDependency=org.scalatest:scalatest_2.10:2.0
|
||||
|
||||
akkaDependency=com.typesafe.akka:akka-actor_2.10:2.3.4
|
||||
akkaTestDependency=com.typesafe.akka:akka-actor-tests_2.10:2.3.4
|
||||
akkaSlf4jDependency=com.typesafe.akka:akka-slf4j_2.10:2.3.4
|
||||
|
||||
springBootVersion=1.1.10.RELEASE
|
||||
|
||||
eventStoreCommonVersion=0.2
|
||||
eventStoreClientVersion=0.2
|
||||
BIN
scala-spring/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
scala-spring/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
6
scala-spring/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
6
scala-spring/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
#Wed Oct 29 07:09:05 PDT 2014
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=http\://services.gradle.org/distributions/gradle-2.0-bin.zip
|
||||
164
scala-spring/gradlew
vendored
Executable file
164
scala-spring/gradlew
vendored
Executable file
@@ -0,0 +1,164 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS=""
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn ( ) {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die ( ) {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
esac
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched.
|
||||
if $cygwin ; then
|
||||
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
fi
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >&-
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >&-
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=$((i+1))
|
||||
done
|
||||
case $i in
|
||||
(0) set -- ;;
|
||||
(1) set -- "$args0" ;;
|
||||
(2) set -- "$args0" "$args1" ;;
|
||||
(3) set -- "$args0" "$args1" "$args2" ;;
|
||||
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
|
||||
function splitJvmOpts() {
|
||||
JVM_OPTS=("$@")
|
||||
}
|
||||
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
|
||||
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
|
||||
|
||||
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
|
||||
90
scala-spring/gradlew.bat
vendored
Normal file
90
scala-spring/gradlew.bat
vendored
Normal file
@@ -0,0 +1,90 @@
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS=
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windowz variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
if "%@eval[2+2]" == "4" goto 4NT_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
goto execute
|
||||
|
||||
:4NT_args
|
||||
@rem Get arguments from the 4NT Shell from JP Software
|
||||
set CMD_LINE_ARGS=%$
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
5
scala-spring/settings.gradle
Normal file
5
scala-spring/settings.gradle
Normal file
@@ -0,0 +1,5 @@
|
||||
include 'eventstore-examples'
|
||||
include 'eventstore-examples-main'
|
||||
include 'eventstore-examples-java'
|
||||
include 'eventstore-examples-java-web'
|
||||
include 'eventstore-examples-java-testutil'
|
||||
Reference in New Issue
Block a user