akka.event.LoggingReceive Scala Examples

The following examples show how to use akka.event.LoggingReceive. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: Person.scala    From akka-serialization-test   with Apache License 2.0 5 votes vote down vote up
package com.github.dnvriend.domain

import akka.actor.ActorLogging
import akka.event.LoggingReceive
import akka.persistence.{ PersistentActor, RecoveryCompleted }

object Person {
  sealed trait PersonEvent
  final case class NameRegisteredEvent(name: String, surname: String) extends PersonEvent
  final case class NameChangedEvent(name: String) extends PersonEvent
  final case class SurnameChangedEvent(surname: String) extends PersonEvent

  sealed trait PersonCommand
  final case class RegisterNameCommand(name: String, surname: String) extends PersonCommand
  final case class ChangeNameCommand(name: String) extends PersonCommand
  final case class ChangeSurnameCommand(surname: String) extends PersonCommand
}

class Person(val persistenceId: String) extends PersistentActor with ActorLogging {
  import Person._
  var name: String = _
  var surname: String = _

  override def receiveRecover: Receive = LoggingReceive {
    case e: NameRegisteredEvent ⇒

      handleEvent(e)
    case e: NameChangedEvent    ⇒ handleEvent(e)
    case e: SurnameChangedEvent ⇒ handleEvent(e)
    case RecoveryCompleted      ⇒ println("==> Recovery completed")
    case e                      ⇒ println("Dropping event: " + e.getClass.getName)
  }

  def handleEvent(event: NameRegisteredEvent): Unit = {
    this.name = event.name
    this.surname = event.surname
    log.debug(s"[NameRegistered]: Person $persistenceId => name: $name, surname: $surname")
  }

  def handleEvent(event: NameChangedEvent): Unit = {
    this.name = event.name
    log.debug(s"[NameChanged]: Person $persistenceId => name: $name, surname: $surname")
  }

  def handleEvent(event: SurnameChangedEvent): Unit = {
    this.surname = event.surname
    log.debug(s"[SurnameChanged]: Person $persistenceId => name: $name, surname: $surname")
  }

  override def receiveCommand: Receive = LoggingReceive {
    case RegisterNameCommand(name, surname) ⇒
      persist(NameRegisteredEvent(name, surname)) { e ⇒
        handleEvent(e)
        sender() ! akka.actor.Status.Success("")
      }
    case ChangeNameCommand(newName) ⇒
      persist(NameChangedEvent(newName)) { e ⇒
        handleEvent(e)
        sender() ! akka.actor.Status.Success("")
      }
    case ChangeSurnameCommand(newSurname) ⇒
      persist(SurnameChangedEvent(newSurname)) { e ⇒
        handleEvent(e)
        sender() ! akka.actor.Status.Success("")
      }
  }

  override def postStop(): Unit = {
    log.debug(s"Stopped $persistenceId")
    super.postStop()
  }
} 
Example 2
Source File: Music.scala    From akka-serialization-test   with Apache License 2.0 5 votes vote down vote up
package com.github.dnvriend.domain

import java.time.Duration

import akka.actor.ActorLogging
import akka.event.LoggingReceive
import akka.persistence.PersistentActor

object Music {

  type Title = String
  type Year = Int

  final case class Song(title: Title, duration: Duration)

  sealed trait AlbumEvent

  final case class TitleChanged(title: Title) extends AlbumEvent

  final case class YearChanged(year: Year) extends AlbumEvent

  final case class SongAdded(song: Song) extends AlbumEvent

  final case class SongRemoved(song: Song) extends AlbumEvent

  sealed trait AlbumCommand

  final case class ChangeAlbumTitle(title: Title) extends AlbumCommand

  final case class ChangeAlbumYear(year: Year) extends AlbumCommand

  final case class AddSong(song: Song) extends AlbumCommand

  final case class RemoveSong(song: Song) extends AlbumCommand

}

class Album(val persistenceId: String) extends PersistentActor with ActorLogging {

  import Music._

  var title: Title = _
  var year: Year = _
  var songs: Set[Song] = Set[Song]()

  override def receiveRecover: Receive = LoggingReceive {
    case e: TitleChanged ⇒ handleEvent(e)
    case e: YearChanged  ⇒ handleEvent(e)
    case e: SongAdded    ⇒ handleEvent(e)
    case e: SongRemoved  ⇒ handleEvent(e)
  }

  def handleEvent(event: TitleChanged): Unit = {
    this.title = event.title
    log.debug(s"[TitleChanged]: Album $persistenceId => title: $title, year: $year songs: $songs")
  }

  def handleEvent(event: YearChanged): Unit = {
    this.year = event.year
    log.debug(s"[YearChanged]: Album $persistenceId => title: $title, year: $year songs: $songs")
  }

  def handleEvent(event: SongAdded): Unit = {
    this.songs = this.songs + event.song
    log.debug(s"[SongAdded]: Album $persistenceId => title: $title, year: $year songs: $songs")
  }

  def handleEvent(event: SongRemoved): Unit = {
    this.songs = this.songs - event.song
    log.debug(s"[SongRemoved]: Album $persistenceId => title: $title, year: $year songs: $songs")
  }

  override def receiveCommand: Receive = LoggingReceive {
    case ChangeAlbumTitle(newTitle) ⇒
      persistAll(List(TitleChanged(newTitle))) { e ⇒
        handleEvent(e)
        sender() ! akka.actor.Status.Success("")
      }
    case ChangeAlbumYear(newYear) ⇒
      persistAll(List(YearChanged(newYear))) { e ⇒
        handleEvent(e)
        sender() ! akka.actor.Status.Success("")
      }
    case AddSong(newSong) ⇒
      persistAll(List(SongAdded(newSong))) { e ⇒
        handleEvent(e)
        sender() ! akka.actor.Status.Success("")
      }
    case RemoveSong(oldSong) ⇒
      persistAll(List(SongRemoved(oldSong))) { e ⇒
        handleEvent(e)
        sender() ! akka.actor.Status.Success("")
      }
  }

  override def postStop(): Unit = {
    log.debug(s"Stopped $persistenceId")
    super.postStop()
  }
} 
Example 3
Source File: PersistenceTestActor.scala    From akka-persistence-dynamodb   with Apache License 2.0 5 votes vote down vote up
package com.github.j5ik2o.akka.persistence.dynamodb.query

import akka.actor.Status.Success
import akka.actor.{ ActorLogging, ActorRef }
import akka.event.LoggingReceive
import akka.persistence._
import akka.persistence.journal.Tagged

object PersistenceTestActor {
  final case class DeleteCmd(toSequenceNr: Long = Long.MaxValue) extends Serializable
}

class PersistenceTestActor(id: Int) extends PersistentActor with ActorLogging {
  import PersistenceTestActor._
  val pluginName = context.system.settings.config.getString("akka.persistence.journal.plugin")

  override def persistenceId: String = "my-" + id

  private val label = s"$persistenceId - $pluginName"

  log.debug("==> Created test actor: " + persistenceId)

  var state: Int = 1

  def debug(msg: String): Unit = log.debug(s"$msg in state $label")

  def deleteCmd(ref: ActorRef): Receive = LoggingReceive.withLabel(label) {
    case msg @ DeleteMessagesSuccess(toSequenceNr) =>
      debug(s"Deleted up to: $msg")
      ref ! Success(s"deleted-$toSequenceNr")
      context.become(receiveCommand)
    case msg @ DeleteMessagesFailure(t, toSequenceNr) =>
      debug(s"Failed deleting events: $msg")
      ref ! akka.actor.Status.Failure(t)
      context.become(receiveCommand)
  }

  override def receiveCommand: Receive = LoggingReceive.withLabel(label) {
    case DeleteCmd(toSequenceNr) =>
      deleteMessages(toSequenceNr)
      debug(s"Deleting up to: '$toSequenceNr'")
      context.become(deleteCmd(sender()))

    case event @ Tagged(payload: Any, tags) =>
      persist(event.copy(payload = s"$payload-$state")) { _ =>
        increment()
        sender() ! event
      }

    case event =>
      persist(s"$event-$state") { _ =>
        increment()
        sender() ! event
      }
  }

  def increment(): Unit = state += 1

  override def receiveRecover: Receive = LoggingReceive.withLabel(label) {
    case _: String         => increment()
    case RecoveryCompleted =>
  }

  override protected def onPersistFailure(cause: Throwable, event: Any, seqNr: Long): Unit = {
    sender() ! akka.actor.Status.Failure(cause)
    context.become(receiveCommand)
    super.onPersistFailure(cause, event, seqNr)
  }

  override protected def onPersistRejected(cause: Throwable, event: Any, seqNr: Long): Unit = {
    sender() ! akka.actor.Status.Failure(cause)
    context.become(receiveCommand)
    super.onPersistRejected(cause, event, seqNr)
  }
} 
Example 4
Source File: ActorSubscriberTest.scala    From intro-to-akka-streams   with Apache License 2.0 5 votes vote down vote up
package com.github.dnvriend.streams.sink

import akka.Done
import akka.actor.Actor.Receive
import akka.actor.{ ActorRef, Props }
import akka.event.LoggingReceive
import akka.stream.actor.ActorSubscriberMessage.{ OnComplete, OnError, OnNext }
import akka.stream.actor.{ ActorSubscriber, OneByOneRequestStrategy, RequestStrategy }
import akka.stream.scaladsl.{ Sink, Source }
import akka.stream.testkit.TestPublisher
import akka.stream.testkit.scaladsl.TestSource
import akka.testkit.TestProbe
import com.github.dnvriend.streams.TestSpec
import com.github.dnvriend.streams.sink.ActorSubscriberTest.TestActorSubscriber

import scala.concurrent.Future
import scala.reflect.ClassTag

object ActorSubscriberTest {
  final val OnNextMessage = "onNext"
  final val OnCompleteMessage = "onComplete"
  final val OnErrorMessage = "onError"

  class TestActorSubscriber(ref: ActorRef) extends ActorSubscriber {
    override protected val requestStrategy: RequestStrategy = OneByOneRequestStrategy
    override def receive: Receive = LoggingReceive {
      case OnNext(msg)    ⇒ ref ! OnNextMessage
      case OnComplete     ⇒ ref ! OnCompleteMessage
      case OnError(cause) ⇒ ref ! OnErrorMessage
    }
  }
}

//class ActorSubscriberTest extends TestSpec {
//  def withForwarder(xs: Int*)(f: TestProbe ⇒ Unit): Unit = {
//    val tp = TestProbe()
//    val ref = new TestActorSubscriber(tp.ref)
//    Source(xs.toList).to(Sink.actorSubscriber(Props())).mapMaterializedValue(_ ⇒ Future.successful[Done]).run()
//    try f(tp) finally killActors(ref)
//  }
//
//} 
Example 5
Source File: CamelActorPublisher.scala    From reactive-activemq   with Apache License 2.0 5 votes vote down vote up
package akka.stream.integration
package camel

import akka.actor.{ ActorLogging, ActorRef, Props }
import akka.camel.{ CamelMessage, Consumer }
import akka.event.LoggingReceive
import akka.stream.actor.ActorPublisher
import akka.stream.actor.ActorPublisherMessage.Cancel
import akka.stream.scaladsl.Source

class CamelActorPublisher(val endpointUri: String) extends Consumer with ActorPublisher[(ActorRef, CamelMessage)] with ActorLogging {
  override val autoAck: Boolean = false

  override def receive: Receive = LoggingReceive {
    case CamelMessage if totalDemand == 0 =>
      sender() ! akka.actor.Status.Failure(new IllegalStateException("No demand for new messages"))

    case msg: CamelMessage => onNext((sender(), msg))

    case Cancel            => context stop self
  }
}

class CamelActorPublisherWithExtractor[A: CamelMessageExtractor](val endpointUri: String) extends Consumer with ActorPublisher[(ActorRef, A)] with ActorLogging {
  override val autoAck: Boolean = false

  override def receive: Receive = LoggingReceive {
    case CamelMessage if totalDemand == 0 =>
      sender() ! akka.actor.Status.Failure(new IllegalStateException("No demand for new messages"))

    case msg: CamelMessage =>
      try {
        onNext((sender(), implicitly[CamelMessageExtractor[A]].extract(msg)))
      } catch {
        case t: Throwable =>
          log.error(t, "Removing message from the broker because of error while extracting the message")
          sender() ! akka.camel.Ack
      }

    case Cancel => context stop self
  }
}

object CamelActorPublisher {
  def fromEndpointUri(endpointUri: String): Source[AckRefTup[CamelMessage], ActorRef] =
    Source.actorPublisher[AckRefTup[CamelMessage]](Props(new CamelActorPublisher(endpointUri)))

  def fromEndpointUriWithExtractor[A: CamelMessageExtractor](endpointUri: String): Source[AckRefTup[A], ActorRef] =
    Source.actorPublisher[AckRefTup[A]](Props(new CamelActorPublisherWithExtractor(endpointUri)))
} 
Example 6
Source File: BlockActor.scala    From bitcoin-s-spv-node   with MIT License 5 votes vote down vote up
package org.bitcoins.spvnode.networking

import akka.actor.{Actor, ActorContext, ActorRef, ActorSystem, Props}
import akka.event.LoggingReceive
import org.bitcoins.core.crypto.DoubleSha256Digest
import org.bitcoins.core.protocol.CompactSizeUInt
import org.bitcoins.core.protocol.blockchain.BlockHeader
import org.bitcoins.core.util.BitcoinSLogger
import org.bitcoins.spvnode.NetworkMessage
import org.bitcoins.spvnode.constant.Constants
import org.bitcoins.spvnode.messages.{BlockMessage, GetBlocksMessage, InventoryMessage, MsgBlock}
import org.bitcoins.spvnode.messages.data.{GetBlocksMessage, GetDataMessage, Inventory, InventoryMessage}
import org.bitcoins.spvnode.util.BitcoinSpvNodeUtil


sealed trait BlockActor extends Actor with BitcoinSLogger {

  def receive: Receive = LoggingReceive {
    case hash: DoubleSha256Digest =>
      val peerMsgHandler = PeerMessageHandler(context)
      val inv = Inventory(MsgBlock,hash)
      val getDataMessage = GetDataMessage(inv)
      val networkMessage = NetworkMessage(Constants.networkParameters, getDataMessage)
      peerMsgHandler ! networkMessage
      context.become(awaitBlockMsg)
    case blockHeader: BlockHeader =>
      self.forward(blockHeader.hash)
  }

  def awaitBlockMsg: Receive = LoggingReceive {
    case blockMsg: BlockMessage =>
      context.parent ! blockMsg
      context.stop(self)
  }
}


object BlockActor {
  private case class BlockActorImpl() extends BlockActor
  def props = Props(classOf[BlockActorImpl])

  def apply(context: ActorContext): ActorRef = context.actorOf(props)

} 
Example 7
Source File: SupervisionTest.scala    From reactive-programming   with Apache License 2.0 5 votes vote down vote up
package com.test.week6

import akka.actor._
import akka.event.LoggingReceive
import akka.pattern.ask
import akka.testkit.TestProbe
import com.test.TestSpec

import scala.concurrent.duration._

class SupervisionTest extends TestSpec {

  case class Command(f: () ⇒ Unit)
  case object Count
  case object GetState
  case class CounterState(counter: Long)

  class Supervisor(tp: TestProbe, svs: SupervisorStrategy) extends Actor {
    val worker: ActorRef = context.actorOf(Props(new Actor with ActorLogging {
      var counter = 0L

      override def receive: Receive = LoggingReceive {
        case Command(f) ⇒ f()
        case Count      ⇒ counter += 1
        case GetState   ⇒ sender() ! CounterState(counter)
      }

      override def preStart(): Unit =
        log.debug("Started")

      override def postStop(): Unit =
        log.debug("Stopped")
    }), "worker")
    tp watch worker

    override def receive = LoggingReceive {
      case msg ⇒ worker forward msg
    }

    override def supervisorStrategy: SupervisorStrategy = svs
  }

  def createSupervisor(tp: TestProbe)(svs: SupervisorStrategy) =
    system.actorOf(Props(new Supervisor(tp, svs)), s"sup-${randomId.take(3)}")

  "SupervisorStrategy" should "resume the worker, state should not change, so should be 1" in {
    val tp = probe
    val sup = createSupervisor(tp) {
      OneForOneStrategy() {
        case t: RuntimeException ⇒ SupervisorStrategy.Resume
      }
    }
    sup ! Count
    (sup ? GetState).futureValue shouldBe CounterState(1L)
    sup ! Command(() ⇒ throw new RuntimeException("resume"))
    (sup ? GetState).futureValue shouldBe CounterState(1L)
    tp.expectNoMsg(100.millis) // no Terminated message
    cleanup(sup)
  }

  it should "restart the worker, so the worker instance has been replaced, and state should be 0 again" in {
    val tp = probe
    val sup = createSupervisor(tp) {
      OneForOneStrategy() {
        case t: RuntimeException ⇒ SupervisorStrategy.Restart
      }
    }
    sup ! Count
    (sup ? GetState).futureValue shouldBe CounterState(1L)
    sup ! Command(() ⇒ throw new RuntimeException("restart"))
    (sup ? GetState).futureValue shouldBe CounterState(0L)
    tp.expectNoMsg(100.millis) // no Terminated message
    cleanup(sup)
  }

  it should "stop the worker, so worker in not there anymore and should not answer" in {
    val tp = probe
    val sup = createSupervisor(tp) {
      OneForOneStrategy() {
        case t: RuntimeException ⇒ SupervisorStrategy.Stop
      }
    }
    sup ! Command(() ⇒ throw new RuntimeException("stop"))
    tp.expectMsgPF[Unit](100.millis) {
      case Terminated(_) ⇒
    }
    cleanup(sup)
  }
} 
Example 8
Source File: BankAccountTest.scala    From reactive-programming   with Apache License 2.0 5 votes vote down vote up
package com.test.week5

import akka.actor.Status.Failure
import akka.actor.{ Actor, ActorRef, Props }
import akka.event.LoggingReceive
import akka.pattern.ask
import com.test.TestSpec

class BankAccountTest extends TestSpec {

  "Actors" should "know itself" in {
    val ref: ActorRef = system.actorOf(Props(new Actor {
      override def receive: Receive = {
        case _ ⇒ sender() ! self
      }
    }))

    (ref ? "").futureValue shouldBe ref
    cleanup(ref)
  }

  it should "count" in {
    val ref: ActorRef = system.actorOf(Props(new Actor {
      def count(num: Int): Receive = LoggingReceive {
        case _ ⇒
          context.become(count(num + 1))
          sender() ! num
      }
      override def receive: Receive = LoggingReceive(count(0))
    }))
    (ref ? "").futureValue shouldBe 0
    (ref ? "").futureValue shouldBe 1
    (ref ? "").futureValue shouldBe 2
    (ref ? "").futureValue shouldBe 3
    cleanup(ref)
  }

  it should "be a BankAccount" in {
    object BankAccount {
      case class Transfer(from: ActorRef, to: ActorRef, amount: BigInt)
      case class Deposit(amount: BigInt)
      case class Withdraw(amount: BigInt)
      case object Info
      case class Done(amount: BigInt)
      case object Failed
    }
    class BankAccount extends Actor {
      import BankAccount._
      var balance: BigInt = BigInt(0)
      override def receive: Receive = LoggingReceive {
        case Deposit(amount) ⇒
          balance += amount
          sender() ! Done(balance)
        case Withdraw(amount) ⇒
          balance -= amount
          sender() ! Done(balance)
        case Info ⇒
          sender() ! Done(balance)
        case _ ⇒ sender() ! Failure
      }
    }

    import BankAccount._
    val account1 = system.actorOf(Props(new BankAccount))
    (account1 ? Info).futureValue shouldBe Done(0)
    (account1 ? Deposit(100)).futureValue shouldBe Done(100)
    (account1 ? Deposit(100)).futureValue shouldBe Done(200)

    val account2 = system.actorOf(Props(new BankAccount))

    val tom = system.actorOf(Props(new Actor {
      def awaitDeposit(client: ActorRef): Receive = LoggingReceive {
        case Done(amount) ⇒
          client ! Done(amount)
          context.stop(self)
      }
      def awaitWithdraw(to: ActorRef, amount: BigInt, client: ActorRef): Receive = LoggingReceive {
        case Done(_) ⇒
          to ! Deposit(amount)
          context.become(awaitDeposit(client))
        case Failed ⇒
          client ! Failed
          context.stop(self)
      }
      override def receive = {
        case Transfer(from, to, amount) ⇒
          from ! Withdraw(amount)
          context.become(awaitWithdraw(to, amount, sender()))
      }
    }))

    (tom ? Transfer(account1, account2, 50)).futureValue shouldBe Done(50)
    (account1 ? Info).futureValue shouldBe Done(150)
    (account2 ? Info).futureValue shouldBe Done(50)
    cleanup(account1, account2, tom)
  }
} 
Example 9
Source File: CounterTest.scala    From reactive-programming   with Apache License 2.0 5 votes vote down vote up
package com.test.week5

import akka.actor.{ Actor, Props }
import akka.event.LoggingReceive
import com.test.TestSpec

class CounterTest extends TestSpec {

  class Counter extends Actor {

    def counter(n: Int): Receive = LoggingReceive {
      case "incr" ⇒ context.become(counter(n + 1))
      case "get"  ⇒ sender() ! n
    }

    override def receive = counter(0)
  }

  "counter" should "increment" in {
    val counter = system.actorOf(Props(new Counter), "counter")
    val p = probe
    p.send(counter, "incr")
    p.send(counter, "get")
    p.expectMsg(1)
    p.send(counter, "incr")
    p.send(counter, "get")
    p.expectMsg(2)
    cleanup(counter)
  }
}