├── .gitignore ├── project ├── build.properties └── plugins.sbt ├── .travis.yml ├── src ├── main │ ├── scala │ │ └── vending │ │ │ ├── Symbols.scala │ │ │ ├── SystemReportsActor.scala │ │ │ ├── UserOutputsActor.scala │ │ │ ├── SmActor.scala │ │ │ ├── SmPersistentActor.scala │ │ │ ├── Domain.scala │ │ │ ├── package.scala │ │ │ ├── VendingMachineDemo.scala │ │ │ ├── BaseVendingMachineActor.scala │ │ │ └── VendingMachineSm.scala │ └── resources │ │ └── application.conf └── test │ ├── resources │ └── application.conf │ └── scala │ └── vending │ ├── SmActorTest.scala │ ├── BaseVendingMachineActorTest.scala │ ├── SmPersistentActorTest.scala │ ├── BaseActorTest.scala │ └── VendingMachineSmTest.scala ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | .idea/ 3 | target/ 4 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.2.6 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("de.heikoseeberger" % "sbt-groll" % "6.1.0") -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: scala 2 | os: 3 | - linux 4 | script: 5 | - sbt clean test 6 | scala: 7 | - 2.12.7 8 | 9 | -------------------------------------------------------------------------------- /src/main/scala/vending/Symbols.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | object Symbols { 4 | val candy = "\uD83C\uDF6C" 5 | val pizza = "\uD83C\uDF55" 6 | val banana = "\uD83C\uDF4C" 7 | val beer = "\uD83C\uDF7A" 8 | } 9 | -------------------------------------------------------------------------------- /src/test/resources/application.conf: -------------------------------------------------------------------------------- 1 | akka { 2 | log-dead-letters = 10 3 | log-dead-letters-during-shutdown = on 4 | } 5 | 6 | akka { 7 | persistence { 8 | journal.plugin = "inmemory-journal" 9 | snapshot-store.plugin = "inmemory-snapshot-store" 10 | } 11 | } 12 | akka.actor.warn-about-java-serializer-usage = false -------------------------------------------------------------------------------- /src/test/scala/vending/SmActorTest.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | import akka.actor.{ActorRef, Props} 4 | 5 | class SmActorTest extends BaseActorTest { 6 | override def createActor(quantity: Map[Domain.Product, Int], 7 | userOutputActor: ActorRef, 8 | reportsActor: ActorRef 9 | ): ActorRef = 10 | system.actorOf(Props(new SmActor(quantity, userOutputActor, reportsActor))) 11 | } 12 | -------------------------------------------------------------------------------- /src/test/scala/vending/BaseVendingMachineActorTest.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | import akka.actor.{ActorRef, Props} 4 | 5 | class BaseVendingMachineActorTest extends BaseActorTest { 6 | override def createActor(quantity: Map[Domain.Product, Int], 7 | userOutputActor: ActorRef, 8 | reportsActor: ActorRef 9 | ): ActorRef = 10 | system.actorOf(Props(new BaseVendingMachineActor(quantity, userOutputActor, reportsActor))) 11 | } 12 | -------------------------------------------------------------------------------- /src/test/scala/vending/SmPersistentActorTest.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | import java.util.UUID 4 | 5 | import akka.actor.{ActorRef, Props} 6 | 7 | class SmPersistentActorTest extends BaseActorTest { 8 | override def createActor(quantity: Map[Domain.Product, Int], 9 | userOutputActor: ActorRef, 10 | reportsActor: ActorRef 11 | ): ActorRef = 12 | system.actorOf(Props(new SmPersistentActor(UUID.randomUUID().toString)(quantity, userOutputActor, reportsActor))) 13 | } 14 | -------------------------------------------------------------------------------- /src/main/resources/application.conf: -------------------------------------------------------------------------------- 1 | akka { 2 | log-dead-letters = 10 3 | log-dead-letters-during-shutdown = on 4 | } 5 | 6 | akka.persistence.journal.plugin = "akka.persistence.journal.leveldb" 7 | akka.persistence.snapshot-store.plugin = "akka.persistence.snapshot-store.local" 8 | 9 | akka.persistence.journal.leveldb.dir = "target/example/journal" 10 | akka.persistence.snapshot-store.local.dir = "target/example/snapshots" 11 | 12 | # DO NOT USE THIS IN PRODUCTION !!! 13 | # See also https://github.com/typesafehub/activator/issues/287 14 | akka.persistence.journal.leveldb.native = false 15 | akka.actor.warn-about-java-serializer-usage = false -------------------------------------------------------------------------------- /src/main/scala/vending/SystemReportsActor.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | import akka.actor.Actor 4 | import vending.Domain._ 5 | 6 | class SystemReportsActor extends Actor { 7 | override def receive: Receive = { 8 | case ProductShortage(product) => 9 | println(s" We are short of ${product.symbol}".inBox()) 10 | case MoneyBoxAlmostFull(amount) => 11 | println(s" We have ${amount}PLN in money box! Come and collect your profit!".inBox()) 12 | case ExpiredProducts(products) => 13 | println(s" Following products will soon expire: ${products.map(_.symbol)}".inBox()) 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/scala/vending/UserOutputsActor.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | import akka.actor.Actor 4 | import vending.Domain._ 5 | 6 | class UserOutputsActor extends Actor { 7 | override def receive: Receive = { 8 | case CreditInfo(value) => println(s" Your credit is $value".inBox()) 9 | case CollectYourMoney => println(" Collect your money".inBox()) 10 | case WrongProduct => println(" Wrong product, select again".inBox()) 11 | case NotEnoughOfCredit(diff) => println(s" Not enough of credit, insert $diff".inBox()) 12 | case OutOfStock(product) => println(s" We are out of stock of ${product.symbol}, select different one".inBox()) 13 | case GiveProductAndChange(product, change) => 14 | println(s" Here is your ${product.symbol} and ${change}PLN of change".inBox()) 15 | case Display(s) => println(s) 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/scala/vending/SmActor.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | import java.time.LocalDate 4 | 5 | import scala.concurrent.duration._ 6 | import scala.language.postfixOps 7 | 8 | import akka.actor.{Actor, ActorRef} 9 | import vending.Domain._ 10 | import vending.VendingMachineSm.VendingMachineState 11 | 12 | class SmActor(quantity: Map[Product, Int], 13 | userReportActor: ActorRef, 14 | reportsActor: ActorRef) 15 | extends Actor { 16 | 17 | var vendingMachineState = VendingMachineState( 18 | credit = 0, 19 | income = 0, 20 | quantity = quantity 21 | ) 22 | 23 | override def preStart(): Unit = { 24 | super.preStart() 25 | context.system.scheduler 26 | .schedule(5 seconds, 5 seconds, self, CheckExpiryDate)(context.system.dispatcher) 27 | } 28 | 29 | override def receive: Receive = { 30 | case a: Action => 31 | val (newState, results) = VendingMachineSm 32 | .compose(a, LocalDate.now()) //creating state monad for action 33 | .run(vendingMachineState) //running state monad 34 | .value //collecting result 35 | 36 | //updating state 37 | vendingMachineState = newState 38 | 39 | //Executing side effects 40 | results.systemReports 41 | .foreach(effect => reportsActor ! effect) 42 | 43 | results.userOutputs 44 | .foreach(effects => userReportActor ! effects) 45 | 46 | case GetState => sender() ! vendingMachineState 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/scala/vending/SmPersistentActor.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | import java.time.LocalDate 4 | 5 | import akka.actor.ActorRef 6 | import akka.persistence.{PersistentActor, RecoveryCompleted} 7 | import vending.Domain.{Action, GetState, Product} 8 | import vending.VendingMachineSm.VendingMachineState 9 | 10 | class SmPersistentActor(val persistenceId: String)( 11 | quantity: Map[Product, Int], 12 | userReportActor: ActorRef, 13 | reportsActor: ActorRef) 14 | extends PersistentActor { 15 | 16 | var vendingMachineState = VendingMachineState( 17 | credit = 0, 18 | income = 0, 19 | quantity = quantity 20 | ) 21 | 22 | override def receiveRecover: Receive = { 23 | 24 | case action: Action => 25 | val (newState, _) = VendingMachineSm 26 | .compose(action, LocalDate.now()) 27 | .run(vendingMachineState) 28 | .value 29 | vendingMachineState = newState 30 | 31 | case RecoveryCompleted => 32 | } 33 | 34 | override def receiveCommand: Receive = { 35 | case action: Action => 36 | 37 | persist(action) { a => 38 | val (newState, effects) = VendingMachineSm 39 | .compose(a, LocalDate.now()) 40 | .run(vendingMachineState) 41 | .value 42 | vendingMachineState = newState 43 | effects.userOutputs.foreach(m => userReportActor ! m) 44 | effects.systemReports.foreach(m => reportsActor ! m) 45 | } 46 | case GetState => sender() ! vendingMachineState 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/scala/vending/Domain.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | import java.time.LocalDate 4 | 5 | import cats.kernel.Monoid 6 | 7 | object Domain { 8 | 9 | case object GetState 10 | 11 | sealed trait Action 12 | case class Credit(value: Int) extends Action 13 | case object Withdrawn extends Action 14 | case object CheckExpiryDate extends Action 15 | case class SelectProduct(number: String) extends Action 16 | case object Quit extends Action 17 | 18 | sealed trait UserOutput 19 | case object CollectYourMoney extends UserOutput 20 | case class CreditInfo(value: Int) extends UserOutput 21 | case object WrongProduct extends UserOutput 22 | case class NotEnoughOfCredit(diff: Int) extends UserOutput 23 | case class OutOfStock(product: Product) extends UserOutput 24 | case class GiveProductAndChange(selected: Product, change: Int) extends UserOutput 25 | case class Display(string: String) extends UserOutput 26 | 27 | sealed trait SystemReporting 28 | case class MoneyBoxAlmostFull(amount: Int) extends SystemReporting 29 | case class ProductShortage(products: Product) extends SystemReporting 30 | case class ExpiredProducts(products: List[Product]) extends SystemReporting 31 | 32 | case class ActionResult(userOutputs: List[UserOutput] = List.empty, 33 | systemReports: List[SystemReporting] = List.empty) { 34 | def nonEmpty(): Boolean = userOutputs.nonEmpty || systemReports.nonEmpty 35 | } 36 | 37 | object ActionResult { 38 | 39 | implicit val monoid: Monoid[ActionResult] = new Monoid[ActionResult] { 40 | override def empty: ActionResult = ActionResult() 41 | override def combine(x: ActionResult, y: ActionResult): ActionResult = 42 | ActionResult(x.userOutputs ::: y.userOutputs, x.systemReports ::: y.systemReports) 43 | } 44 | } 45 | 46 | case class Product(price: Int, code: String, symbol: String, expiryDate: LocalDate) 47 | } 48 | -------------------------------------------------------------------------------- /src/main/scala/vending/package.scala: -------------------------------------------------------------------------------- 1 | import cats.Show 2 | import vending.Domain.{ActionResult, SystemReporting, UserOutput} 3 | import vending.VendingMachineSm.VendingMachineState 4 | 5 | package object vending { 6 | implicit val vendingShow: Show[VendingMachineState] = (t: VendingMachineState) => { 7 | val products = t.quantity.map { case (product, quantity) => 8 | s"${product.code}: ${product.price}PLN <${product.symbol * quantity}>" 9 | } 10 | s""" 11 | | +-----------------------------+ 12 | | | Vending Machine 2.0 | 13 | | +-----------------------------+ 14 | | | Credit: ${t.credit}PLN 15 | | | Products: 16 | ${products.map(x => s"| | $x").mkString("\n")} 17 | | +-----------------------------+ 18 | | | Maintenance info: 19 | | | Income: ${t.income}PLN 20 | | +-----------------------------+ 21 | |""" 22 | }.stripMargin 23 | 24 | implicit class ListOfUserOutputsOps(list: List[UserOutput]) { 25 | def actionResult(): ActionResult = ActionResult(userOutputs = list) 26 | } 27 | 28 | implicit class ListOfSystemReportsOps(list: List[SystemReporting]) { 29 | def actionResult(): ActionResult = ActionResult(systemReports = list) 30 | } 31 | 32 | implicit class SystemReportOps(systemReporting: SystemReporting) { 33 | def actionResult(): ActionResult = ActionResult(systemReports = List(systemReporting)) 34 | } 35 | 36 | implicit class UserOutputsOps(userOutput: UserOutput) { 37 | def actionResult(): ActionResult = ActionResult(userOutputs = List(userOutput)) 38 | } 39 | 40 | implicit class StringOps(s: String) { 41 | def inBox(): String = { 42 | val maxLength = s.lines.map(_.toCharArray.length).max 43 | s.lines.map { line => 44 | s"""│$line${" " * (maxLength - line.length)}│""" 45 | }.mkString(s"╭${"─" * maxLength}╮\n", "\n", s"\n╰${"─" * maxLength}╯") 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # state-monad 2 | Example usage of state monad from cats and comparison with implementation of logic in actors 3 | 4 | ## Model 5 | 6 | This application is modeling vending machine. Program interacts with user by simple command in terminal. User can: 7 | - insert coin 8 | - select product 9 | - withdraw money 10 | 11 | Vending machine can give you a product, change or display message. Additionally vending machine is sending reports to owner like: 12 | - there is a lot of money 13 | - issues with expiry date 14 | - vending machine run out of product 15 | 16 | ## Architecture 17 | ``` 18 | 19 | ╭────────────╮ ╭────────────────╮ 20 | User Input -> │ Actor │ -> │ User Outputs │ 21 | │ │ ╰────────────────╯ 22 | │ Logic is │ ╭────────────────╮ 23 | │ here │ -> │ System reports │ 24 | ╰────────────╯ ╰────────────────╯ 25 | 26 | 27 | 28 | ``` 29 | 30 | 31 | ## Implementation 32 | There are two implementations of vending machine: 33 | - [actor based](https://github.com/otrebski/state-monad/blob/master/src/main/scala/vending/BaseVendingMachineActor.scala), all logic is in actor 34 | - [all logic in state monad](https://github.com/otrebski/state-monad/blob/master/src/main/scala/vending/VendingMachineSm.scala) (from cats), [actor](https://github.com/otrebski/state-monad/blob/master/src/main/scala/vending/SmActor.scala) is for communication and keeping state 35 | 36 | ## Run app 37 | Running application: 38 | 39 | ```bash 40 | sbt "runMain vending.VendingMachineDemo" 41 | ``` 42 | 43 | You will be asked to choose implementation. 44 | 45 | Interaction with vending machine: 46 | ``` 47 | +digit -> insert coins, for example: +3 48 | digit -> select number, for example: 2 49 | - -> resign and take your money 50 | q -> quit program 51 | ``` 52 | 53 | ## Tests 54 | 55 | Tests are written for: 56 | - [actors](https://github.com/otrebski/state-monad/blob/master/src/test/scala/vending/BaseActorTest.scala) 57 | - [state monad](https://github.com/otrebski/state-monad/blob/master/src/test/scala/vending/VendingMachineSmTest.scala) 58 | 59 | One test is ignored (`should do not report if money box is almost full for a second time`). This test is currently failing because feature is not implemented. You can enable this test and implement logic using Actor and state monad. 60 | 61 | ## Where you should look 62 | Take a look at code and think about following topics: 63 | - can logic be divided into smaller parts? 64 | - can logic be composed from smaller parts? 65 | - can logic can be reused? 66 | - is it easy to test code? 67 | - is it easy to add additional features? 68 | - how fast are test 69 | 70 | -------------------------------------------------------------------------------- /src/main/scala/vending/VendingMachineDemo.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | import java.time.LocalDate 4 | 5 | import scala.annotation.tailrec 6 | import scala.io.StdIn 7 | import scala.util.Try 8 | 9 | import akka.actor.{ActorRef, ActorSystem, Props} 10 | import vending.Domain._ 11 | import vending.VendingMachineSm.VendingMachineState 12 | 13 | object VendingMachineDemo extends App { 14 | 15 | println("Vending machine demo") 16 | private val manual: String = 17 | """| Commands: 18 | | +digit -> insert coins, for example: +3 19 | | digit -> select number, for example: 2 20 | | - -> resign and take your money 21 | | q -> quit program 22 | """.stripMargin 23 | 24 | val expiryDate = LocalDate.now().plusDays(2) 25 | var vendingMachineState = VendingMachineState( 26 | credit = 0, income = 0, 27 | quantity = Map( 28 | Product(price = 4, code = "1", symbol = Symbols.candy, expiryDate = expiryDate) -> 1, 29 | Product(price = 2, code = "2", symbol = Symbols.pizza, expiryDate = expiryDate) -> 6, 30 | Product(price = 1, code = "3", symbol = Symbols.banana, expiryDate = expiryDate) -> 2, 31 | Product(price = 8, code = "4", symbol = Symbols.beer, expiryDate = expiryDate) -> 3 32 | ) 33 | ) 34 | 35 | private val system = ActorSystem("vending_machine") 36 | 37 | val clear = "\u001b[2J" 38 | 39 | println( 40 | """Pick Vending machine implementation: 41 | | 1 -> Logic in actor 42 | | 2 -> Logic in State Monad 43 | | 3 -> Logic in State Monad with persistence """.stripMargin) 44 | 45 | private def parseAction(line: String): Option[Action] = { 46 | import cats.syntax.option._ 47 | if (line.matches("\\+[\\d]+")) { 48 | Try(Credit(line.toInt)).toOption 49 | } else if (line.matches("\\d+")) { 50 | Try(SelectProduct(line)).toOption 51 | } else if (line == "-") { 52 | Withdrawn.some 53 | } else if (line == "q") { 54 | Quit.some 55 | } else { 56 | none[Action] 57 | } 58 | } 59 | 60 | def chooseActor(userOutputActor: ActorRef, reportsActor: ActorRef): Props = { 61 | val answer = StdIn.readLine() 62 | answer match { 63 | case "1" => Props(new BaseVendingMachineActor( 64 | vendingMachineState.quantity, 65 | userOutputActor, 66 | reportsActor)) 67 | case "2" => Props(new SmActor( 68 | vendingMachineState.quantity, 69 | userOutputActor, 70 | reportsActor)) 71 | case "3" => Props(new SmPersistentActor("p")( 72 | vendingMachineState.quantity, 73 | userOutputActor, 74 | reportsActor)) 75 | case _ => chooseActor(userOutputActor, reportsActor) 76 | } 77 | } 78 | 79 | val userOutputActor = system.actorOf(Props(new UserOutputsActor)) 80 | val reportsActor = system.actorOf(Props(new SystemReportsActor)) 81 | val props = chooseActor(userOutputActor, reportsActor) 82 | val actor = system.actorOf(props, "vm") 83 | actor ! Credit(0) 84 | 85 | @tailrec 86 | def loop(actor: ActorRef): Unit = { 87 | println(manual) 88 | val line = StdIn.readLine() 89 | val action = parseAction(line) 90 | action match { 91 | case Some(Quit) => () 92 | case Some(a) => 93 | println(clear) 94 | actor ! a 95 | loop(actor) 96 | case None => loop(actor) 97 | } 98 | } 99 | 100 | loop(actor) 101 | system.terminate() 102 | } 103 | -------------------------------------------------------------------------------- /src/main/scala/vending/BaseVendingMachineActor.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | import java.time.LocalDate 4 | 5 | import scala.concurrent.duration._ 6 | import scala.language.postfixOps 7 | 8 | import akka.actor.{Actor, ActorRef} 9 | import cats.syntax.show._ 10 | import vending.Domain._ 11 | import vending.VendingMachineSm.VendingMachineState 12 | 13 | class BaseVendingMachineActor( 14 | var quantity: Map[Product, Int], 15 | userReportActor: ActorRef, 16 | reportsActor: ActorRef 17 | ) extends Actor { 18 | 19 | var credit: Int = 0 20 | var income: Int = 0 21 | var expiryNotified: Set[Domain.Product] = Set.empty 22 | 23 | override def preStart(): Unit = { 24 | super.preStart() 25 | context.system.scheduler 26 | .schedule(5 seconds, 5 seconds, self, CheckExpiryDate)(context.system.dispatcher) 27 | } 28 | 29 | override def receive: Receive = { 30 | case SelectProduct(number) => 31 | val selected = number.toString 32 | val maybeProduct = quantity.keys.find(_.code == selected) 33 | val maybeQuantity = maybeProduct.map(quantity) 34 | (maybeProduct, maybeQuantity) match { 35 | case (Some(product), Some(q)) if product.price <= credit && q > 0 => 36 | val giveChange = credit - product.price // calculating new state 37 | val newQuantity = q - 1 // ..................... 38 | 39 | credit = 0 // Changing internal state 40 | income += product.price // ....................... 41 | quantity = quantity.updated(product, newQuantity) // ...................... 42 | 43 | userReportActor ! GiveProductAndChange(product, giveChange) //Execute side effects 44 | if (newQuantity == 0) reportsActor ! ProductShortage(product) //.................... 45 | if (income > 10) reportsActor ! MoneyBoxAlmostFull(income) //.................... 46 | userReportActor ! Display(currentState()) //.................... 47 | 48 | case (Some(product), Some(q)) if q < 1 => 49 | userReportActor ! OutOfStock(product) 50 | userReportActor ! Display(currentState()) 51 | case (Some(product), _) => 52 | userReportActor ! NotEnoughOfCredit(product.price - credit) 53 | userReportActor ! Display(currentState()) 54 | 55 | case (None, _) => 56 | userReportActor ! WrongProduct 57 | userReportActor ! Display(currentState()) 58 | } 59 | 60 | case Credit(value) => 61 | credit += value 62 | userReportActor ! CreditInfo(credit) 63 | userReportActor ! Display(currentState()) 64 | 65 | case Withdrawn => 66 | credit = 0 67 | userReportActor ! CollectYourMoney 68 | userReportActor ! Display(currentState()) 69 | 70 | case CheckExpiryDate => 71 | val now = LocalDate.now() 72 | val expiredProducts = quantity.keys.filter { p => 73 | !p.expiryDate.isAfter(now) && !expiryNotified.contains(p) 74 | } 75 | expiryNotified = expiryNotified ++ expiredProducts.toSet 76 | if (expiredProducts.nonEmpty) { 77 | reportsActor ! ExpiredProducts(expiredProducts.toList) 78 | } 79 | 80 | case GetState => 81 | 82 | val vm = VendingMachineState( 83 | credit, income, 84 | quantity, 85 | reportedExpiryDate = expiryNotified) 86 | sender() ! vm 87 | 88 | } 89 | 90 | def currentState(): String = { 91 | VendingMachineState( 92 | credit, income, 93 | quantity, 94 | reportedExpiryDate = expiryNotified).show 95 | 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/scala/vending/VendingMachineSm.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | import java.time.LocalDate 4 | 5 | import cats.data.State 6 | import cats.syntax.option._ 7 | import cats.syntax.show._ 8 | import vending.Domain._ 9 | 10 | object VendingMachineSm { 11 | 12 | // State monad is function 13 | // ╭----------------------------╮ 14 | // | State => (State, Effect) | 15 | // ╰----------------------------╯ 16 | // 17 | // In our case 18 | // Vending machine state => (New vending machine state, effects) 19 | 20 | def compose(action: Action, now: LocalDate): State[VendingMachineState, ActionResult] = 21 | for { 22 | updateResult <- updateCredit(action) 23 | // result ⬅ application() 24 | // ⬇ modified state 25 | selectResult <- selectProduct(action) 26 | // result ⬅ application() 27 | // ⬇ modified state 28 | maybeShortage <- detectShortage() 29 | // result ⬅ application() 30 | // ⬇ modified state 31 | expiredResult <- checkExpiryDate(action, now) 32 | // result ⬅ application() 33 | // ⬇ modified state 34 | maybeMbaf <- detectMoneyBoxAlmostFull() 35 | // result ⬅ application() 36 | // ⬇ modified state 37 | maybeDisplay <- maybeDisplayState(action) 38 | } yield ActionResult( 39 | userOutputs = List(updateResult, selectResult, maybeDisplay).flatten, 40 | systemReports = List(expiredResult, maybeMbaf).flatten ++ maybeShortage 41 | ) 42 | 43 | def updateCredit(action: Action): State[VendingMachineState, Option[UserOutput]] = 44 | State[VendingMachineState, Option[UserOutput]] { s => 45 | action match { 46 | case Credit(value) => (s.copy(credit = s.credit + value), CreditInfo(s.credit + value).some) 47 | case Withdrawn => (s.copy(credit = 0), CollectYourMoney.some) 48 | case _ => (s, none[UserOutput]) 49 | } 50 | } 51 | 52 | def selectProduct(action: Action): State[VendingMachineState, Option[UserOutput]] = 53 | State[VendingMachineState, Option[UserOutput]] { s => 54 | action match { 55 | case SelectProduct(number) => 56 | val selected = number.toString 57 | val maybeProduct = s.quantity.keys.find(_.code == selected) 58 | val maybeQuantity = maybeProduct.map(s.quantity) 59 | (maybeProduct, maybeQuantity) match { 60 | case (Some(product), Some(quantity)) if product.price <= s.credit && quantity > 0 => 61 | val giveChange = s.credit - product.price 62 | val newQuantity = quantity - 1 63 | val newState = s.copy( 64 | credit = 0, 65 | income = s.income + product.price, 66 | quantity = s.quantity.updated(product, newQuantity) 67 | ) 68 | (newState, GiveProductAndChange(product, giveChange).some) 69 | 70 | case (Some(product), Some(q)) if q < 1 => 71 | (s, OutOfStock(product).some) 72 | 73 | case (Some(product), _) => 74 | (s, NotEnoughOfCredit(product.price - s.credit).some) 75 | 76 | case (None, _) => 77 | (s, WrongProduct.some) 78 | } 79 | 80 | case _ => (s, none[UserOutput]) 81 | } 82 | } 83 | 84 | def detectShortage(): State[VendingMachineState, List[ProductShortage]] = { 85 | State[VendingMachineState, List[ProductShortage]] { s => 86 | val toNotify: Set[Product] = s.quantity.filter(_._2 == 0).keySet -- s.reportedShortage 87 | if (toNotify.isEmpty) { 88 | (s, List.empty[ProductShortage]) 89 | } else { 90 | (s.copy(reportedShortage = s.reportedShortage ++ toNotify), toNotify.toList.map(ProductShortage)) 91 | } 92 | } 93 | } 94 | 95 | def checkExpiryDate(action: Action, now: LocalDate): State[VendingMachineState, Option[SystemReporting]] = 96 | 97 | State[VendingMachineState, Option[SystemReporting]] { s => 98 | if (action == CheckExpiryDate) { 99 | val products = s.quantity.keys.filter { p => 100 | !p.expiryDate.isAfter(now) && !s.reportedExpiryDate.contains(p) 101 | }.toList 102 | val newState = s.copy(reportedExpiryDate = s.reportedExpiryDate ++ products) 103 | val result = if (products.nonEmpty) ExpiredProducts(products).some else none[SystemReporting] 104 | (newState, result) 105 | } else { 106 | (s, none[SystemReporting]) 107 | } 108 | } 109 | 110 | def detectMoneyBoxAlmostFull(): State[VendingMachineState, Option[MoneyBoxAlmostFull]] = { 111 | State[VendingMachineState, Option[MoneyBoxAlmostFull]] { s => 112 | if (s.income > 10) { 113 | (s, MoneyBoxAlmostFull(s.income).some) 114 | } else { 115 | (s, none[MoneyBoxAlmostFull]) 116 | } 117 | } 118 | } 119 | 120 | def maybeDisplayState(action: Action): State[VendingMachineState, Option[Display]] = 121 | State[VendingMachineState, Option[Display]] { s => 122 | val r = action match { 123 | case Credit(_) | Withdrawn | SelectProduct(_) => Display(s.show).some 124 | case _ => None 125 | } 126 | (s, r) 127 | } 128 | 129 | case class VendingMachineState(credit: Int, 130 | income: Int, 131 | quantity: Map[Product, Int] = Map.empty, 132 | reportedExpiryDate: Set[Domain.Product] = Set.empty[Domain.Product], 133 | reportedShortage: Set[Domain.Product] = Set.empty[Domain.Product] 134 | ) 135 | 136 | } 137 | -------------------------------------------------------------------------------- /src/test/scala/vending/BaseActorTest.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | import java.time.LocalDate 4 | 5 | import scala.concurrent.Await 6 | import scala.concurrent.duration._ 7 | import scala.language.postfixOps 8 | 9 | import akka.actor.{ActorRef, ActorSystem} 10 | import akka.pattern._ 11 | import akka.testkit.{ImplicitSender, TestKit, TestProbe} 12 | import akka.util.Timeout 13 | import org.scalatest.{Matchers, WordSpecLike} 14 | import vending.Domain._ 15 | import vending.VendingMachineSm.VendingMachineState 16 | 17 | abstract class BaseActorTest extends TestKit(ActorSystem("test")) 18 | with WordSpecLike 19 | with ImplicitSender 20 | with Matchers { 21 | private val beer = Product(3, "1", Symbols.beer, LocalDate.of(2020, 12, 10)) 22 | private val pizza = Product(100, "2", Symbols.pizza, LocalDate.of(2018, 12, 10)) 23 | 24 | private val quantity = Map(beer -> 5, pizza -> 3) 25 | 26 | def createActor(quantity: Map[Domain.Product, Int], 27 | userOutputActor: ActorRef, 28 | reportsActor: ActorRef): ActorRef 29 | 30 | implicit val timeout: Timeout = Timeout(3 seconds) 31 | 32 | "Actor" should { 33 | 34 | "successfully buy and give change" in { 35 | //given 36 | val userOutput = TestProbe("userOutput") //Create mocks 37 | val reports = TestProbe("reports") //............ 38 | val underTest = createActor(quantity, userOutput.ref, reports.ref) 39 | underTest ! Credit(10) // Prepare internal state 40 | userOutput.expectMsg(CreditInfo(10)) // ...................... 41 | userOutput.expectMsgType[Display] // ...................... 42 | 43 | //when 44 | underTest ! SelectProduct("1") // Invoke logic 45 | 46 | //then 47 | userOutput.expectMsg(GiveProductAndChange(beer, 7)) //Check mocks 48 | userOutput.expectMsgType[Display] //........... 49 | 50 | val state = Await.result((underTest ? GetState).mapTo[VendingMachineState], 3 seconds) 51 | state.quantity.get(beer) shouldBe Some(4) //Check actor internal state 52 | } 53 | 54 | "refuse to buy if not enough of money" in { 55 | val userOutput = TestProbe("userOutput") 56 | val reports = TestProbe("reports") 57 | val underTest = createActor(quantity, userOutput.ref, reports.ref) 58 | 59 | underTest ! Credit(10) 60 | userOutput.expectMsg(CreditInfo(10)) 61 | userOutput.expectMsgType[Display] 62 | underTest ! SelectProduct("2") 63 | 64 | userOutput.expectMsg(NotEnoughOfCredit(90)) 65 | userOutput.expectMsgType[Display] 66 | 67 | } 68 | 69 | "refuse to buy for wrong product selection" in { 70 | val userOutput = TestProbe("userOutput") 71 | val reports = TestProbe("reports") 72 | val underTest = createActor(quantity, userOutput.ref, reports.ref) 73 | 74 | underTest ! Credit(10) 75 | userOutput.expectMsg(CreditInfo(10)) 76 | userOutput.expectMsgType[Display] 77 | 78 | underTest ! SelectProduct("4") 79 | 80 | userOutput.expectMsg(WrongProduct) 81 | userOutput.expectMsgType[Display] 82 | } 83 | 84 | "refuse to buy if out of stock" in { 85 | val userOutput = TestProbe("userOutput") 86 | val reports = TestProbe("reports") 87 | val underTest = createActor(quantity.updated(beer, 0), userOutput.ref, reports.ref) 88 | 89 | underTest ! Credit(10) 90 | userOutput.expectMsg(CreditInfo(10)) 91 | userOutput.expectMsgType[Display] 92 | 93 | underTest ! SelectProduct("1") 94 | 95 | userOutput.expectMsg(OutOfStock(beer)) 96 | userOutput.expectMsgType[Display] 97 | } 98 | 99 | "track credit" in { 100 | val userOutput = TestProbe("userOutput") 101 | val reports = TestProbe("reports") 102 | val underTest = createActor(quantity, userOutput.ref, reports.ref) 103 | 104 | Await.result((underTest ? GetState).mapTo[VendingMachineState], 3 seconds).credit shouldBe 0 105 | 106 | underTest ! Credit(2) 107 | userOutput.expectMsg(CreditInfo(2)) 108 | userOutput.expectMsgType[Display] 109 | 110 | underTest ! Credit(3) 111 | userOutput.expectMsg(CreditInfo(5)) 112 | userOutput.expectMsgType[Display] 113 | } 114 | 115 | "track income" in { 116 | val userOutput = TestProbe("userOutput") 117 | val reports = TestProbe("reports") 118 | val underTest = createActor(quantity, userOutput.ref, reports.ref) 119 | 120 | Await.result((underTest ? GetState).mapTo[VendingMachineState], 3 seconds).income shouldBe 0 121 | 122 | underTest ! Credit(10) 123 | userOutput.expectMsg(CreditInfo(10)) 124 | userOutput.expectMsgType[Display] 125 | 126 | underTest ! SelectProduct("1") 127 | userOutput.expectMsg(GiveProductAndChange(beer, 7)) 128 | userOutput.expectMsgType[Display] 129 | Await.result((underTest ? GetState).mapTo[VendingMachineState], 3 seconds).income shouldBe 3 130 | 131 | underTest ! Credit(10) 132 | userOutput.expectMsg(CreditInfo(10)) 133 | userOutput.expectMsgType[Display] 134 | underTest ! SelectProduct("1") 135 | userOutput.expectMsg(GiveProductAndChange(beer, 7)) 136 | userOutput.expectMsgType[Display] 137 | Await.result((underTest ? GetState).mapTo[VendingMachineState], 3 seconds).income shouldBe 6 138 | } 139 | 140 | "give back all money if withdraw" in { 141 | val userOutput = TestProbe("userOutput") 142 | val reports = TestProbe("reports") 143 | val underTest = createActor(quantity, userOutput.ref, reports.ref) 144 | 145 | underTest ! Credit(10) 146 | userOutput.expectMsg(CreditInfo(10)) 147 | userOutput.expectMsgType[Display] 148 | 149 | underTest ! Withdrawn 150 | 151 | userOutput.expectMsg(CollectYourMoney) 152 | userOutput.expectMsgType[Display] 153 | } 154 | 155 | "report if money box is almost full" in { 156 | val userOutput = TestProbe("userOutput") 157 | val reports = TestProbe("reports") 158 | val underTest = createActor(quantity, userOutput.ref, reports.ref) 159 | 160 | underTest ! Credit(100) 161 | userOutput.expectMsg(CreditInfo(100)) 162 | userOutput.expectMsgType[Display] 163 | 164 | underTest ! SelectProduct("2") 165 | 166 | userOutput.expectMsg(GiveProductAndChange(pizza, 0)) 167 | userOutput.expectMsgType[Display] 168 | reports.expectMsg(MoneyBoxAlmostFull(100)) 169 | 170 | } 171 | 172 | "report shortage of product" in { 173 | val userOutput = TestProbe("userOutput") 174 | val reports = TestProbe("reports") 175 | val underTest = createActor(quantity.updated(beer, 1), userOutput.ref, reports.ref) 176 | 177 | underTest ! Credit(beer.price) 178 | userOutput.expectMsg(CreditInfo(beer.price)) 179 | userOutput.expectMsgType[Display] 180 | 181 | underTest ! SelectProduct("1") 182 | userOutput.expectMsg(GiveProductAndChange(beer, 0)) 183 | userOutput.expectMsgType[Display] 184 | reports.expectMsg(ProductShortage(beer)) 185 | 186 | } 187 | 188 | "report issues with expiry date" in { 189 | val oldPaprika = pizza.copy(expiryDate = LocalDate.now().minusDays(1)) 190 | val userOutput = TestProbe("userOutput") 191 | val reports = TestProbe("reports") 192 | val underTest = createActor(Map(oldPaprika -> 2), userOutput.ref, reports.ref) 193 | 194 | underTest ! CheckExpiryDate 195 | reports.expectMsg(ExpiredProducts(List(oldPaprika))) 196 | } 197 | 198 | "do not report issues with expiry date for a second time" in { 199 | val oldPaprika = pizza.copy(expiryDate = LocalDate.now().minusDays(1)) 200 | val userOutput = TestProbe("userOutput") 201 | val reports = TestProbe("reports") 202 | val underTest = createActor(Map(oldPaprika -> 2), userOutput.ref, reports.ref) 203 | 204 | underTest ! CheckExpiryDate 205 | reports.expectMsg(ExpiredProducts(List(oldPaprika))) 206 | 207 | underTest ! CheckExpiryDate 208 | reports.expectNoMessage() 209 | } 210 | 211 | } 212 | 213 | } 214 | -------------------------------------------------------------------------------- /src/test/scala/vending/VendingMachineSmTest.scala: -------------------------------------------------------------------------------- 1 | package vending 2 | 3 | import java.time.LocalDate 4 | 5 | import cats.syntax.option._ 6 | import org.scalatest.{Matchers, WordSpec} 7 | import vending.Domain.{_} 8 | import vending.VendingMachineSm.VendingMachineState 9 | 10 | class VendingMachineSmTest extends WordSpec with Matchers { 11 | 12 | val now: LocalDate = LocalDate.of(2018, 10, 1) 13 | private val beer = Product(3, "1", Symbols.beer, LocalDate.of(2020, 12, 10)) 14 | private val pizza = Product(100, "2", Symbols.pizza, LocalDate.of(2018, 12, 10)) 15 | var vendingMachineState = VendingMachineState( 16 | credit = 0, income = 0, 17 | quantity = Map( 18 | beer -> 5, 19 | pizza -> 1 20 | ) 21 | ) 22 | 23 | "Vending machine" should { 24 | 25 | "successfully buy and give change" in { 26 | val (state, effects) = (for { 27 | _ <- VendingMachineSm.compose(Credit(10), now) 28 | e <- VendingMachineSm.compose(SelectProduct("1"), now) 29 | } yield e).run(vendingMachineState).value 30 | 31 | state.quantity.get(beer) shouldBe Some(4) 32 | effects.userOutputs should contain(GiveProductAndChange(beer, 7)) 33 | } 34 | 35 | "refuse to buy if not enough of money" in { 36 | val (state, effects) = (for { 37 | _ <- VendingMachineSm.compose(Credit(1), now) 38 | e <- VendingMachineSm.compose(SelectProduct("1"), now) 39 | } yield e).run(vendingMachineState).value 40 | 41 | state.quantity.get(beer) shouldBe Some(5) 42 | state.credit shouldBe 1 43 | effects.userOutputs should contain(NotEnoughOfCredit(2)) 44 | } 45 | 46 | "refuse to buy for wrong product selection" in { 47 | val (state, effects) = (for { 48 | _ <- VendingMachineSm.compose(Credit(1), now) 49 | e <- VendingMachineSm.compose(SelectProduct("3"), now) 50 | } yield e).run(vendingMachineState).value 51 | 52 | state.quantity.get(beer) shouldBe Some(5) 53 | state.credit shouldBe 1 54 | effects.userOutputs should contain(WrongProduct) 55 | } 56 | 57 | "refuse to buy if out of stock" in { 58 | val (state, effects) = (for { 59 | _ <- VendingMachineSm.compose(Credit(10), now) 60 | e <- VendingMachineSm.compose(SelectProduct("1"), now) 61 | } yield e).run(vendingMachineState.copy(quantity = Map(beer -> 0))).value 62 | 63 | state.quantity.get(beer) shouldBe Some(0) 64 | state.credit shouldBe 10 65 | effects.userOutputs should contain(OutOfStock(beer)) 66 | } 67 | 68 | "track income" in { 69 | val (state, _) = ( 70 | for { 71 | _ <- VendingMachineSm.compose(Credit(10), now) 72 | _ <- VendingMachineSm.compose(SelectProduct("1"), now) 73 | _ <- VendingMachineSm.compose(Credit(10), now) 74 | _ <- VendingMachineSm.compose(SelectProduct("1"), now) 75 | } yield () 76 | ).run(vendingMachineState).value 77 | 78 | state.income shouldBe 6 79 | } 80 | 81 | "track credit" in { 82 | val (state, (effects1, effects2)) = ( 83 | for { 84 | e1 <- VendingMachineSm.compose(Credit(10), now) 85 | e2 <- VendingMachineSm.compose(Credit(1), now) 86 | } yield (e1, e2)).run(vendingMachineState).value 87 | 88 | effects1.userOutputs.head shouldBe CreditInfo(10) 89 | effects2.userOutputs.head shouldBe CreditInfo(11) 90 | state.credit shouldBe 11 91 | } 92 | 93 | "give back all money if withdraw" in { 94 | val (state, _) = ( 95 | for { 96 | _ <- VendingMachineSm.compose(Credit(10), now) 97 | _ <- VendingMachineSm.compose(Withdrawn, now) 98 | } yield ()).run(vendingMachineState).value 99 | 100 | state.credit shouldBe 0 101 | } 102 | 103 | "report if money box is almost full" in { 104 | val (_, effects) = ( 105 | for { 106 | _ <- VendingMachineSm.compose(Credit(200), now) 107 | e <- VendingMachineSm.compose(SelectProduct("2"), now) 108 | } yield e).run(vendingMachineState).value 109 | 110 | effects.systemReports should contain(MoneyBoxAlmostFull(100)) 111 | } 112 | 113 | "detect shortage of product" in { 114 | val (_, effects) = ( 115 | for { 116 | _ <- VendingMachineSm.compose(Credit(200), now) 117 | e <- VendingMachineSm.compose(SelectProduct("2"), now) 118 | } yield e).run(vendingMachineState).value 119 | 120 | effects.systemReports should contain(ProductShortage(pizza)) 121 | } 122 | 123 | "report issues with expiry date" in { 124 | val now = LocalDate.of(2019, 1, 1) 125 | val (state, (effects1, effects2)) = ( 126 | for { 127 | e1 <- VendingMachineSm.compose(CheckExpiryDate, now) 128 | e2 <- VendingMachineSm.compose(CheckExpiryDate, now) 129 | } yield (e1, e2)).run(vendingMachineState).value 130 | 131 | effects1.systemReports should contain(ExpiredProducts(List(pizza))) 132 | effects2.systemReports should not contain (ExpiredProducts(List(pizza))) 133 | state.reportedExpiryDate should contain(pizza) 134 | } 135 | 136 | } 137 | 138 | "expiry date monad" should { 139 | val expired = pizza.expiryDate.plusDays(1) 140 | val state0 = vendingMachineState.copy( 141 | 142 | ) 143 | 144 | "find expired products" in { 145 | val (state1, effects) = VendingMachineSm.checkExpiryDate(CheckExpiryDate, expired).run(state0).value 146 | 147 | effects shouldBe ExpiredProducts(List(pizza)).some 148 | state1.reportedExpiryDate shouldBe Set(pizza) 149 | } 150 | 151 | "ignore expired products if already reported" in { 152 | val (state1, effects) = (for { 153 | _ <- VendingMachineSm.checkExpiryDate(CheckExpiryDate, expired) 154 | e <- VendingMachineSm.checkExpiryDate(CheckExpiryDate, expired) 155 | } yield e).run(state0).value 156 | 157 | effects shouldBe none[ExpiredProducts] 158 | state1.reportedExpiryDate shouldBe Set(pizza) 159 | } 160 | 161 | "check that all products are ok" in { 162 | val (state1, effects) = VendingMachineSm.checkExpiryDate(CheckExpiryDate, LocalDate.MIN).run(state0).value 163 | 164 | effects shouldBe none[ExpiredProducts] 165 | state1.reportedExpiryDate shouldBe Set.empty[Product] 166 | } 167 | } 168 | 169 | "update credit monad" should { 170 | 171 | "update credit when insert" in { 172 | 173 | val (state, (effects1, effects2)) = (for { 174 | e1 <- VendingMachineSm.updateCredit(Credit(2)) 175 | e2 <- VendingMachineSm.updateCredit(Credit(5)) 176 | } yield (e1, e2)).run(vendingMachineState).value 177 | 178 | state.credit shouldBe 7 179 | effects1 shouldBe CreditInfo(2).some 180 | effects2 shouldBe CreditInfo(7).some 181 | } 182 | 183 | "clear credit when withdrawn is selected" in { 184 | val state0 = vendingMachineState.copy(credit = 20) 185 | 186 | val (state1, effects) = VendingMachineSm.updateCredit(Withdrawn).run(state0).value 187 | 188 | state1.credit shouldBe 0 189 | effects shouldBe CollectYourMoney.some 190 | } 191 | 192 | } 193 | 194 | "select product monad" should { 195 | 196 | val state0 = vendingMachineState.copy( 197 | credit = 10 198 | ) 199 | "successfully buy product" in { 200 | val (state1, effects) = VendingMachineSm.selectProduct(SelectProduct(beer.code)).run(state0).value 201 | 202 | state1.income shouldBe beer.price 203 | effects shouldBe GiveProductAndChange(beer, 7).some 204 | } 205 | "refuse to buy if not enough of money" in { 206 | val (state1, effects) = VendingMachineSm.selectProduct(SelectProduct(pizza.code)).run(state0).value 207 | 208 | state1.income shouldBe 0 209 | state1.credit shouldBe 10 210 | effects shouldBe NotEnoughOfCredit(90).some 211 | } 212 | } 213 | 214 | "detect shortage monad" should { 215 | 216 | val state0 = vendingMachineState.copy(quantity = Map(beer -> 0)) 217 | 218 | "detect shortage" in { 219 | val (_, effects) = VendingMachineSm.detectShortage().run(state0).value 220 | effects shouldBe List(ProductShortage(beer)) 221 | } 222 | 223 | "ignore shortage for a second time" in { 224 | val (_, effects) = (for { 225 | e1 <- VendingMachineSm.detectShortage() 226 | e2 <- VendingMachineSm.detectShortage() 227 | } yield (e1, e2)).run(state0).value 228 | 229 | effects._1 shouldBe List(ProductShortage(beer)) 230 | effects._2 shouldBe List.empty 231 | } 232 | } 233 | 234 | "detect money box almost full monad" should { 235 | val state0 = vendingMachineState.copy(income = 100) 236 | "notify if money box is almost full" in { 237 | val (_, effects) = VendingMachineSm.detectMoneyBoxAlmostFull().run(state0).value 238 | effects shouldBe MoneyBoxAlmostFull(100).some 239 | } 240 | } 241 | 242 | } 243 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------