=doc #3689 Don't rewrite arrows in doc and samples

This commit is contained in:
Patrik Nordwall 2013-12-03 16:34:26 +01:00
parent 37f8f2831b
commit 5a019c0a7a
61 changed files with 531 additions and 517 deletions

View file

@ -3,7 +3,7 @@ package docs.osgi
case object SomeMessage case object SomeMessage
class SomeActor extends akka.actor.Actor { class SomeActor extends akka.actor.Actor {
def receive = { case SomeMessage } def receive = { case SomeMessage => }
} }
//#Activator //#Activator

View file

@ -35,9 +35,9 @@ class DangerousActor extends Actor with ActorLogging {
def dangerousCall: String = "This really isn't that dangerous of a call after all" def dangerousCall: String = "This really isn't that dangerous of a call after all"
def receive = { def receive = {
case "is my middle name" case "is my middle name" =>
breaker.withCircuitBreaker(Future(dangerousCall)) pipeTo sender breaker.withCircuitBreaker(Future(dangerousCall)) pipeTo sender
case "block for me" case "block for me" =>
sender ! breaker.withSyncCircuitBreaker(dangerousCall) sender ! breaker.withSyncCircuitBreaker(dangerousCall)
} }
//#circuit-breaker-usage //#circuit-breaker-usage

View file

@ -65,7 +65,7 @@ epub_cover = ("../_sphinx/static/akka.png", "")
def setup(app): def setup(app):
from sphinx.util.texescape import tex_replacements from sphinx.util.texescape import tex_replacements
tex_replacements.append((u'', ur'\(\Rightarrow\)')) tex_replacements.append((u'=>', ur'\(\Rightarrow\)'))
latex_paper_size = 'a4' latex_paper_size = 'a4'
latex_font_size = '10pt' latex_font_size = '10pt'

View file

@ -26,8 +26,8 @@ import scala.concurrent.Await
class MyActor extends Actor { class MyActor extends Actor {
val log = Logging(context.system, this) val log = Logging(context.system, this)
def receive = { def receive = {
case "test" log.info("received test") case "test" => log.info("received test")
case _ log.info("received unknown message") case _ => log.info("received unknown message")
} }
} }
//#my-actor //#my-actor
@ -40,14 +40,14 @@ class FirstActor extends Actor {
val child = context.actorOf(Props[MyActor], name = "myChild") val child = context.actorOf(Props[MyActor], name = "myChild")
//#plus-some-behavior //#plus-some-behavior
def receive = { def receive = {
case x sender ! x case x => sender ! x
} }
//#plus-some-behavior //#plus-some-behavior
} }
//#context-actorOf //#context-actorOf
class ActorWithArgs(arg: String) extends Actor { class ActorWithArgs(arg: String) extends Actor {
def receive = { case _ () } def receive = { case _ => () }
} }
class DemoActorWrapper extends Actor { class DemoActorWrapper extends Actor {
@ -64,7 +64,7 @@ class DemoActorWrapper extends Actor {
class DemoActor(magicNumber: Int) extends Actor { class DemoActor(magicNumber: Int) extends Actor {
def receive = { def receive = {
case x: Int sender ! (x + magicNumber) case x: Int => sender ! (x + magicNumber)
} }
} }
@ -79,10 +79,10 @@ class DemoActorWrapper extends Actor {
class AnonymousActor extends Actor { class AnonymousActor extends Actor {
//#anonymous-actor //#anonymous-actor
def receive = { def receive = {
case m: DoIt case m: DoIt =>
context.actorOf(Props(new Actor { context.actorOf(Props(new Actor {
def receive = { def receive = {
case DoIt(msg) case DoIt(msg) =>
val replyMsg = doSomeDangerousWork(msg) val replyMsg = doSomeDangerousWork(msg)
sender ! replyMsg sender ! replyMsg
context.stop(self) context.stop(self)
@ -112,13 +112,13 @@ class Hook extends Actor {
class ReplyException extends Actor { class ReplyException extends Actor {
def receive = { def receive = {
case _ case _ =>
//#reply-exception //#reply-exception
try { try {
val result = operation() val result = operation()
sender ! result sender ! result
} catch { } catch {
case e: Exception case e: Exception =>
sender ! akka.actor.Status.Failure(e) sender ! akka.actor.Status.Failure(e)
throw e throw e
} }
@ -136,10 +136,10 @@ class Swapper extends Actor {
val log = Logging(system, this) val log = Logging(system, this)
def receive = { def receive = {
case Swap case Swap =>
log.info("Hi") log.info("Hi")
become({ become({
case Swap case Swap =>
log.info("Ho") log.info("Ho")
unbecome() // resets the latest 'become' (just for fun) unbecome() // resets the latest 'become' (just for fun)
}, discardOld = false) // push on top instead of replace }, discardOld = false) // push on top instead of replace
@ -166,7 +166,7 @@ abstract class GenericActor extends Actor {
// generic message handler // generic message handler
def genericMessageHandler: Receive = { def genericMessageHandler: Receive = {
case event printf("generic: %s\n", event) case event => printf("generic: %s\n", event)
} }
def receive = specificMessageHandler orElse genericMessageHandler def receive = specificMessageHandler orElse genericMessageHandler
@ -174,7 +174,7 @@ abstract class GenericActor extends Actor {
class SpecificActor extends GenericActor { class SpecificActor extends GenericActor {
def specificMessageHandler = { def specificMessageHandler = {
case event: MyMsg printf("specific: %s\n", event.subject) case event: MyMsg => printf("specific: %s\n", event.subject)
} }
} }
@ -190,7 +190,7 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
import context._ import context._
val myActor = actorOf(Props[MyActor], name = "myactor") val myActor = actorOf(Props[MyActor], name = "myactor")
def receive = { def receive = {
case x myActor ! x case x => myActor ! x
} }
} }
//#import-context //#import-context
@ -207,17 +207,17 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
// TODO: convert docs to AkkaSpec(Map(...)) // TODO: convert docs to AkkaSpec(Map(...))
val filter = EventFilter.custom { val filter = EventFilter.custom {
case e: Logging.Info true case e: Logging.Info => true
case _ false case _ => false
} }
system.eventStream.publish(TestEvent.Mute(filter)) system.eventStream.publish(TestEvent.Mute(filter))
system.eventStream.subscribe(testActor, classOf[Logging.Info]) system.eventStream.subscribe(testActor, classOf[Logging.Info])
myActor ! "test" myActor ! "test"
expectMsgPF(1 second) { case Logging.Info(_, _, "received test") true } expectMsgPF(1 second) { case Logging.Info(_, _, "received test") => true }
myActor ! "unknown" myActor ! "unknown"
expectMsgPF(1 second) { case Logging.Info(_, _, "received unknown message") true } expectMsgPF(1 second) { case Logging.Info(_, _, "received unknown message") => true }
system.eventStream.unsubscribe(testActor) system.eventStream.unsubscribe(testActor)
system.eventStream.publish(TestEvent.UnMute(filter)) system.eventStream.publish(TestEvent.UnMute(filter))
@ -245,7 +245,7 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
//#creating-props-deprecated //#creating-props-deprecated
// DEPRECATED: old case class signature // DEPRECATED: old case class signature
val props4 = Props( val props4 = Props(
creator = { () new MyActor }, creator = { () => new MyActor },
dispatcher = "my-dispatcher") dispatcher = "my-dispatcher")
// DEPRECATED due to duplicate functionality with Props.apply() // DEPRECATED due to duplicate functionality with Props.apply()
@ -273,8 +273,8 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
"creating actor with IndirectActorProducer" in { "creating actor with IndirectActorProducer" in {
class Echo(name: String) extends Actor { class Echo(name: String) extends Actor {
def receive = { def receive = {
case n: Int sender ! name case n: Int => sender ! name
case message case message =>
val target = testActor val target = testActor
//#forward //#forward
target forward message target forward message
@ -348,10 +348,10 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
// To set an initial delay // To set an initial delay
context.setReceiveTimeout(30 milliseconds) context.setReceiveTimeout(30 milliseconds)
def receive = { def receive = {
case "Hello" case "Hello" =>
// To set in a response to a message // To set in a response to a message
context.setReceiveTimeout(100 milliseconds) context.setReceiveTimeout(100 milliseconds)
case ReceiveTimeout case ReceiveTimeout =>
// To turn it off // To turn it off
context.setReceiveTimeout(Duration.Undefined) context.setReceiveTimeout(Duration.Undefined)
throw new RuntimeException("Receive timed out") throw new RuntimeException("Receive timed out")
@ -364,18 +364,18 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
class HotSwapActor extends Actor { class HotSwapActor extends Actor {
import context._ import context._
def angry: Receive = { def angry: Receive = {
case "foo" sender ! "I am already angry?" case "foo" => sender ! "I am already angry?"
case "bar" become(happy) case "bar" => become(happy)
} }
def happy: Receive = { def happy: Receive = {
case "bar" sender ! "I am already happy :-)" case "bar" => sender ! "I am already happy :-)"
case "foo" become(angry) case "foo" => become(angry)
} }
def receive = { def receive = {
case "foo" become(angry) case "foo" => become(angry)
case "bar" become(happy) case "bar" => become(happy)
} }
} }
//#hot-swap-actor //#hot-swap-actor
@ -389,16 +389,16 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
import akka.actor.Stash import akka.actor.Stash
class ActorWithProtocol extends Actor with Stash { class ActorWithProtocol extends Actor with Stash {
def receive = { def receive = {
case "open" case "open" =>
unstashAll() unstashAll()
context.become({ context.become({
case "write" // do writing... case "write" => // do writing...
case "close" case "close" =>
unstashAll() unstashAll()
context.unbecome() context.unbecome()
case msg stash() case msg => stash()
}, discardOld = false) // stack on top instead of replacing }, discardOld = false) // stack on top instead of replacing
case msg stash() case msg => stash()
} }
} }
//#stash //#stash
@ -415,9 +415,9 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
var lastSender = system.deadLetters var lastSender = system.deadLetters
def receive = { def receive = {
case "kill" case "kill" =>
context.stop(child); lastSender = sender context.stop(child); lastSender = sender
case Terminated(`child`) lastSender ! "finished" case Terminated(`child`) => lastSender ! "finished"
} }
} }
//#watch //#watch
@ -457,15 +457,15 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
context.actorSelection("/user/another") ! Identify(identifyId) context.actorSelection("/user/another") ! Identify(identifyId)
def receive = { def receive = {
case ActorIdentity(`identifyId`, Some(ref)) case ActorIdentity(`identifyId`, Some(ref)) =>
context.watch(ref) context.watch(ref)
context.become(active(ref)) context.become(active(ref))
case ActorIdentity(`identifyId`, None) context.stop(self) case ActorIdentity(`identifyId`, None) => context.stop(self)
} }
def active(another: ActorRef): Actor.Receive = { def active(another: ActorRef): Actor.Receive = {
case Terminated(`another`) context.stop(self) case Terminated(`another`) => context.stop(self)
} }
} }
//#identify //#identify
@ -490,7 +490,7 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
// the actor has been stopped // the actor has been stopped
} catch { } catch {
// the actor wasn't stopped within 5 seconds // the actor wasn't stopped within 5 seconds
case e: akka.pattern.AskTimeoutException case e: akka.pattern.AskTimeoutException =>
} }
//#gracefulStop //#gracefulStop
} }
@ -507,9 +507,9 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
val f: Future[Result] = val f: Future[Result] =
for { for {
x ask(actorA, Request).mapTo[Int] // call pattern directly x <- ask(actorA, Request).mapTo[Int] // call pattern directly
s (actorB ask Request).mapTo[String] // call by implicit conversion s <- (actorB ask Request).mapTo[String] // call by implicit conversion
d (actorC ? Request).mapTo[Double] // call by symbolic name d <- (actorC ? Request).mapTo[Double] // call by symbolic name
} yield Result(x, s, d) } yield Result(x, s, d)
f pipeTo actorD // .. or .. f pipeTo actorD // .. or ..
@ -519,12 +519,12 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
class Replier extends Actor { class Replier extends Actor {
def receive = { def receive = {
case ref: ActorRef case ref: ActorRef =>
//#reply-with-sender //#reply-with-sender
sender.tell("reply", context.parent) // replies will go back to parent sender.tell("reply", context.parent) // replies will go back to parent
sender.!("reply")(context.parent) // alternative syntax (beware of the parens!) sender.!("reply")(context.parent) // alternative syntax (beware of the parens!)
//#reply-with-sender //#reply-with-sender
case x case x =>
//#reply-without-sender //#reply-without-sender
sender ! x // replies will go to this actor sender ! x // replies will go to this actor
//#reply-without-sender //#reply-without-sender
@ -547,8 +547,8 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
"using ActorDSL outside of akka.actor package" in { "using ActorDSL outside of akka.actor package" in {
import akka.actor.ActorDSL._ import akka.actor.ActorDSL._
actor(new Act { actor(new Act {
superviseWith(OneForOneStrategy() { case _ Stop; Restart; Resume; Escalate }) superviseWith(OneForOneStrategy() { case _ => Stop; Restart; Resume; Escalate })
superviseWith(AllForOneStrategy() { case _ Stop; Restart; Resume; Escalate }) superviseWith(AllForOneStrategy() { case _ => Stop; Restart; Resume; Escalate })
}) })
} }
@ -561,9 +561,9 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
private var pfsOption: Option[Vector[PF]] = Some(Vector.empty) private var pfsOption: Option[Vector[PF]] = Some(Vector.empty)
private def mapPfs[C](f: Vector[PF] (Option[Vector[PF]], C)): C = { private def mapPfs[C](f: Vector[PF] => (Option[Vector[PF]], C)): C = {
pfsOption.fold(throw new IllegalStateException("Already built"))(f) match { pfsOption.fold(throw new IllegalStateException("Already built"))(f) match {
case (newPfsOption, result) { case (newPfsOption, result) => {
pfsOption = newPfsOption pfsOption = newPfsOption
result result
} }
@ -571,10 +571,10 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
} }
def +=(pf: PF): Unit = def +=(pf: PF): Unit =
mapPfs { case pfs (Some(pfs :+ pf), ()) } mapPfs { case pfs => (Some(pfs :+ pf), ()) }
def result(): PF = def result(): PF =
mapPfs { case pfs (None, pfs.foldLeft[PF](Map.empty) { _ orElse _ }) } mapPfs { case pfs => (None, pfs.foldLeft[PF](Map.empty) { _ orElse _ }) }
} }
trait ComposableActor extends Actor { trait ComposableActor extends Actor {
@ -584,13 +584,13 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
trait TheirComposableActor extends ComposableActor { trait TheirComposableActor extends ComposableActor {
receiveBuilder += { receiveBuilder += {
case "foo" sender ! "foo received" case "foo" => sender ! "foo received"
} }
} }
class MyComposableActor extends TheirComposableActor { class MyComposableActor extends TheirComposableActor {
receiveBuilder += { receiveBuilder += {
case "bar" sender ! "bar received" case "bar" => sender ! "bar received"
} }
} }
//#receive-orElse2 //#receive-orElse2

View file

@ -5,7 +5,7 @@ package docs.actor
import language.postfixOps import language.postfixOps
import akka.testkit.{ AkkaSpec MyFavoriteTestFrameWorkPlusAkkaTestKit } import akka.testkit.{ AkkaSpec => MyFavoriteTestFrameWorkPlusAkkaTestKit }
import akka.util.ByteString import akka.util.ByteString
//#test-code //#test-code
@ -46,23 +46,23 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit {
//#when-syntax //#when-syntax
when(Idle) { when(Idle) {
case Event(SetTarget(ref), Uninitialized) case Event(SetTarget(ref), Uninitialized) =>
stay using Todo(ref, Vector.empty) stay using Todo(ref, Vector.empty)
} }
//#when-syntax //#when-syntax
//#transition-elided //#transition-elided
onTransition { onTransition {
case Active -> Idle case Active -> Idle =>
stateData match { stateData match {
case Todo(ref, queue) ref ! Batch(queue) case Todo(ref, queue) => ref ! Batch(queue)
} }
} }
//#transition-elided //#transition-elided
//#when-syntax //#when-syntax
when(Active, stateTimeout = 1 second) { when(Active, stateTimeout = 1 second) {
case Event(Flush | StateTimeout, t: Todo) case Event(Flush | StateTimeout, t: Todo) =>
goto(Idle) using t.copy(queue = Vector.empty) goto(Idle) using t.copy(queue = Vector.empty)
} }
//#when-syntax //#when-syntax
@ -70,10 +70,10 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit {
//#unhandled-elided //#unhandled-elided
whenUnhandled { whenUnhandled {
// common code for both states // common code for both states
case Event(Queue(obj), t @ Todo(_, v)) case Event(Queue(obj), t @ Todo(_, v)) =>
goto(Active) using t.copy(queue = v :+ obj) goto(Active) using t.copy(queue = v :+ obj)
case Event(e, s) case Event(e, s) =>
log.warning("received unhandled request {} in state {}/{}", e, stateName, s) log.warning("received unhandled request {} in state {}/{}", e, stateName, s)
stay stay
} }
@ -99,16 +99,16 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit {
//#modifier-syntax //#modifier-syntax
when(SomeState) { when(SomeState) {
case Event(msg, _) case Event(msg, _) =>
goto(Processing) using (newData) forMax (5 seconds) replying (WillDo) goto(Processing) using (newData) forMax (5 seconds) replying (WillDo)
} }
//#modifier-syntax //#modifier-syntax
//#transition-syntax //#transition-syntax
onTransition { onTransition {
case Idle -> Active setTimer("timeout", Tick, 1 second, true) case Idle -> Active => setTimer("timeout", Tick, 1 second, true)
case Active -> _ cancelTimer("timeout") case Active -> _ => cancelTimer("timeout")
case x -> Idle log.info("entering Idle from " + x) case x -> Idle => log.info("entering Idle from " + x)
} }
//#transition-syntax //#transition-syntax
@ -122,7 +122,7 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit {
//#stop-syntax //#stop-syntax
when(Error) { when(Error) {
case Event("stop", _) case Event("stop", _) =>
// do cleanup ... // do cleanup ...
stop() stop()
} }
@ -130,38 +130,38 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit {
//#transform-syntax //#transform-syntax
when(SomeState)(transform { when(SomeState)(transform {
case Event(bytes: ByteString, read) stay using (read + bytes.length) case Event(bytes: ByteString, read) => stay using (read + bytes.length)
} using { } using {
case s @ FSM.State(state, read, timeout, stopReason, replies) if read > 1000 case s @ FSM.State(state, read, timeout, stopReason, replies) if read > 1000 =>
goto(Processing) goto(Processing)
}) })
//#transform-syntax //#transform-syntax
//#alt-transform-syntax //#alt-transform-syntax
val processingTrigger: PartialFunction[State, State] = { val processingTrigger: PartialFunction[State, State] = {
case s @ FSM.State(state, read, timeout, stopReason, replies) if read > 1000 case s @ FSM.State(state, read, timeout, stopReason, replies) if read > 1000 =>
goto(Processing) goto(Processing)
} }
when(SomeState)(transform { when(SomeState)(transform {
case Event(bytes: ByteString, read) stay using (read + bytes.length) case Event(bytes: ByteString, read) => stay using (read + bytes.length)
} using processingTrigger) } using processingTrigger)
//#alt-transform-syntax //#alt-transform-syntax
//#termination-syntax //#termination-syntax
onTermination { onTermination {
case StopEvent(FSM.Normal, state, data) // ... case StopEvent(FSM.Normal, state, data) => // ...
case StopEvent(FSM.Shutdown, state, data) // ... case StopEvent(FSM.Shutdown, state, data) => // ...
case StopEvent(FSM.Failure(cause), state, data) // ... case StopEvent(FSM.Failure(cause), state, data) => // ...
} }
//#termination-syntax //#termination-syntax
//#unhandled-syntax //#unhandled-syntax
whenUnhandled { whenUnhandled {
case Event(x: X, data) case Event(x: X, data) =>
log.info("Received unhandled event: " + x) log.info("Received unhandled event: " + x)
stay stay
case Event(msg, _) case Event(msg, _) =>
log.warning("Received unknown event: " + msg) log.warning("Received unknown event: " + msg)
goto(Error) goto(Error)
} }
@ -175,7 +175,7 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit {
//#body-elided //#body-elided
override def logDepth = 12 override def logDepth = 12
onTermination { onTermination {
case StopEvent(FSM.Failure(_), state, data) case StopEvent(FSM.Failure(_), state, data) =>
val lastEvents = getLog.mkString("\n\t") val lastEvents = getLog.mkString("\n\t")
log.warning("Failure in state " + state + " with data " + data + "\n" + log.warning("Failure in state " + state + " with data " + data + "\n" +
"Events leading up to this point:\n\t" + lastEvents) "Events leading up to this point:\n\t" + lastEvents)

View file

@ -49,14 +49,14 @@ class Listener extends Actor with ActorLogging {
context.setReceiveTimeout(15 seconds) context.setReceiveTimeout(15 seconds)
def receive = { def receive = {
case Progress(percent) case Progress(percent) =>
log.info("Current progress: {} %", percent) log.info("Current progress: {} %", percent)
if (percent >= 100.0) { if (percent >= 100.0) {
log.info("That's all, shutting down") log.info("That's all, shutting down")
context.system.shutdown() context.system.shutdown()
} }
case ReceiveTimeout case ReceiveTimeout =>
// No progress within 15 seconds, ServiceUnavailable // No progress within 15 seconds, ServiceUnavailable
log.error("Shutting down due to unavailable service") log.error("Shutting down due to unavailable service")
context.system.shutdown() context.system.shutdown()
@ -83,7 +83,7 @@ class Worker extends Actor with ActorLogging {
// Stop the CounterService child if it throws ServiceUnavailable // Stop the CounterService child if it throws ServiceUnavailable
override val supervisorStrategy = OneForOneStrategy() { override val supervisorStrategy = OneForOneStrategy() {
case _: CounterService.ServiceUnavailable Stop case _: CounterService.ServiceUnavailable => Stop
} }
// The sender of the initial Start message will continuously be notified // The sender of the initial Start message will continuously be notified
@ -94,18 +94,18 @@ class Worker extends Actor with ActorLogging {
import context.dispatcher // Use this Actors' Dispatcher as ExecutionContext import context.dispatcher // Use this Actors' Dispatcher as ExecutionContext
def receive = LoggingReceive { def receive = LoggingReceive {
case Start if progressListener.isEmpty case Start if progressListener.isEmpty =>
progressListener = Some(sender) progressListener = Some(sender)
context.system.scheduler.schedule(Duration.Zero, 1 second, self, Do) context.system.scheduler.schedule(Duration.Zero, 1 second, self, Do)
case Do case Do =>
counterService ! Increment(1) counterService ! Increment(1)
counterService ! Increment(1) counterService ! Increment(1)
counterService ! Increment(1) counterService ! Increment(1)
// Send current progress to the initial sender // Send current progress to the initial sender
counterService ? GetCurrentCount map { counterService ? GetCurrentCount map {
case CurrentCount(_, count) Progress(100.0 * count / totalCount) case CurrentCount(_, count) => Progress(100.0 * count / totalCount)
} pipeTo progressListener.get } pipeTo progressListener.get
} }
} }
@ -135,7 +135,7 @@ class CounterService extends Actor {
// After 3 restarts within 5 seconds it will be stopped. // After 3 restarts within 5 seconds it will be stopped.
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 3, override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 3,
withinTimeRange = 5 seconds) { withinTimeRange = 5 seconds) {
case _: Storage.StorageException Restart case _: Storage.StorageException => Restart
} }
val key = self.path.name val key = self.path.name
@ -166,21 +166,21 @@ class CounterService extends Actor {
def receive = LoggingReceive { def receive = LoggingReceive {
case Entry(k, v) if k == key && counter == None case Entry(k, v) if k == key && counter == None =>
// Reply from Storage of the initial value, now we can create the Counter // Reply from Storage of the initial value, now we can create the Counter
val c = context.actorOf(Props(classOf[Counter], key, v)) val c = context.actorOf(Props(classOf[Counter], key, v))
counter = Some(c) counter = Some(c)
// Tell the counter to use current storage // Tell the counter to use current storage
c ! UseStorage(storage) c ! UseStorage(storage)
// and send the buffered backlog to the counter // and send the buffered backlog to the counter
for ((replyTo, msg) backlog) c.tell(msg, sender = replyTo) for ((replyTo, msg) <- backlog) c.tell(msg, sender = replyTo)
backlog = IndexedSeq.empty backlog = IndexedSeq.empty
case msg @ Increment(n) forwardOrPlaceInBacklog(msg) case msg @ Increment(n) => forwardOrPlaceInBacklog(msg)
case msg @ GetCurrentCount forwardOrPlaceInBacklog(msg) case msg @ GetCurrentCount => forwardOrPlaceInBacklog(msg)
case Terminated(actorRef) if Some(actorRef) == storage case Terminated(actorRef) if Some(actorRef) == storage =>
// After 3 restarts the storage child is stopped. // After 3 restarts the storage child is stopped.
// We receive Terminated because we watch the child, see initStorage. // We receive Terminated because we watch the child, see initStorage.
storage = None storage = None
@ -189,7 +189,7 @@ class CounterService extends Actor {
// Try to re-establish storage after while // Try to re-establish storage after while
context.system.scheduler.scheduleOnce(10 seconds, self, Reconnect) context.system.scheduler.scheduleOnce(10 seconds, self, Reconnect)
case Reconnect case Reconnect =>
// Re-establish storage after the scheduled delay // Re-establish storage after the scheduled delay
initStorage() initStorage()
} }
@ -199,8 +199,8 @@ class CounterService extends Actor {
// the counter. Before that we place the messages in a backlog, to be sent // the counter. Before that we place the messages in a backlog, to be sent
// to the counter when it is initialized. // to the counter when it is initialized.
counter match { counter match {
case Some(c) c forward msg case Some(c) => c forward msg
case None case None =>
if (backlog.size >= MaxBacklog) if (backlog.size >= MaxBacklog)
throw new ServiceUnavailable( throw new ServiceUnavailable(
"CounterService not available, lack of initial value") "CounterService not available, lack of initial value")
@ -230,15 +230,15 @@ class Counter(key: String, initialValue: Long) extends Actor {
var storage: Option[ActorRef] = None var storage: Option[ActorRef] = None
def receive = LoggingReceive { def receive = LoggingReceive {
case UseStorage(s) case UseStorage(s) =>
storage = s storage = s
storeCount() storeCount()
case Increment(n) case Increment(n) =>
count += n count += n
storeCount() storeCount()
case GetCurrentCount case GetCurrentCount =>
sender ! CurrentCount(key, count) sender ! CurrentCount(key, count)
} }
@ -271,8 +271,8 @@ class Storage extends Actor {
val db = DummyDB val db = DummyDB
def receive = LoggingReceive { def receive = LoggingReceive {
case Store(Entry(key, count)) db.save(key, count) case Store(Entry(key, count)) => db.save(key, count)
case Get(key) sender ! Entry(key, db.load(key).getOrElse(0L)) case Get(key) => sender ! Entry(key, db.load(key).getOrElse(0L))
} }
} }

View file

@ -26,15 +26,15 @@ object FaultHandlingDocSpec {
override val supervisorStrategy = override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
case _: ArithmeticException Resume case _: ArithmeticException => Resume
case _: NullPointerException Restart case _: NullPointerException => Restart
case _: IllegalArgumentException Stop case _: IllegalArgumentException => Stop
case _: Exception Escalate case _: Exception => Escalate
} }
//#strategy //#strategy
def receive = { def receive = {
case p: Props sender ! context.actorOf(p) case p: Props => sender ! context.actorOf(p)
} }
} }
//#supervisor //#supervisor
@ -48,15 +48,15 @@ object FaultHandlingDocSpec {
override val supervisorStrategy = override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
case _: ArithmeticException Resume case _: ArithmeticException => Resume
case _: NullPointerException Restart case _: NullPointerException => Restart
case _: IllegalArgumentException Stop case _: IllegalArgumentException => Stop
case _: Exception Escalate case _: Exception => Escalate
} }
//#strategy2 //#strategy2
def receive = { def receive = {
case p: Props sender ! context.actorOf(p) case p: Props => sender ! context.actorOf(p)
} }
// override default to kill all children during restart // override default to kill all children during restart
override def preRestart(cause: Throwable, msg: Option[Any]) {} override def preRestart(cause: Throwable, msg: Option[Any]) {}
@ -71,9 +71,9 @@ object FaultHandlingDocSpec {
override val supervisorStrategy = override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
case _: ArithmeticException Resume case _: ArithmeticException => Resume
case t case t =>
super.supervisorStrategy.decider.applyOrElse(t, (_: Any) Escalate) super.supervisorStrategy.decider.applyOrElse(t, (_: Any) => Escalate)
} }
//#default-strategy-fallback //#default-strategy-fallback
@ -85,9 +85,9 @@ object FaultHandlingDocSpec {
class Child extends Actor { class Child extends Actor {
var state = 0 var state = 0
def receive = { def receive = {
case ex: Exception throw ex case ex: Exception => throw ex
case x: Int state = x case x: Int => state = x
case "get" sender ! state case "get" => sender ! state
} }
} }
//#child //#child
@ -133,7 +133,7 @@ class FaultHandlingDocSpec extends AkkaSpec with ImplicitSender {
//#stop //#stop
watch(child) // have testActor watch child watch(child) // have testActor watch child
child ! new IllegalArgumentException // break it child ! new IllegalArgumentException // break it
expectMsgPF() { case Terminated(`child`) () } expectMsgPF() { case Terminated(`child`) => () }
//#stop //#stop
} }
EventFilter[Exception]("CRASH", occurrences = 2) intercept { EventFilter[Exception]("CRASH", occurrences = 2) intercept {
@ -147,7 +147,7 @@ class FaultHandlingDocSpec extends AkkaSpec with ImplicitSender {
child2 ! new Exception("CRASH") // escalate failure child2 ! new Exception("CRASH") // escalate failure
expectMsgPF() { expectMsgPF() {
case t @ Terminated(`child2`) if t.existenceConfirmed () case t @ Terminated(`child2`) if t.existenceConfirmed => ()
} }
//#escalate-kill //#escalate-kill
//#escalate-restart //#escalate-restart

View file

@ -10,7 +10,7 @@ object InitializationDocSpec {
class PreStartInitExample extends Actor { class PreStartInitExample extends Actor {
override def receive = { override def receive = {
case _ // Ignore case _ => // Ignore
} }
//#preStartInit //#preStartInit
@ -37,14 +37,14 @@ object InitializationDocSpec {
var initializeMe: Option[String] = None var initializeMe: Option[String] = None
override def receive = { override def receive = {
case "init" case "init" =>
initializeMe = Some("Up and running") initializeMe = Some("Up and running")
context.become(initialized, discardOld = true) context.become(initialized, discardOld = true)
} }
def initialized: Receive = { def initialized: Receive = {
case "U OK?" initializeMe foreach { sender ! _ } case "U OK?" => initializeMe foreach { sender ! _ }
} }
//#messageInit //#messageInit

View file

@ -43,7 +43,7 @@ class SchedulerDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
val Tick = "tick" val Tick = "tick"
class TickActor extends Actor { class TickActor extends Actor {
def receive = { def receive = {
case Tick //Do something case Tick => //Do something
} }
} }
val tickActor = system.actorOf(Props(classOf[TickActor], this)) val tickActor = system.actorOf(Props(classOf[TickActor], this))

View file

@ -12,7 +12,7 @@ import org.scalatest.matchers.MustMatchers
import akka.testkit._ import akka.testkit._
//Mr funny man avoids printing to stdout AND keeping docs alright //Mr funny man avoids printing to stdout AND keeping docs alright
import java.lang.String.{ valueOf println } import java.lang.String.{ valueOf => println }
import akka.actor.ActorRef import akka.actor.ActorRef
//#typed-actor-iface //#typed-actor-iface
@ -91,7 +91,7 @@ class TypedActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
//#typed-actor-extension-tools //#typed-actor-extension-tools
} catch { } catch {
case e: Exception //dun care case e: Exception => //dun care
} }
} }
@ -160,7 +160,7 @@ class TypedActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
//Use "childSquarer" as a Squarer //Use "childSquarer" as a Squarer
//#typed-actor-hierarchy //#typed-actor-hierarchy
} catch { } catch {
case e: Exception //ignore case e: Exception => //ignore
} }
} }

View file

@ -34,16 +34,16 @@ class UnnestedReceives extends Actor {
} }
def receive = { def receive = {
case 'Replay //Our first message should be a 'Replay message, all others are invalid case 'Replay => //Our first message should be a 'Replay message, all others are invalid
allOldMessages() foreach process //Process all old messages/events allOldMessages() foreach process //Process all old messages/events
become { //Switch behavior to look for the GoAhead signal become { //Switch behavior to look for the GoAhead signal
case 'GoAhead //When we get the GoAhead signal we process all our buffered messages/events case 'GoAhead => //When we get the GoAhead signal we process all our buffered messages/events
queue foreach process queue foreach process
queue.clear queue.clear
become { //Then we change behaviour to process incoming messages/events as they arrive become { //Then we change behaviour to process incoming messages/events as they arrive
case msg process(msg) case msg => process(msg)
} }
case msg //While we haven't gotten the GoAhead signal, buffer all incoming messages case msg => //While we haven't gotten the GoAhead signal, buffer all incoming messages
queue += msg //Here you have full control, you can handle overflow etc queue += msg //Here you have full control, you can handle overflow etc
} }
} }

View file

@ -17,7 +17,7 @@ import akka.actor.{ Actor, ExtendedActorSystem }
class MyActor extends Actor { class MyActor extends Actor {
def receive = { def receive = {
case x case x =>
} }
} }
@ -61,8 +61,8 @@ class MyMailboxType(systemSettings: ActorSystem.Settings, config: Config)
override def create(owner: Option[ActorRef], override def create(owner: Option[ActorRef],
system: Option[ActorSystem]): MessageQueue = system: Option[ActorSystem]): MessageQueue =
(owner zip system) headOption match { (owner zip system) headOption match {
case Some((o, s: ExtendedActorSystem)) new MyMessageQueue(o, s) case Some((o, s: ExtendedActorSystem)) => new MyMessageQueue(o, s)
case _ case _ =>
throw new IllegalArgumentException("requires an owner " + throw new IllegalArgumentException("requires an owner " +
"(i.e. does not work with BalancingDispatcher)") "(i.e. does not work with BalancingDispatcher)")
} }

View file

@ -58,7 +58,7 @@ class AgentDocSpec extends AkkaSpec {
agent send (_ * 2) agent send (_ * 2)
//#send //#send
def longRunningOrBlockingFunction = (i: Int) i * 1 // Just for the example code def longRunningOrBlockingFunction = (i: Int) => i * 1 // Just for the example code
def someExecutionContext() = scala.concurrent.ExecutionContext.Implicits.global // Just for the example code def someExecutionContext() = scala.concurrent.ExecutionContext.Implicits.global // Just for the example code
//#send-off //#send-off
// the ExecutionContext you want to run the function on // the ExecutionContext you want to run the function on
@ -81,7 +81,7 @@ class AgentDocSpec extends AkkaSpec {
val f3: Future[Int] = agent alter (_ * 2) val f3: Future[Int] = agent alter (_ * 2)
//#alter //#alter
def longRunningOrBlockingFunction = (i: Int) i * 1 // Just for the example code def longRunningOrBlockingFunction = (i: Int) => i * 1 // Just for the example code
def someExecutionContext() = ExecutionContext.global // Just for the example code def someExecutionContext() = ExecutionContext.global // Just for the example code
//#alter-off //#alter-off
@ -102,7 +102,7 @@ class AgentDocSpec extends AkkaSpec {
import scala.concurrent.stm._ import scala.concurrent.stm._
def transfer(from: Agent[Int], to: Agent[Int], amount: Int): Boolean = { def transfer(from: Agent[Int], to: Agent[Int], amount: Int): Boolean = {
atomic { txn atomic { txn =>
if (from.get < amount) false if (from.get < amount) false
else { else {
from send (_ - amount) from send (_ - amount)
@ -133,19 +133,19 @@ class AgentDocSpec extends AkkaSpec {
val agent2 = Agent(5) val agent2 = Agent(5)
// uses foreach // uses foreach
for (value agent1) for (value <- agent1)
println(value) println(value)
// uses map // uses map
val agent3 = for (value agent1) yield value + 1 val agent3 = for (value <- agent1) yield value + 1
// or using map directly // or using map directly
val agent4 = agent1 map (_ + 1) val agent4 = agent1 map (_ + 1)
// uses flatMap // uses flatMap
val agent5 = for { val agent5 = for {
value1 agent1 value1 <- agent1
value2 agent2 value2 <- agent2
} yield value1 + value2 } yield value1 + value2
//#monadic-example //#monadic-example

View file

@ -15,7 +15,7 @@ object Consumers {
def endpointUri = "file:data/input/actor" def endpointUri = "file:data/input/actor"
def receive = { def receive = {
case msg: CamelMessage println("received %s" format msg.bodyAs[String]) case msg: CamelMessage => println("received %s" format msg.bodyAs[String])
} }
} }
//#Consumer1 //#Consumer1
@ -28,7 +28,7 @@ object Consumers {
def endpointUri = "jetty:http://localhost:8877/camel/default" def endpointUri = "jetty:http://localhost:8877/camel/default"
def receive = { def receive = {
case msg: CamelMessage sender ! ("Hello %s" format msg.bodyAs[String]) case msg: CamelMessage => sender ! ("Hello %s" format msg.bodyAs[String])
} }
} }
//#Consumer2 //#Consumer2
@ -45,7 +45,7 @@ object Consumers {
def endpointUri = "jms:queue:test" def endpointUri = "jms:queue:test"
def receive = { def receive = {
case msg: CamelMessage case msg: CamelMessage =>
sender ! Ack sender ! Ack
// on success // on success
// .. // ..
@ -65,7 +65,7 @@ object Consumers {
def endpointUri = "jetty:http://localhost:8877/camel/default" def endpointUri = "jetty:http://localhost:8877/camel/default"
override def replyTimeout = 500 millis override def replyTimeout = 500 millis
def receive = { def receive = {
case msg: CamelMessage sender ! ("Hello %s" format msg.bodyAs[String]) case msg: CamelMessage => sender ! ("Hello %s" format msg.bodyAs[String])
} }
} }
//#Consumer4 //#Consumer4

View file

@ -18,9 +18,9 @@ object CustomRoute {
import akka.camel._ import akka.camel._
class Responder extends Actor { class Responder extends Actor {
def receive = { def receive = {
case msg: CamelMessage case msg: CamelMessage =>
sender ! (msg.mapBody { sender ! (msg.mapBody {
body: String "received %s" format body body: String => "received %s" format body
}) })
} }
} }
@ -47,9 +47,9 @@ object CustomRoute {
class ErrorThrowingConsumer(override val endpointUri: String) extends Consumer { class ErrorThrowingConsumer(override val endpointUri: String) extends Consumer {
def receive = { def receive = {
case msg: CamelMessage throw new Exception("error: %s" format msg.body) case msg: CamelMessage => throw new Exception("error: %s" format msg.body)
} }
override def onRouteDefinition = (rd) rd.onException(classOf[Exception]). override def onRouteDefinition = (rd) => rd.onException(classOf[Exception]).
handled(true).transform(Builder.exceptionMessage).end handled(true).transform(Builder.exceptionMessage).end
final override def preRestart(reason: Throwable, message: Option[Any]) { final override def preRestart(reason: Throwable, message: Option[Any]) {

View file

@ -15,8 +15,8 @@ object Introduction {
def endpointUri = "mina2:tcp://localhost:6200?textline=true" def endpointUri = "mina2:tcp://localhost:6200?textline=true"
def receive = { def receive = {
case msg: CamelMessage { /* ... */ } case msg: CamelMessage => { /* ... */ }
case _ { /* ... */ } case _ => { /* ... */ }
} }
} }
@ -35,8 +35,8 @@ object Introduction {
def endpointUri = "jetty:http://localhost:8877/example" def endpointUri = "jetty:http://localhost:8877/example"
def receive = { def receive = {
case msg: CamelMessage { /* ... */ } case msg: CamelMessage => { /* ... */ }
case _ { /* ... */ } case _ => { /* ... */ }
} }
} }
//#Consumer //#Consumer
@ -85,8 +85,8 @@ object Introduction {
def endpointUri = "mina2:tcp://localhost:6200?textline=true" def endpointUri = "mina2:tcp://localhost:6200?textline=true"
def receive = { def receive = {
case msg: CamelMessage { /* ... */ } case msg: CamelMessage => { /* ... */ }
case _ { /* ... */ } case _ => { /* ... */ }
} }
} }
val system = ActorSystem("some-system") val system = ActorSystem("some-system")

View file

@ -33,7 +33,7 @@ object Producers {
class ResponseReceiver extends Actor { class ResponseReceiver extends Actor {
def receive = { def receive = {
case msg: CamelMessage case msg: CamelMessage =>
// do something with the forwarded response // do something with the forwarded response
} }
} }
@ -61,11 +61,11 @@ object Producers {
def endpointUri = uri def endpointUri = uri
def upperCase(msg: CamelMessage) = msg.mapBody { def upperCase(msg: CamelMessage) = msg.mapBody {
body: String body.toUpperCase body: String => body.toUpperCase
} }
override def transformOutgoingMessage(msg: Any) = msg match { override def transformOutgoingMessage(msg: Any) = msg match {
case msg: CamelMessage upperCase(msg) case msg: CamelMessage => upperCase(msg)
} }
} }
//#TransformOutgoingMessage //#TransformOutgoingMessage
@ -106,7 +106,7 @@ object Producers {
import akka.actor.Actor import akka.actor.Actor
class MyActor extends Actor { class MyActor extends Actor {
def receive = { def receive = {
case msg case msg =>
val template = CamelExtension(context.system).template val template = CamelExtension(context.system).template
template.sendBody("direct:news", msg) template.sendBody("direct:news", msg)
} }
@ -118,7 +118,7 @@ object Producers {
import akka.actor.Actor import akka.actor.Actor
class MyActor extends Actor { class MyActor extends Actor {
def receive = { def receive = {
case msg case msg =>
val template = CamelExtension(context.system).template val template = CamelExtension(context.system).template
sender ! template.requestBody("direct:news", msg) sender ! template.requestBody("direct:news", msg)
} }

View file

@ -9,7 +9,7 @@ object PublishSubscribe {
def endpointUri = uri def endpointUri = uri
def receive = { def receive = {
case msg: CamelMessage println("%s received: %s" format (name, msg.body)) case msg: CamelMessage => println("%s received: %s" format (name, msg.body))
} }
} }
@ -25,7 +25,7 @@ object PublishSubscribe {
def endpointUri = uri def endpointUri = uri
def receive = { def receive = {
case msg: CamelMessage { case msg: CamelMessage => {
publisher ! msg.bodyAs[String] publisher ! msg.bodyAs[String]
sender ! ("message published") sender ! ("message published")
} }

View file

@ -32,7 +32,7 @@ object ChannelDocSpec {
class Child extends Actor class Child extends Actor
with Channels[(Stats, Nothing) :+: TNil, (Request, Reply) :+: TNil] { with Channels[(Stats, Nothing) :+: TNil, (Request, Reply) :+: TNil] {
channel[Request] { (x, snd) channel[Request] { (x, snd) =>
parentChannel <-!- Stats(x) parentChannel <-!- Stats(x)
snd <-!- CommandSuccess snd <-!- CommandSuccess
} }
@ -43,9 +43,9 @@ object ChannelDocSpec {
val child = createChild(new Child) val child = createChild(new Child)
channel[GetChild.type] { (_, snd) ChildRef(child) -!-> snd } channel[GetChild.type] { (_, snd) => ChildRef(child) -!-> snd }
channel[Stats] { (x, _) channel[Stats] { (x, _) =>
// collect some stats // collect some stats
} }
} }
@ -89,10 +89,10 @@ class ChannelDocSpec extends AkkaSpec {
"demonstrate channels creation" ignore { "demonstrate channels creation" ignore {
//#declaring-channels //#declaring-channels
class AC extends Actor with Channels[TNil, (Request, Reply) :+: TNil] { class AC extends Actor with Channels[TNil, (Request, Reply) :+: TNil] {
channel[Request] { (req, snd) channel[Request] { (req, snd) =>
req match { req match {
case Command("ping") snd <-!- CommandSuccess case Command("ping") => snd <-!- CommandSuccess
case _ case _ =>
} }
} }
} }
@ -100,8 +100,8 @@ class ChannelDocSpec extends AkkaSpec {
//#declaring-subchannels //#declaring-subchannels
class ACSub extends Actor with Channels[TNil, (Request, Reply) :+: TNil] { class ACSub extends Actor with Channels[TNil, (Request, Reply) :+: TNil] {
channel[Command] { (cmd, snd) snd <-!- CommandSuccess } channel[Command] { (cmd, snd) => snd <-!- CommandSuccess }
channel[Request] { (req, snd) channel[Request] { (req, snd) =>
if (ThreadLocalRandom.current.nextBoolean) snd <-!- CommandSuccess if (ThreadLocalRandom.current.nextBoolean) snd <-!- CommandSuccess
else snd <-!- CommandFailure("no luck") else snd <-!- CommandFailure("no luck")
} }
@ -159,17 +159,17 @@ class ChannelDocSpec extends AkkaSpec {
//#become //#become
channel[Request] { channel[Request] {
case (Command("close"), snd) case (Command("close"), snd) =>
channel[T1] { (t, s) t -?-> target -!-> s } channel[T1] { (t, s) => t -?-> target -!-> s }
snd <-!- CommandSuccess snd <-!- CommandSuccess
case (Command("open"), snd) case (Command("open"), snd) =>
channel[T1] { (_, _) } channel[T1] { (_, _) => }
snd <-!- CommandSuccess snd <-!- CommandSuccess
} }
//#become //#become
channel[T1] { (t, snd) t -?-> target -!-> snd } channel[T1] { (t, snd) => t -?-> target -!-> snd }
} }
//#forwarding //#forwarding

View file

@ -64,7 +64,7 @@ class DataflowDocSpec extends WordSpec with MustMatchers {
//#for-vs-flow //#for-vs-flow
val f1, f2 = Future { 1 } val f1, f2 = Future { 1 }
val usingFor = for { v1 f1; v2 f2 } yield v1 + v2 val usingFor = for { v1 <- f1; v2 <- f2 } yield v1 + v2
val usingFlow = flow { f1() + f2() } val usingFlow = flow { f1() + f2() }
usingFor onComplete println usingFor onComplete println

View file

@ -200,22 +200,22 @@ object DispatcherDocSpec {
// Create a new PriorityGenerator, lower prio means more important // Create a new PriorityGenerator, lower prio means more important
PriorityGenerator { PriorityGenerator {
// 'highpriority messages should be treated first if possible // 'highpriority messages should be treated first if possible
case 'highpriority 0 case 'highpriority => 0
// 'lowpriority messages should be treated last if possible // 'lowpriority messages should be treated last if possible
case 'lowpriority 2 case 'lowpriority => 2
// PoisonPill when no other left // PoisonPill when no other left
case PoisonPill 3 case PoisonPill => 3
// We default to 1, which is in between high and low // We default to 1, which is in between high and low
case otherwise 1 case otherwise => 1
}) })
//#prio-mailbox //#prio-mailbox
class MyActor extends Actor { class MyActor extends Actor {
def receive = { def receive = {
case x case x =>
} }
} }
@ -232,7 +232,7 @@ object DispatcherDocSpec {
with RequiresMessageQueue[MyUnboundedMessageQueueSemantics] { with RequiresMessageQueue[MyUnboundedMessageQueueSemantics] {
//#require-mailbox-on-actor //#require-mailbox-on-actor
def receive = { def receive = {
case _ case _ =>
} }
//#require-mailbox-on-actor //#require-mailbox-on-actor
// ... // ...
@ -319,7 +319,7 @@ class DispatcherDocSpec extends AkkaSpec(DispatcherDocSpec.config) {
self ! PoisonPill self ! PoisonPill
def receive = { def receive = {
case x log.info(x.toString) case x => log.info(x.toString)
} }
} }
val a = system.actorOf(Props(classOf[Logger], this).withDispatcher( val a = system.actorOf(Props(classOf[Logger], this).withDispatcher(
@ -338,7 +338,7 @@ class DispatcherDocSpec extends AkkaSpec(DispatcherDocSpec.config) {
//#prio-dispatcher //#prio-dispatcher
watch(a) watch(a)
expectMsgPF() { case Terminated(`a`) () } expectMsgPF() { case Terminated(`a`) => () }
} }
} }

View file

@ -22,8 +22,8 @@ object LoggingDocSpec {
reason.getMessage, message.getOrElse("")) reason.getMessage, message.getOrElse(""))
} }
def receive = { def receive = {
case "test" log.info("Received test") case "test" => log.info("Received test")
case x log.warning("Received unknown message: {}", x) case x => log.warning("Received unknown message: {}", x)
} }
} }
//#my-actor //#my-actor
@ -34,7 +34,7 @@ object LoggingDocSpec {
val log = Logging(this) val log = Logging(this)
def receive = { def receive = {
case _ { case _ => {
//#mdc //#mdc
val mdc = Map("requestId" -> 1234, "visitorId" -> 5678) val mdc = Map("requestId" -> 1234, "visitorId" -> 5678)
log.mdc(mdc) log.mdc(mdc)
@ -60,14 +60,14 @@ object LoggingDocSpec {
reqId += 1 reqId += 1
val always = Map("requestId" -> reqId) val always = Map("requestId" -> reqId)
val perMessage = currentMessage match { val perMessage = currentMessage match {
case r: Req Map("visitorId" -> r.visitorId) case r: Req => Map("visitorId" -> r.visitorId)
case _ Map() case _ => Map()
} }
always ++ perMessage always ++ perMessage
} }
def receive: Receive = { def receive: Receive = {
case r: Req { case r: Req => {
log.info(s"Starting new request: ${r.work}") log.info(s"Starting new request: ${r.work}")
} }
} }
@ -85,11 +85,11 @@ object LoggingDocSpec {
class MyEventListener extends Actor { class MyEventListener extends Actor {
def receive = { def receive = {
case InitializeLogger(_) sender ! LoggerInitialized case InitializeLogger(_) => sender ! LoggerInitialized
case Error(cause, logSource, logClass, message) // ... case Error(cause, logSource, logClass, message) => // ...
case Warning(logSource, logClass, message) // ... case Warning(logSource, logClass, message) => // ...
case Info(logSource, logClass, message) // ... case Info(logSource, logClass, message) => // ...
case Debug(logSource, logClass, message) // ... case Debug(logSource, logClass, message) => // ...
} }
} }
//#my-event-listener //#my-event-listener
@ -140,7 +140,7 @@ class LoggingDocSpec extends AkkaSpec {
class Listener extends Actor { class Listener extends Actor {
def receive = { def receive = {
case d: DeadLetter println(d) case d: DeadLetter => println(d)
} }
} }
val listener = system.actorOf(Props(classOf[Listener], this)) val listener = system.actorOf(Props(classOf[Listener], this))

View file

@ -60,7 +60,7 @@ object ExtensionDocSpec {
class MyActor extends Actor { class MyActor extends Actor {
def receive = { def receive = {
case someMessage case someMessage =>
CountExtension(context.system).increment() CountExtension(context.system).increment()
} }
} }
@ -68,12 +68,12 @@ object ExtensionDocSpec {
//#extension-usage-actor-trait //#extension-usage-actor-trait
trait Counting { self: Actor trait Counting { self: Actor =>
def increment() = CountExtension(context.system).increment() def increment() = CountExtension(context.system).increment()
} }
class MyCounterActor extends Actor with Counting { class MyCounterActor extends Actor with Counting {
def receive = { def receive = {
case someMessage increment() case someMessage => increment()
} }
} }
//#extension-usage-actor-trait //#extension-usage-actor-trait

View file

@ -65,7 +65,7 @@ object SettingsExtensionDocSpec {
//#extension-usage-actor //#extension-usage-actor
def receive = { def receive = {
case someMessage case someMessage =>
} }
def connect(dbUri: String, circuitBreakerTimeout: Duration) = { def connect(dbUri: String, circuitBreakerTimeout: Duration) = {

View file

@ -18,9 +18,9 @@ object FutureDocSpec {
class MyActor extends Actor { class MyActor extends Actor {
def receive = { def receive = {
case x: String sender ! x.toUpperCase case x: String => sender ! x.toUpperCase
case x: Int if x < 0 sender ! Status.Failure(new ArithmeticException("Negative values not supported")) case x: Int if x < 0 => sender ! Status.Failure(new ArithmeticException("Negative values not supported"))
case x: Int sender ! x case x: Int => sender ! x
} }
} }
@ -29,7 +29,7 @@ object FutureDocSpec {
class OddActor extends Actor { class OddActor extends Actor {
var n = 1 var n = 1
def receive = { def receive = {
case GetNext case GetNext =>
sender ! n sender ! n
n += 2 n += 2
} }
@ -40,7 +40,7 @@ class FutureDocSpec extends AkkaSpec {
import FutureDocSpec._ import FutureDocSpec._
import system.dispatcher import system.dispatcher
val println: PartialFunction[Any, Unit] = { case _ } val println: PartialFunction[Any, Unit] = { case _ => }
"demonstrate usage custom ExecutionContext" in { "demonstrate usage custom ExecutionContext" in {
val yourExecutorServiceGoesHere = java.util.concurrent.Executors.newSingleThreadExecutor() val yourExecutorServiceGoesHere = java.util.concurrent.Executors.newSingleThreadExecutor()
@ -112,7 +112,7 @@ class FutureDocSpec extends AkkaSpec {
val f1 = Future { val f1 = Future {
"Hello" + "World" "Hello" + "World"
} }
val f2 = f1 map { x val f2 = f1 map { x =>
x.length x.length
} }
f2 foreach println f2 foreach println
@ -128,8 +128,8 @@ class FutureDocSpec extends AkkaSpec {
"Hello" + "World" "Hello" + "World"
} }
val f2 = Future.successful(3) val f2 = Future.successful(3)
val f3 = f1 map { x val f3 = f1 map { x =>
f2 map { y f2 map { y =>
x.length * y x.length * y
} }
} }
@ -144,8 +144,8 @@ class FutureDocSpec extends AkkaSpec {
"Hello" + "World" "Hello" + "World"
} }
val f2 = Future.successful(3) val f2 = Future.successful(3)
val f3 = f1 flatMap { x val f3 = f1 flatMap { x =>
f2 map { y f2 map { y =>
x.length * y x.length * y
} }
} }
@ -164,7 +164,7 @@ class FutureDocSpec extends AkkaSpec {
val failedFilter = future1.filter(_ % 2 == 1).recover { val failedFilter = future1.filter(_ % 2 == 1).recover {
// When filter fails, it will have a java.util.NoSuchElementException // When filter fails, it will have a java.util.NoSuchElementException
case m: NoSuchElementException 0 case m: NoSuchElementException => 0
} }
failedFilter foreach println failedFilter foreach println
@ -178,9 +178,9 @@ class FutureDocSpec extends AkkaSpec {
"demonstrate usage of for comprehension" in { "demonstrate usage of for comprehension" in {
//#for-comprehension //#for-comprehension
val f = for { val f = for {
a Future(10 / 2) // 10 / 2 = 5 a <- Future(10 / 2) // 10 / 2 = 5
b Future(a + 1) // 5 + 1 = 6 b <- Future(a + 1) // 5 + 1 = 6
c Future(a - 1) // 5 - 1 = 4 c <- Future(a - 1) // 5 - 1 = 4
if c > 3 // Future.filter if c > 3 // Future.filter
} yield b * c // 6 * 4 = 24 } yield b * c // 6 * 4 = 24
@ -232,9 +232,9 @@ class FutureDocSpec extends AkkaSpec {
val f2 = ask(actor2, msg2) val f2 = ask(actor2, msg2)
val f3 = for { val f3 = for {
a f1.mapTo[Int] a <- f1.mapTo[Int]
b f2.mapTo[Int] b <- f2.mapTo[Int]
c ask(actor3, (a + b)).mapTo[Int] c <- ask(actor3, (a + b)).mapTo[Int]
} yield c } yield c
f3 foreach println f3 foreach println
@ -262,7 +262,7 @@ class FutureDocSpec extends AkkaSpec {
"demonstrate usage of sequence" in { "demonstrate usage of sequence" in {
//#sequence //#sequence
val futureList = Future.sequence((1 to 100).toList.map(x Future(x * 2 - 1))) val futureList = Future.sequence((1 to 100).toList.map(x => Future(x * 2 - 1)))
val oddSum = futureList.map(_.sum) val oddSum = futureList.map(_.sum)
oddSum foreach println oddSum foreach println
//#sequence //#sequence
@ -271,7 +271,7 @@ class FutureDocSpec extends AkkaSpec {
"demonstrate usage of traverse" in { "demonstrate usage of traverse" in {
//#traverse //#traverse
val futureList = Future.traverse((1 to 100).toList)(x Future(x * 2 - 1)) val futureList = Future.traverse((1 to 100).toList)(x => Future(x * 2 - 1))
val oddSum = futureList.map(_.sum) val oddSum = futureList.map(_.sum)
oddSum foreach println oddSum foreach println
//#traverse //#traverse
@ -281,7 +281,7 @@ class FutureDocSpec extends AkkaSpec {
"demonstrate usage of fold" in { "demonstrate usage of fold" in {
//#fold //#fold
// Create a sequence of Futures // Create a sequence of Futures
val futures = for (i 1 to 1000) yield Future(i * 2) val futures = for (i <- 1 to 1000) yield Future(i * 2)
val futureSum = Future.fold(futures)(0)(_ + _) val futureSum = Future.fold(futures)(0)(_ + _)
futureSum foreach println futureSum foreach println
//#fold //#fold
@ -291,7 +291,7 @@ class FutureDocSpec extends AkkaSpec {
"demonstrate usage of reduce" in { "demonstrate usage of reduce" in {
//#reduce //#reduce
// Create a sequence of Futures // Create a sequence of Futures
val futures = for (i 1 to 1000) yield Future(i * 2) val futures = for (i <- 1 to 1000) yield Future(i * 2)
val futureSum = Future.reduce(futures)(_ + _) val futureSum = Future.reduce(futures)(_ + _)
futureSum foreach println futureSum foreach println
//#reduce //#reduce
@ -304,7 +304,7 @@ class FutureDocSpec extends AkkaSpec {
val msg1 = -1 val msg1 = -1
//#recover //#recover
val future = akka.pattern.ask(actor, msg1) recover { val future = akka.pattern.ask(actor, msg1) recover {
case e: ArithmeticException 0 case e: ArithmeticException => 0
} }
future foreach println future foreach println
//#recover //#recover
@ -317,8 +317,8 @@ class FutureDocSpec extends AkkaSpec {
val msg1 = -1 val msg1 = -1
//#try-recover //#try-recover
val future = akka.pattern.ask(actor, msg1) recoverWith { val future = akka.pattern.ask(actor, msg1) recoverWith {
case e: ArithmeticException Future.successful(0) case e: ArithmeticException => Future.successful(0)
case foo: IllegalArgumentException case foo: IllegalArgumentException =>
Future.failed[Int](new IllegalStateException("All br0ken!")) Future.failed[Int](new IllegalStateException("All br0ken!"))
} }
future foreach println future foreach println
@ -330,7 +330,7 @@ class FutureDocSpec extends AkkaSpec {
val future1 = Future { "foo" } val future1 = Future { "foo" }
val future2 = Future { "bar" } val future2 = Future { "bar" }
//#zip //#zip
val future3 = future1 zip future2 map { case (a, b) a + " " + b } val future3 = future1 zip future2 map { case (a, b) => a + " " + b }
future3 foreach println future3 foreach println
//#zip //#zip
Await.result(future3, 3 seconds) must be("foo bar") Await.result(future3, 3 seconds) must be("foo bar")
@ -343,9 +343,9 @@ class FutureDocSpec extends AkkaSpec {
def watchSomeTV(): Unit = () def watchSomeTV(): Unit = ()
//#and-then //#and-then
val result = Future { loadPage(url) } andThen { val result = Future { loadPage(url) } andThen {
case Failure(exception) log(exception) case Failure(exception) => log(exception)
} andThen { } andThen {
case _ watchSomeTV() case _ => watchSomeTV()
} }
result foreach println result foreach println
//#and-then //#and-then
@ -368,8 +368,8 @@ class FutureDocSpec extends AkkaSpec {
val future = Future { "foo" } val future = Future { "foo" }
//#onSuccess //#onSuccess
future onSuccess { future onSuccess {
case "bar" println("Got my bar alright!") case "bar" => println("Got my bar alright!")
case x: String println("Got some random string: " + x) case x: String => println("Got some random string: " + x)
} }
//#onSuccess //#onSuccess
Await.result(future, 3 seconds) must be("foo") Await.result(future, 3 seconds) must be("foo")
@ -378,9 +378,9 @@ class FutureDocSpec extends AkkaSpec {
val future = Future.failed[String](new IllegalStateException("OHNOES")) val future = Future.failed[String](new IllegalStateException("OHNOES"))
//#onFailure //#onFailure
future onFailure { future onFailure {
case ise: IllegalStateException if ise.getMessage == "OHNOES" case ise: IllegalStateException if ise.getMessage == "OHNOES" =>
//OHNOES! We are in deep trouble, do something! //OHNOES! We are in deep trouble, do something!
case e: Exception case e: Exception =>
//Do something else //Do something else
} }
//#onFailure //#onFailure
@ -391,8 +391,8 @@ class FutureDocSpec extends AkkaSpec {
def doSomethingOnFailure(t: Throwable) = () def doSomethingOnFailure(t: Throwable) = ()
//#onComplete //#onComplete
future onComplete { future onComplete {
case Success(result) doSomethingOnSuccess(result) case Success(result) => doSomethingOnSuccess(result)
case Failure(failure) doSomethingOnFailure(failure) case Failure(failure) => doSomethingOnFailure(failure)
} }
//#onComplete //#onComplete
Await.result(future, 3 seconds) must be("foo") Await.result(future, 3 seconds) must be("foo")
@ -436,7 +436,7 @@ class FutureDocSpec extends AkkaSpec {
val f = Future("hello") val f = Future("hello")
def receive = { def receive = {
//#receive-omitted //#receive-omitted
case _ case _ =>
//#receive-omitted //#receive-omitted
} }
} }

View file

@ -53,15 +53,15 @@ class EchoManager(handlerClass: Class[_]) extends Actor with ActorLogging {
override def postRestart(thr: Throwable): Unit = context stop self override def postRestart(thr: Throwable): Unit = context stop self
def receive = { def receive = {
case Bound(localAddress) case Bound(localAddress) =>
log.info("listening on port {}", localAddress.getPort) log.info("listening on port {}", localAddress.getPort)
case CommandFailed(Bind(_, local, _, _)) case CommandFailed(Bind(_, local, _, _)) =>
log.warning(s"cannot bind to [$local]") log.warning(s"cannot bind to [$local]")
context stop self context stop self
//#echo-manager //#echo-manager
case Connected(remote, local) case Connected(remote, local) =>
log.info("received connection from {}", remote) log.info("received connection from {}", remote)
val handler = context.actorOf(Props(handlerClass, sender, remote)) val handler = context.actorOf(Props(handlerClass, sender, remote))
sender ! Register(handler, keepOpenOnPeerClosed = true) sender ! Register(handler, keepOpenOnPeerClosed = true)
@ -91,18 +91,18 @@ class EchoHandler(connection: ActorRef, remote: InetSocketAddress)
//#writing //#writing
def writing: Receive = { def writing: Receive = {
case Received(data) case Received(data) =>
connection ! Write(data, Ack(currentOffset)) connection ! Write(data, Ack(currentOffset))
buffer(data) buffer(data)
case Ack(ack) case Ack(ack) =>
acknowledge(ack) acknowledge(ack)
case CommandFailed(Write(_, Ack(ack))) case CommandFailed(Write(_, Ack(ack))) =>
connection ! ResumeWriting connection ! ResumeWriting
context become buffering(ack) context become buffering(ack)
case PeerClosed case PeerClosed =>
if (storage.isEmpty) context stop self if (storage.isEmpty) context stop self
else context become closing else context become closing
} }
@ -114,11 +114,11 @@ class EchoHandler(connection: ActorRef, remote: InetSocketAddress)
var peerClosed = false var peerClosed = false
{ {
case Received(data) buffer(data) case Received(data) => buffer(data)
case WritingResumed writeFirst() case WritingResumed => writeFirst()
case PeerClosed peerClosed = true case PeerClosed => peerClosed = true
case Ack(ack) if ack < nack acknowledge(ack) case Ack(ack) if ack < nack => acknowledge(ack)
case Ack(ack) case Ack(ack) =>
acknowledge(ack) acknowledge(ack)
if (storage.nonEmpty) { if (storage.nonEmpty) {
if (toAck > 0) { if (toAck > 0) {
@ -138,19 +138,19 @@ class EchoHandler(connection: ActorRef, remote: InetSocketAddress)
//#closing //#closing
def closing: Receive = { def closing: Receive = {
case CommandFailed(_: Write) case CommandFailed(_: Write) =>
connection ! ResumeWriting connection ! ResumeWriting
context.become({ context.become({
case WritingResumed case WritingResumed =>
writeAll() writeAll()
context.unbecome() context.unbecome()
case ack: Int acknowledge(ack) case ack: Int => acknowledge(ack)
}, discardOld = false) }, discardOld = false)
case Ack(ack) case Ack(ack) =>
acknowledge(ack) acknowledge(ack)
if (storage.isEmpty) context stop self if (storage.isEmpty) context stop self
} }
@ -213,7 +213,7 @@ class EchoHandler(connection: ActorRef, remote: InetSocketAddress)
} }
private def writeAll(): Unit = { private def writeAll(): Unit = {
for ((data, i) storage.zipWithIndex) { for ((data, i) <- storage.zipWithIndex) {
connection ! Write(data, Ack(storageOffset + i)) connection ! Write(data, Ack(storageOffset + i))
} }
} }
@ -234,17 +234,17 @@ class SimpleEchoHandler(connection: ActorRef, remote: InetSocketAddress)
case object Ack extends Event case object Ack extends Event
def receive = { def receive = {
case Received(data) case Received(data) =>
buffer(data) buffer(data)
connection ! Write(data, Ack) connection ! Write(data, Ack)
context.become({ context.become({
case Received(data) buffer(data) case Received(data) => buffer(data)
case Ack acknowledge() case Ack => acknowledge()
case PeerClosed closing = true case PeerClosed => closing = true
}, discardOld = false) }, discardOld = false)
case PeerClosed context stop self case PeerClosed => context stop self
} }
//#storage-omitted //#storage-omitted

View file

@ -34,14 +34,14 @@ class Server extends Actor {
IO(Tcp) ! Bind(self, new InetSocketAddress("localhost", 0)) IO(Tcp) ! Bind(self, new InetSocketAddress("localhost", 0))
def receive = { def receive = {
case b @ Bound(localAddress) case b @ Bound(localAddress) =>
//#do-some-logging-or-setup //#do-some-logging-or-setup
context.parent ! b context.parent ! b
//#do-some-logging-or-setup //#do-some-logging-or-setup
case CommandFailed(_: Bind) context stop self case CommandFailed(_: Bind) => context stop self
case c @ Connected(remote, local) case c @ Connected(remote, local) =>
//#server //#server
context.parent ! c context.parent ! c
//#server //#server
@ -57,8 +57,8 @@ class Server extends Actor {
class SimplisticHandler extends Actor { class SimplisticHandler extends Actor {
import Tcp._ import Tcp._
def receive = { def receive = {
case Received(data) sender ! Write(data) case Received(data) => sender ! Write(data)
case PeerClosed context stop self case PeerClosed => context stop self
} }
} }
//#simplistic-handler //#simplistic-handler
@ -77,20 +77,20 @@ class Client(remote: InetSocketAddress, listener: ActorRef) extends Actor {
IO(Tcp) ! Connect(remote) IO(Tcp) ! Connect(remote)
def receive = { def receive = {
case CommandFailed(_: Connect) case CommandFailed(_: Connect) =>
listener ! "failed" listener ! "failed"
context stop self context stop self
case c @ Connected(remote, local) case c @ Connected(remote, local) =>
listener ! c listener ! c
val connection = sender val connection = sender
connection ! Register(self) connection ! Register(self)
context become { context become {
case data: ByteString connection ! Write(data) case data: ByteString => connection ! Write(data)
case CommandFailed(w: Write) // O/S buffer was full case CommandFailed(w: Write) => // O/S buffer was full
case Received(data) listener ! data case Received(data) => listener ! data
case "close" connection ! Close case "close" => connection ! Close
case _: ConnectionClosed context stop self case _: ConnectionClosed => context stop self
} }
} }
} }
@ -101,7 +101,7 @@ class IODocSpec extends AkkaSpec {
class Parent extends Actor { class Parent extends Actor {
context.actorOf(Props[Server], "server") context.actorOf(Props[Server], "server")
def receive = { def receive = {
case msg testActor forward msg case msg => testActor forward msg
} }
} }

View file

@ -45,12 +45,12 @@ class PipelinesDocSpec extends AkkaSpec {
builder ++= bs builder ++= bs
} }
override val commandPipeline = { msg: Message override val commandPipeline = { msg: Message =>
val bs = ByteString.newBuilder val bs = ByteString.newBuilder
// first store the persons // first store the persons
bs putInt msg.persons.size bs putInt msg.persons.size
msg.persons foreach { p msg.persons foreach { p =>
putString(bs, p.first) putString(bs, p.first)
putString(bs, p.last) putString(bs, p.last)
} }
@ -72,12 +72,12 @@ class PipelinesDocSpec extends AkkaSpec {
ByteString(bytes).utf8String ByteString(bytes).utf8String
} }
override val eventPipeline = { bs: ByteString override val eventPipeline = { bs: ByteString =>
val iter = bs.iterator val iter = bs.iterator
val personLength = iter.getInt val personLength = iter.getInt
val persons = val persons =
(1 to personLength) map (_ Person(getString(iter), getString(iter))) (1 to personLength) map (_ => Person(getString(iter), getString(iter)))
val curveLength = iter.getInt val curveLength = iter.getInt
val curve = new Array[Double](curveLength) val curve = new Array[Double](curveLength)
@ -94,10 +94,10 @@ class PipelinesDocSpec extends AkkaSpec {
var lastTick = Duration.Zero var lastTick = Duration.Zero
override val managementPort: Mgmt = { override val managementPort: Mgmt = {
case TickGenerator.Tick(timestamp) case TickGenerator.Tick(timestamp) =>
//#omitted //#omitted
testActor ! TickGenerator.Tick(timestamp) testActor ! TickGenerator.Tick(timestamp)
import java.lang.String.{ valueOf println } import java.lang.String.{ valueOf => println }
//#omitted //#omitted
println(s"time since last tick: ${timestamp - lastTick}") println(s"time since last tick: ${timestamp - lastTick}")
lastTick = timestamp lastTick = timestamp
@ -207,20 +207,20 @@ class PipelinesDocSpec extends AkkaSpec {
new LengthFieldFrame(10000) // new LengthFieldFrame(10000) //
)( )(
// failure in the pipeline will fail this actor // failure in the pipeline will fail this actor
cmd cmds ! cmd.get, cmd => cmds ! cmd.get,
evt evts ! evt.get) evt => evts ! evt.get)
def receive = { def receive = {
case m: Message pipeline.injectCommand(m) case m: Message => pipeline.injectCommand(m)
case b: ByteString pipeline.injectEvent(b) case b: ByteString => pipeline.injectEvent(b)
case t: TickGenerator.Trigger pipeline.managementCommand(t) case t: TickGenerator.Trigger => pipeline.managementCommand(t)
} }
} }
//#actor //#actor
class P(cmds: ActorRef, evts: ActorRef) extends Processor(cmds, evts) { class P(cmds: ActorRef, evts: ActorRef) extends Processor(cmds, evts) {
override def receive = ({ override def receive = ({
case "fail!" throw new RuntimeException("FAIL!") case "fail!" => throw new RuntimeException("FAIL!")
}: Receive) orElse super.receive }: Receive) orElse super.receive
} }

View file

@ -21,7 +21,7 @@ object ScalaUdpDocSpec {
IO(Udp) ! Udp.SimpleSender IO(Udp) ! Udp.SimpleSender
def receive = { def receive = {
case Udp.SimpleSenderReady case Udp.SimpleSenderReady =>
context.become(ready(sender)) context.become(ready(sender))
//#sender //#sender
sender ! Udp.Send(ByteString("hello"), remote) sender ! Udp.Send(ByteString("hello"), remote)
@ -29,7 +29,7 @@ object ScalaUdpDocSpec {
} }
def ready(send: ActorRef): Receive = { def ready(send: ActorRef): Receive = {
case msg: String case msg: String =>
send ! Udp.Send(ByteString(msg), remote) send ! Udp.Send(ByteString(msg), remote)
//#sender //#sender
if (msg == "world") send ! PoisonPill if (msg == "world") send ! PoisonPill
@ -44,7 +44,7 @@ object ScalaUdpDocSpec {
IO(Udp) ! Udp.Bind(self, new InetSocketAddress("localhost", 0)) IO(Udp) ! Udp.Bind(self, new InetSocketAddress("localhost", 0))
def receive = { def receive = {
case Udp.Bound(local) case Udp.Bound(local) =>
//#listener //#listener
nextActor forward local nextActor forward local
//#listener //#listener
@ -52,15 +52,15 @@ object ScalaUdpDocSpec {
} }
def ready(socket: ActorRef): Receive = { def ready(socket: ActorRef): Receive = {
case Udp.Received(data, remote) case Udp.Received(data, remote) =>
val processed = // parse data etc., e.g. using PipelineStage val processed = // parse data etc., e.g. using PipelineStage
//#listener //#listener
data.utf8String data.utf8String
//#listener //#listener
socket ! Udp.Send(data, remote) // example server echoes back socket ! Udp.Send(data, remote) // example server echoes back
nextActor ! processed nextActor ! processed
case Udp.Unbind socket ! Udp.Unbind case Udp.Unbind => socket ! Udp.Unbind
case Udp.Unbound context.stop(self) case Udp.Unbound => context.stop(self)
} }
} }
//#listener //#listener
@ -71,7 +71,7 @@ object ScalaUdpDocSpec {
IO(UdpConnected) ! UdpConnected.Connect(self, remote) IO(UdpConnected) ! UdpConnected.Connect(self, remote)
def receive = { def receive = {
case UdpConnected.Connected case UdpConnected.Connected =>
context.become(ready(sender)) context.become(ready(sender))
//#connected //#connected
sender ! UdpConnected.Send(ByteString("hello")) sender ! UdpConnected.Send(ByteString("hello"))
@ -79,16 +79,16 @@ object ScalaUdpDocSpec {
} }
def ready(connection: ActorRef): Receive = { def ready(connection: ActorRef): Receive = {
case UdpConnected.Received(data) case UdpConnected.Received(data) =>
// process data, send it on, etc. // process data, send it on, etc.
//#connected //#connected
if (data.utf8String == "hello") if (data.utf8String == "hello")
connection ! UdpConnected.Send(ByteString("world")) connection ! UdpConnected.Send(ByteString("world"))
//#connected //#connected
case msg: String case msg: String =>
connection ! UdpConnected.Send(ByteString(msg)) connection ! UdpConnected.Send(ByteString(msg))
case d @ UdpConnected.Disconnect connection ! d case d @ UdpConnected.Disconnect => connection ! d
case UdpConnected.Disconnected context.stop(self) case UdpConnected.Disconnected => context.stop(self)
} }
} }
//#connected //#connected

View file

@ -26,11 +26,11 @@ object SchedulerPatternSpec {
override def postStop() = tick.cancel() override def postStop() = tick.cancel()
def receive = { def receive = {
case "tick" case "tick" =>
// do something useful here // do something useful here
//#schedule-constructor //#schedule-constructor
target ! "tick" target ! "tick"
case "restart" case "restart" =>
throw new ArithmeticException throw new ArithmeticException
//#schedule-constructor //#schedule-constructor
} }
@ -53,13 +53,13 @@ object SchedulerPatternSpec {
override def postRestart(reason: Throwable) = {} override def postRestart(reason: Throwable) = {}
def receive = { def receive = {
case "tick" case "tick" =>
// send another periodic tick after the specified delay // send another periodic tick after the specified delay
system.scheduler.scheduleOnce(1000 millis, self, "tick") system.scheduler.scheduleOnce(1000 millis, self, "tick")
// do something useful here // do something useful here
//#schedule-receive //#schedule-receive
target ! "tick" target ! "tick"
case "restart" case "restart" =>
throw new ArithmeticException throw new ArithmeticException
//#schedule-receive //#schedule-receive
} }

View file

@ -21,11 +21,11 @@ trait PersistenceDocSpec {
class MyProcessor extends Processor { class MyProcessor extends Processor {
def receive = { def receive = {
case Persistent(payload, sequenceNr) case Persistent(payload, sequenceNr) =>
// message successfully written to journal // message successfully written to journal
case PersistenceFailure(payload, sequenceNr, cause) case PersistenceFailure(payload, sequenceNr, cause) =>
// message failed to be written to journal // message failed to be written to journal
case other case other =>
// message not written to journal // message not written to journal
} }
} }
@ -67,8 +67,8 @@ trait PersistenceDocSpec {
//#deletion //#deletion
override def preRestart(reason: Throwable, message: Option[Any]) { override def preRestart(reason: Throwable, message: Option[Any]) {
message match { message match {
case Some(p: Persistent) deleteMessage(p.sequenceNr) case Some(p: Persistent) => deleteMessage(p.sequenceNr)
case _ case _ =>
} }
super.preRestart(reason, message) super.preRestart(reason, message)
} }
@ -94,7 +94,7 @@ trait PersistenceDocSpec {
override def processorId = "my-stable-processor-id" override def processorId = "my-stable-processor-id"
//#processor-id-override //#processor-id-override
def receive = { def receive = {
case _ case _ =>
} }
} }
} }
@ -109,14 +109,14 @@ trait PersistenceDocSpec {
val channel = context.actorOf(Channel.props(), name = "myChannel") val channel = context.actorOf(Channel.props(), name = "myChannel")
def receive = { def receive = {
case p @ Persistent(payload, _) case p @ Persistent(payload, _) =>
channel ! Deliver(p.withPayload(s"processed ${payload}"), destination) channel ! Deliver(p.withPayload(s"processed ${payload}"), destination)
} }
} }
class MyDestination extends Actor { class MyDestination extends Actor {
def receive = { def receive = {
case p @ ConfirmablePersistent(payload, sequenceNr, redeliveries) case p @ ConfirmablePersistent(payload, sequenceNr, redeliveries) =>
// ... // ...
p.confirm() p.confirm()
} }
@ -139,7 +139,7 @@ trait PersistenceDocSpec {
//#channel-custom-settings //#channel-custom-settings
def receive = { def receive = {
case p @ Persistent(payload, _) case p @ Persistent(payload, _) =>
//#channel-example-reply //#channel-example-reply
channel ! Deliver(p.withPayload(s"processed ${payload}"), sender) channel ! Deliver(p.withPayload(s"processed ${payload}"), sender)
//#channel-example-reply //#channel-example-reply
@ -155,7 +155,7 @@ trait PersistenceDocSpec {
class MyProcessor3 extends Processor { class MyProcessor3 extends Processor {
def receive = { def receive = {
//#payload-pattern-matching //#payload-pattern-matching
case Persistent(payload, _) case Persistent(payload, _) =>
//#payload-pattern-matching //#payload-pattern-matching
} }
} }
@ -163,7 +163,7 @@ trait PersistenceDocSpec {
class MyProcessor4 extends Processor { class MyProcessor4 extends Processor {
def receive = { def receive = {
//#sequence-nr-pattern-matching //#sequence-nr-pattern-matching
case Persistent(_, sequenceNr) case Persistent(_, sequenceNr) =>
//#sequence-nr-pattern-matching //#sequence-nr-pattern-matching
} }
} }
@ -178,12 +178,12 @@ trait PersistenceDocSpec {
startWith("closed", 0) startWith("closed", 0)
when("closed") { when("closed") {
case Event(Persistent("open", _), counter) case Event(Persistent("open", _), counter) =>
goto("open") using (counter + 1) replying (counter) goto("open") using (counter + 1) replying (counter)
} }
when("open") { when("open") {
case Event(Persistent("close", _), counter) case Event(Persistent("close", _), counter) =>
goto("closed") using (counter + 1) replying (counter) goto("closed") using (counter + 1) replying (counter)
} }
} }
@ -196,9 +196,9 @@ trait PersistenceDocSpec {
var state: Any = _ var state: Any = _
def receive = { def receive = {
case "snap" saveSnapshot(state) case "snap" => saveSnapshot(state)
case SaveSnapshotSuccess(metadata) // ... case SaveSnapshotSuccess(metadata) => // ...
case SaveSnapshotFailure(metadata, reason) // ... case SaveSnapshotFailure(metadata, reason) => // ...
} }
} }
//#save-snapshot //#save-snapshot
@ -210,8 +210,8 @@ trait PersistenceDocSpec {
var state: Any = _ var state: Any = _
def receive = { def receive = {
case SnapshotOffer(metadata, offeredSnapshot) state = offeredSnapshot case SnapshotOffer(metadata, offeredSnapshot) => state = offeredSnapshot
case Persistent(payload, sequenceNr) // ... case Persistent(payload, sequenceNr) => // ...
} }
} }
//#snapshot-offer //#snapshot-offer
@ -232,8 +232,8 @@ trait PersistenceDocSpec {
//#batch-write //#batch-write
class MyProcessor extends Processor { class MyProcessor extends Processor {
def receive = { def receive = {
case Persistent("a", _) // ... case Persistent("a", _) => // ...
case Persistent("b", _) // ... case Persistent("b", _) => // ...
} }
} }
@ -278,11 +278,11 @@ trait PersistenceDocSpec {
} }
def receiveReplay: Receive = { def receiveReplay: Receive = {
case event: String handleEvent(event) case event: String => handleEvent(event)
} }
def receiveCommand: Receive = { def receiveCommand: Receive = {
case "cmd" { case "cmd" => {
// ... // ...
persist("evt")(handleEvent) persist("evt")(handleEvent)
} }

View file

@ -98,7 +98,7 @@ object SharedLeveldbPluginDocSpec {
} }
def receive = { def receive = {
case ActorIdentity(1, Some(store)) case ActorIdentity(1, Some(store)) =>
SharedLeveldbJournal.setStore(store, context.system) SharedLeveldbJournal.setStore(store, context.system)
} }
} }
@ -122,7 +122,7 @@ class MyJournal extends AsyncWriteJournal {
def writeAsync(persistentBatch: Seq[PersistentRepr]): Future[Unit] = ??? def writeAsync(persistentBatch: Seq[PersistentRepr]): Future[Unit] = ???
def deleteAsync(processorId: String, fromSequenceNr: Long, toSequenceNr: Long, permanent: Boolean): Future[Unit] = ??? def deleteAsync(processorId: String, fromSequenceNr: Long, toSequenceNr: Long, permanent: Boolean): Future[Unit] = ???
def confirmAsync(processorId: String, sequenceNr: Long, channelId: String): Future[Unit] = ??? def confirmAsync(processorId: String, sequenceNr: Long, channelId: String): Future[Unit] = ???
def replayAsync(processorId: String, fromSequenceNr: Long, toSequenceNr: Long)(replayCallback: (PersistentRepr) Unit): Future[Long] = ??? def replayAsync(processorId: String, fromSequenceNr: Long, toSequenceNr: Long)(replayCallback: (PersistentRepr) => Unit): Future[Long] = ???
} }
class MySnapshotStore extends SnapshotStore { class MySnapshotStore extends SnapshotStore {

View file

@ -13,7 +13,7 @@ import akka.remote.RemoteScope
object RemoteDeploymentDocSpec { object RemoteDeploymentDocSpec {
class SampleActor extends Actor { class SampleActor extends Actor {
def receive = { case _ sender ! self } def receive = { case _ => sender ! self }
} }
} }

View file

@ -18,9 +18,9 @@ object ConsistentHashingRouterDocSpec {
var cache = Map.empty[String, String] var cache = Map.empty[String, String]
def receive = { def receive = {
case Entry(key, value) cache += (key -> value) case Entry(key, value) => cache += (key -> value)
case Get(key) sender ! cache.get(key) case Get(key) => sender ! cache.get(key)
case Evict(key) cache -= key case Evict(key) => cache -= key
} }
} }
@ -50,7 +50,7 @@ class ConsistentHashingRouterDocSpec extends AkkaSpec with ImplicitSender {
import akka.routing.ConsistentHashingRouter.ConsistentHashableEnvelope import akka.routing.ConsistentHashingRouter.ConsistentHashableEnvelope
def hashMapping: ConsistentHashMapping = { def hashMapping: ConsistentHashMapping = {
case Evict(key) key case Evict(key) => key
} }
val cache: ActorRef = val cache: ActorRef =

View file

@ -50,7 +50,7 @@ akka.actor.deployment {
class RedundancyRoutingLogic(nbrCopies: Int) extends RoutingLogic { class RedundancyRoutingLogic(nbrCopies: Int) extends RoutingLogic {
val roundRobin = RoundRobinRoutingLogic() val roundRobin = RoundRobinRoutingLogic()
def select(message: Any, routees: immutable.IndexedSeq[Routee]): Routee = { def select(message: Any, routees: immutable.IndexedSeq[Routee]): Routee = {
val targets = (1 to nbrCopies).map(_ roundRobin.select(message, routees)) val targets = (1 to nbrCopies).map(_ => roundRobin.select(message, routees))
SeveralRoutees(targets) SeveralRoutees(targets)
} }
} }
@ -58,7 +58,7 @@ akka.actor.deployment {
class Storage extends Actor { class Storage extends Actor {
def receive = { def receive = {
case x sender ! x case x => sender ! x
} }
} }
@ -99,7 +99,7 @@ class CustomRouterDocSpec extends AkkaSpec(CustomRouterDocSpec.config) with Impl
//#unit-test-logic //#unit-test-logic
val logic = new RedundancyRoutingLogic(nbrCopies = 3) val logic = new RedundancyRoutingLogic(nbrCopies = 3)
val routees = for (n 1 to 7) yield TestRoutee(n) val routees = for (n <- 1 to 7) yield TestRoutee(n)
val r1 = logic.select("msg", routees) val r1 = logic.select("msg", routees)
r1.asInstanceOf[SeveralRoutees].routees must be( r1.asInstanceOf[SeveralRoutees].routees must be(
@ -118,16 +118,16 @@ class CustomRouterDocSpec extends AkkaSpec(CustomRouterDocSpec.config) with Impl
"demonstrate usage of custom router" in { "demonstrate usage of custom router" in {
//#usage-1 //#usage-1
for (n 1 to 10) system.actorOf(Props[Storage], "s" + n) for (n <- 1 to 10) system.actorOf(Props[Storage], "s" + n)
val paths = for (n 1 to 10) yield ("/user/s" + n) val paths = for (n <- 1 to 10) yield ("/user/s" + n)
val redundancy1: ActorRef = val redundancy1: ActorRef =
system.actorOf(RedundancyGroup(paths, nbrCopies = 3).props(), system.actorOf(RedundancyGroup(paths, nbrCopies = 3).props(),
name = "redundancy1") name = "redundancy1")
redundancy1 ! "important" redundancy1 ! "important"
//#usage-1 //#usage-1
for (_ 1 to 3) expectMsg("important") for (_ <- 1 to 3) expectMsg("important")
//#usage-2 //#usage-2
val redundancy2: ActorRef = system.actorOf(FromConfig.props(), val redundancy2: ActorRef = system.actorOf(FromConfig.props(),
@ -135,7 +135,7 @@ class CustomRouterDocSpec extends AkkaSpec(CustomRouterDocSpec.config) with Impl
redundancy2 ! "very important" redundancy2 ! "very important"
//#usage-2 //#usage-2
for (_ 1 to 5) expectMsg("very important") for (_ <- 1 to 5) expectMsg("very important")
} }

View file

@ -173,9 +173,9 @@ router-dispatcher {}
} }
def receive = { def receive = {
case w: Work case w: Work =>
router.route(w, sender) router.route(w, sender)
case Terminated(a) case Terminated(a) =>
router = router.removeRoutee(a) router = router.removeRoutee(a)
val r = context.actorOf(Props[Worker]) val r = context.actorOf(Props[Worker])
context watch r context watch r
@ -186,7 +186,7 @@ router-dispatcher {}
class Worker extends Actor { class Worker extends Actor {
def receive = { def receive = {
case _ case _ =>
} }
} }
@ -199,7 +199,7 @@ router-dispatcher {}
//#create-worker-actors //#create-worker-actors
def receive = { def receive = {
case _ case _ =>
} }
} }
@ -335,14 +335,14 @@ router-dispatcher {}
//#resize-pool-2 //#resize-pool-2
def receive = { def receive = {
case _ case _ =>
} }
} }
class Echo extends Actor { class Echo extends Actor {
def receive = { def receive = {
case m sender ! m case m => sender ! m
} }
} }
} }

View file

@ -16,7 +16,7 @@ import akka.testkit.ImplicitSender
object MySpec { object MySpec {
class EchoActor extends Actor { class EchoActor extends Actor {
def receive = { def receive = {
case x sender ! x case x => sender ! x
} }
} }
} }

View file

@ -79,7 +79,7 @@ class TestKitUsageSpec
filterRef ! 1 filterRef ! 1
receiveWhile(500 millis) { receiveWhile(500 millis) {
case msg: String messages = msg +: messages case msg: String => messages = msg +: messages
} }
} }
messages.length should be(3) messages.length should be(3)
@ -90,12 +90,12 @@ class TestKitUsageSpec
"receive an interesting message at some point " in { "receive an interesting message at some point " in {
within(500 millis) { within(500 millis) {
ignoreMsg { ignoreMsg {
case msg: String msg != "something" case msg: String => msg != "something"
} }
seqRef ! "something" seqRef ! "something"
expectMsg("something") expectMsg("something")
ignoreMsg { ignoreMsg {
case msg: String msg == "1" case msg: String => msg == "1"
} }
expectNoMsg expectNoMsg
ignoreNoMsg ignoreNoMsg
@ -117,7 +117,7 @@ object TestKitUsageSpec {
*/ */
class EchoActor extends Actor { class EchoActor extends Actor {
def receive = { def receive = {
case msg sender ! msg case msg => sender ! msg
} }
} }
@ -126,7 +126,7 @@ object TestKitUsageSpec {
*/ */
class ForwardingActor(next: ActorRef) extends Actor { class ForwardingActor(next: ActorRef) extends Actor {
def receive = { def receive = {
case msg next ! msg case msg => next ! msg
} }
} }
@ -135,8 +135,8 @@ object TestKitUsageSpec {
*/ */
class FilteringActor(next: ActorRef) extends Actor { class FilteringActor(next: ActorRef) extends Actor {
def receive = { def receive = {
case msg: String next ! msg case msg: String => next ! msg
case _ None case _ => None
} }
} }
@ -149,7 +149,7 @@ object TestKitUsageSpec {
class SequencingActor(next: ActorRef, head: immutable.Seq[String], class SequencingActor(next: ActorRef, head: immutable.Seq[String],
tail: immutable.Seq[String]) extends Actor { tail: immutable.Seq[String]) extends Actor {
def receive = { def receive = {
case msg { case msg => {
head foreach { next ! _ } head foreach { next ! _ }
next ! msg next ! msg
tail foreach { next ! _ } tail foreach { next ! _ }

View file

@ -22,18 +22,18 @@ object TestkitDocSpec {
class MyActor extends Actor { class MyActor extends Actor {
def receive = { def receive = {
case Say42 sender ! 42 case Say42 => sender ! 42
case "some work" sender ! "some result" case "some work" => sender ! "some result"
} }
} }
class TestFsmActor extends Actor with FSM[Int, String] { class TestFsmActor extends Actor with FSM[Int, String] {
startWith(1, "") startWith(1, "")
when(1) { when(1) {
case Event("go", _) goto(2) using "go" case Event("go", _) => goto(2) using "go"
} }
when(2) { when(2) {
case Event("back", _) goto(1) using "back" case Event("back", _) => goto(1) using "back"
} }
} }
@ -42,10 +42,10 @@ object TestkitDocSpec {
var dest1: ActorRef = _ var dest1: ActorRef = _
var dest2: ActorRef = _ var dest2: ActorRef = _
def receive = { def receive = {
case (d1: ActorRef, d2: ActorRef) case (d1: ActorRef, d2: ActorRef) =>
dest1 = d1 dest1 = d1
dest2 = d2 dest2 = d2
case x case x =>
dest1 ! x dest1 ! x
dest2 ! x dest2 ! x
} }
@ -58,13 +58,13 @@ object TestkitDocSpec {
//#test-probe-forward-actors //#test-probe-forward-actors
class Source(target: ActorRef) extends Actor { class Source(target: ActorRef) extends Actor {
def receive = { def receive = {
case "start" target ! "work" case "start" => target ! "work"
} }
} }
class Destination extends Actor { class Destination extends Actor {
def receive = { def receive = {
case x // Do something.. case x => // Do something..
} }
} }
@ -74,7 +74,7 @@ object TestkitDocSpec {
//#logging-receive //#logging-receive
import akka.event.LoggingReceive import akka.event.LoggingReceive
def receive = LoggingReceive { def receive = LoggingReceive {
case msg // Do something... case msg => // Do something...
} }
//#logging-receive //#logging-receive
} }
@ -151,7 +151,7 @@ class TestkitDocSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
val actorRef = TestActorRef(new Actor { val actorRef = TestActorRef(new Actor {
def receive = { def receive = {
case "hello" throw new IllegalArgumentException("boom") case "hello" => throw new IllegalArgumentException("boom")
} }
}) })
intercept[IllegalArgumentException] { actorRef.receive("hello") } intercept[IllegalArgumentException] { actorRef.receive("hello") }
@ -199,7 +199,7 @@ class TestkitDocSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
val probe = new TestProbe(system) { val probe = new TestProbe(system) {
def expectUpdate(x: Int) = { def expectUpdate(x: Int) = {
expectMsgPF() { expectMsgPF() {
case Update(id, _) if id == x true case Update(id, _) if id == x => true
} }
sender ! "ACK" sender ! "ACK"
} }
@ -280,7 +280,7 @@ class TestkitDocSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
//#put-your-test-code-here //#put-your-test-code-here
val probe = TestProbe() val probe = TestProbe()
probe.send(testActor, "hello") probe.send(testActor, "hello")
try expectMsg("hello") catch { case NonFatal(e) system.shutdown(); throw e } try expectMsg("hello") catch { case NonFatal(e) => system.shutdown(); throw e }
//#put-your-test-code-here //#put-your-test-code-here
shutdown(system) shutdown(system)

View file

@ -26,13 +26,13 @@ object CoordinatedExample {
val count = Ref(0) val count = Ref(0)
def receive = { def receive = {
case coordinated @ Coordinated(Increment(friend)) { case coordinated @ Coordinated(Increment(friend)) => {
friend foreach (_ ! coordinated(Increment())) friend foreach (_ ! coordinated(Increment()))
coordinated atomic { implicit t coordinated atomic { implicit t =>
count transform (_ + 1) count transform (_ + 1)
} }
} }
case GetCount sender ! count.single.get case GetCount => sender ! count.single.get
} }
} }
//#coordinated-example //#coordinated-example
@ -44,9 +44,9 @@ object CoordinatedApi {
class Coordinator extends Actor { class Coordinator extends Actor {
//#receive-coordinated //#receive-coordinated
def receive = { def receive = {
case coordinated @ Coordinated(Message) { case coordinated @ Coordinated(Message) => {
//#coordinated-atomic //#coordinated-atomic
coordinated atomic { implicit t coordinated atomic { implicit t =>
// do something in the coordinated transaction ... // do something in the coordinated transaction ...
} }
//#coordinated-atomic //#coordinated-atomic
@ -66,8 +66,8 @@ object CounterExample {
class Counter extends Transactor { class Counter extends Transactor {
val count = Ref(0) val count = Ref(0)
def atomically = implicit txn { def atomically = implicit txn => {
case Increment count transform (_ + 1) case Increment => count transform (_ + 1)
} }
} }
//#counter-example //#counter-example
@ -85,11 +85,11 @@ object FriendlyCounterExample {
val count = Ref(0) val count = Ref(0)
override def coordinate = { override def coordinate = {
case Increment include(friend) case Increment => include(friend)
} }
def atomically = implicit txn { def atomically = implicit txn => {
case Increment count transform (_ + 1) case Increment => count transform (_ + 1)
} }
} }
//#friendly-counter-example //#friendly-counter-example
@ -97,8 +97,8 @@ object FriendlyCounterExample {
class Friend extends Transactor { class Friend extends Transactor {
val count = Ref(0) val count = Ref(0)
def atomically = implicit txn { def atomically = implicit txn => {
case Increment count transform (_ + 1) case Increment => count transform (_ + 1)
} }
} }
} }
@ -115,22 +115,22 @@ object TransactorCoordinate {
class TestCoordinateInclude(actor1: ActorRef, actor2: ActorRef, actor3: ActorRef) extends Transactor { class TestCoordinateInclude(actor1: ActorRef, actor2: ActorRef, actor3: ActorRef) extends Transactor {
//#coordinate-include //#coordinate-include
override def coordinate = { override def coordinate = {
case Message include(actor1, actor2, actor3) case Message => include(actor1, actor2, actor3)
} }
//#coordinate-include //#coordinate-include
def atomically = txn doNothing def atomically = txn => doNothing
} }
class TestCoordinateSendTo(someActor: ActorRef, actor1: ActorRef, actor2: ActorRef) extends Transactor { class TestCoordinateSendTo(someActor: ActorRef, actor1: ActorRef, actor2: ActorRef) extends Transactor {
//#coordinate-sendto //#coordinate-sendto
override def coordinate = { override def coordinate = {
case SomeMessage sendTo(someActor -> SomeOtherMessage) case SomeMessage => sendTo(someActor -> SomeOtherMessage)
case OtherMessage sendTo(actor1 -> Message1, actor2 -> Message2) case OtherMessage => sendTo(actor1 -> Message1, actor2 -> Message2)
} }
//#coordinate-sendto //#coordinate-sendto
def atomically = txn doNothing def atomically = txn => doNothing
} }
} }

View file

@ -45,7 +45,7 @@ object ZeromqDocSpec {
} }
def receive: Receive = { def receive: Receive = {
case Tick case Tick =>
val currentHeap = memory.getHeapMemoryUsage val currentHeap = memory.getHeapMemoryUsage
val timestamp = System.currentTimeMillis val timestamp = System.currentTimeMillis
@ -73,13 +73,13 @@ object ZeromqDocSpec {
def receive = { def receive = {
// the first frame is the topic, second is the message // the first frame is the topic, second is the message
case m: ZMQMessage if m.frames(0).utf8String == "health.heap" case m: ZMQMessage if m.frames(0).utf8String == "health.heap" =>
val Heap(timestamp, used, max) = ser.deserialize(m.frames(1).toArray, val Heap(timestamp, used, max) = ser.deserialize(m.frames(1).toArray,
classOf[Heap]).get classOf[Heap]).get
log.info("Used heap {} bytes, at {}", used, log.info("Used heap {} bytes, at {}", used,
timestampFormat.format(new Date(timestamp))) timestampFormat.format(new Date(timestamp)))
case m: ZMQMessage if m.frames(0).utf8String == "health.load" case m: ZMQMessage if m.frames(0).utf8String == "health.load" =>
val Load(timestamp, loadAverage) = ser.deserialize(m.frames(1).toArray, val Load(timestamp, loadAverage) = ser.deserialize(m.frames(1).toArray,
classOf[Load]).get classOf[Load]).get
log.info("Load average {}, at {}", loadAverage, log.info("Load average {}, at {}", loadAverage,
@ -98,7 +98,7 @@ object ZeromqDocSpec {
def receive = { def receive = {
// the first frame is the topic, second is the message // the first frame is the topic, second is the message
case m: ZMQMessage if m.frames(0).utf8String == "health.heap" case m: ZMQMessage if m.frames(0).utf8String == "health.heap" =>
val Heap(timestamp, used, max) = val Heap(timestamp, used, max) =
ser.deserialize(m.frames(1).toArray, classOf[Heap]).get ser.deserialize(m.frames(1).toArray, classOf[Heap]).get
if ((used.toDouble / max) > 0.9) count += 1 if ((used.toDouble / max) > 0.9) count += 1
@ -130,9 +130,9 @@ class ZeromqDocSpec extends AkkaSpec("akka.loglevel=INFO") {
class Listener extends Actor { class Listener extends Actor {
def receive: Receive = { def receive: Receive = {
case Connecting //... case Connecting => //...
case m: ZMQMessage //... case m: ZMQMessage => //...
case _ //... case _ => //...
} }
} }
@ -195,11 +195,11 @@ class ZeromqDocSpec extends AkkaSpec("akka.loglevel=INFO") {
def checkZeroMQInstallation() = try { def checkZeroMQInstallation() = try {
ZeroMQExtension(system).version match { ZeroMQExtension(system).version match {
case ZeroMQVersion(2, x, _) if x >= 1 Unit case ZeroMQVersion(2, x, _) if x >= 1 => Unit
case ZeroMQVersion(y, _, _) if y >= 3 Unit case ZeroMQVersion(y, _, _) if y >= 3 => Unit
case version pending case version => pending
} }
} catch { } catch {
case e: LinkageError pending case e: LinkageError => pending
} }
} }

View file

@ -80,7 +80,7 @@ abstract class StatsSampleSingleMasterSpec extends MultiNodeSpec(StatsSampleSing
Cluster(system) join firstAddress Cluster(system) join firstAddress
receiveN(3).collect { case MemberUp(m) m.address }.toSet must be( receiveN(3).collect { case MemberUp(m) => m.address }.toSet must be(
Set(firstAddress, secondAddress, thirdAddress)) Set(firstAddress, secondAddress, thirdAddress))
Cluster(system).unsubscribe(testActor) Cluster(system).unsubscribe(testActor)

View file

@ -83,7 +83,7 @@ abstract class StatsSampleSpec extends MultiNodeSpec(StatsSampleSpecConfig)
system.actorOf(Props[StatsWorker], "statsWorker") system.actorOf(Props[StatsWorker], "statsWorker")
system.actorOf(Props[StatsService], "statsService") system.actorOf(Props[StatsService], "statsService")
receiveN(3).collect { case MemberUp(m) m.address }.toSet must be( receiveN(3).collect { case MemberUp(m) => m.address }.toSet must be(
Set(firstAddress, secondAddress, thirdAddress)) Set(firstAddress, secondAddress, thirdAddress))
Cluster(system).unsubscribe(testActor) Cluster(system).unsubscribe(testActor)

View file

@ -68,7 +68,7 @@ abstract class TransformationSampleSpec extends MultiNodeSpec(TransformationSamp
transformationFrontend ! new TransformationJob("hello") transformationFrontend ! new TransformationJob("hello")
expectMsgPF() { expectMsgPF() {
// no backends yet, service unavailble // no backends yet, service unavailble
case f: JobFailed case f: JobFailed =>
} }
} }

View file

@ -56,21 +56,21 @@ abstract class GenericBuncher[A: ClassTag, B](val singleTimeout: FiniteDuration,
startWith(Idle, empty) startWith(Idle, empty)
when(Idle) { when(Idle) {
case Event(Msg(m), acc) case Event(Msg(m), acc) =>
setTimer("multi", StateTimeout, multiTimeout, false) setTimer("multi", StateTimeout, multiTimeout, false)
goto(Active) using merge(acc, m) goto(Active) using merge(acc, m)
case Event(Flush, _) stay case Event(Flush, _) => stay
case Event(Stop, _) stop case Event(Stop, _) => stop
} }
when(Active, stateTimeout = singleTimeout) { when(Active, stateTimeout = singleTimeout) {
case Event(Msg(m), acc) case Event(Msg(m), acc) =>
stay using merge(acc, m) stay using merge(acc, m)
case Event(StateTimeout, acc) case Event(StateTimeout, acc) =>
flush(acc) flush(acc)
case Event(Flush, acc) case Event(Flush, acc) =>
flush(acc) flush(acc)
case Event(Stop, acc) case Event(Stop, acc) =>
send(acc) send(acc)
cancelTimer("multi") cancelTimer("multi")
stop stop
@ -99,7 +99,7 @@ class Buncher[A: ClassTag](singleTimeout: FiniteDuration, multiTimeout: FiniteDu
protected def merge(l: List[A], elem: A) = elem :: l protected def merge(l: List[A], elem: A) = elem :: l
whenUnhandled { whenUnhandled {
case Event(Target(t), _) case Event(Target(t), _) =>
target = Some(t) target = Some(t)
stay stay
} }

View file

@ -33,15 +33,15 @@ class Chopstick extends Actor {
//It will refuse to be taken by other hakkers //It will refuse to be taken by other hakkers
//But the owning hakker can put it back //But the owning hakker can put it back
def takenBy(hakker: ActorRef): Receive = { def takenBy(hakker: ActorRef): Receive = {
case Take(otherHakker) case Take(otherHakker) =>
otherHakker ! Busy(self) otherHakker ! Busy(self)
case Put(`hakker`) case Put(`hakker`) =>
become(available) become(available)
} }
//When a Chopstick is available, it can be taken by a hakker //When a Chopstick is available, it can be taken by a hakker
def available: Receive = { def available: Receive = {
case Take(hakker) case Take(hakker) =>
become(takenBy(hakker)) become(takenBy(hakker))
hakker ! Taken(self) hakker ! Taken(self)
} }
@ -60,7 +60,7 @@ class Hakker(name: String, left: ActorRef, right: ActorRef) extends Actor {
//When a hakker is thinking it can become hungry //When a hakker is thinking it can become hungry
//and try to pick up its chopsticks and eat //and try to pick up its chopsticks and eat
def thinking: Receive = { def thinking: Receive = {
case Eat case Eat =>
become(hungry) become(hungry)
left ! Take(self) left ! Take(self)
right ! Take(self) right ! Take(self)
@ -71,11 +71,11 @@ class Hakker(name: String, left: ActorRef, right: ActorRef) extends Actor {
//If the hakkers first attempt at grabbing a chopstick fails, //If the hakkers first attempt at grabbing a chopstick fails,
//it starts to wait for the response of the other grab //it starts to wait for the response of the other grab
def hungry: Receive = { def hungry: Receive = {
case Taken(`left`) case Taken(`left`) =>
become(waiting_for(right, left)) become(waiting_for(right, left))
case Taken(`right`) case Taken(`right`) =>
become(waiting_for(left, right)) become(waiting_for(left, right))
case Busy(chopstick) case Busy(chopstick) =>
become(denied_a_chopstick) become(denied_a_chopstick)
} }
@ -83,12 +83,12 @@ class Hakker(name: String, left: ActorRef, right: ActorRef) extends Actor {
//and start eating, or the other chopstick was busy, and the hakker goes //and start eating, or the other chopstick was busy, and the hakker goes
//back to think about how he should obtain his chopsticks :-) //back to think about how he should obtain his chopsticks :-)
def waiting_for(chopstickToWaitFor: ActorRef, otherChopstick: ActorRef): Receive = { def waiting_for(chopstickToWaitFor: ActorRef, otherChopstick: ActorRef): Receive = {
case Taken(`chopstickToWaitFor`) case Taken(`chopstickToWaitFor`) =>
println("%s has picked up %s and %s and starts to eat".format(name, left.path.name, right.path.name)) println("%s has picked up %s and %s and starts to eat".format(name, left.path.name, right.path.name))
become(eating) become(eating)
system.scheduler.scheduleOnce(5 seconds, self, Think) system.scheduler.scheduleOnce(5 seconds, self, Think)
case Busy(chopstick) case Busy(chopstick) =>
become(thinking) become(thinking)
otherChopstick ! Put(self) otherChopstick ! Put(self)
self ! Eat self ! Eat
@ -98,11 +98,11 @@ class Hakker(name: String, left: ActorRef, right: ActorRef) extends Actor {
//he needs to put it back if he got the other one. //he needs to put it back if he got the other one.
//Then go back and think and try to grab the chopsticks again //Then go back and think and try to grab the chopsticks again
def denied_a_chopstick: Receive = { def denied_a_chopstick: Receive = {
case Taken(chopstick) case Taken(chopstick) =>
become(thinking) become(thinking)
chopstick ! Put(self) chopstick ! Put(self)
self ! Eat self ! Eat
case Busy(chopstick) case Busy(chopstick) =>
become(thinking) become(thinking)
self ! Eat self ! Eat
} }
@ -110,7 +110,7 @@ class Hakker(name: String, left: ActorRef, right: ActorRef) extends Actor {
//When a hakker is eating, he can decide to start to think, //When a hakker is eating, he can decide to start to think,
//then he puts down his chopsticks and starts to think //then he puts down his chopsticks and starts to think
def eating: Receive = { def eating: Receive = {
case Think case Think =>
become(thinking) become(thinking)
left ! Put(self) left ! Put(self)
right ! Put(self) right ! Put(self)
@ -120,7 +120,7 @@ class Hakker(name: String, left: ActorRef, right: ActorRef) extends Actor {
//All hakkers start in a non-eating state //All hakkers start in a non-eating state
def receive = { def receive = {
case Think case Think =>
println("%s starts to think".format(name)) println("%s starts to think".format(name))
become(thinking) become(thinking)
system.scheduler.scheduleOnce(5 seconds, self, Eat) system.scheduler.scheduleOnce(5 seconds, self, Eat)
@ -137,11 +137,11 @@ object DiningHakkers {
def run(): Unit = { def run(): Unit = {
//Create 5 chopsticks //Create 5 chopsticks
val chopsticks = for (i 1 to 5) yield system.actorOf(Props[Chopstick], "Chopstick" + i) val chopsticks = for (i <- 1 to 5) yield system.actorOf(Props[Chopstick], "Chopstick" + i)
//Create 5 awesome hakkers and assign them their left and right chopstick //Create 5 awesome hakkers and assign them their left and right chopstick
val hakkers = for { val hakkers = for {
(name, i) List("Ghosh", "Boner", "Klang", "Krasser", "Manie").zipWithIndex (name, i) <- List("Ghosh", "Boner", "Klang", "Krasser", "Manie").zipWithIndex
} yield system.actorOf(Props(classOf[Hakker], name, chopsticks(i), chopsticks((i + 1) % 5))) } yield system.actorOf(Props(classOf[Hakker], name, chopsticks(i), chopsticks((i + 1) % 5)))
//Signal all hakkers that they should start thinking, and watch the show //Signal all hakkers that they should start thinking, and watch the show

View file

@ -40,7 +40,7 @@ class Chopstick extends Actor with FSM[ChopstickState, TakenBy] {
// When a chopstick is available, it can be taken by a some hakker // When a chopstick is available, it can be taken by a some hakker
when(Available) { when(Available) {
case Event(Take, _) case Event(Take, _) =>
goto(Taken) using TakenBy(sender) replying Taken(self) goto(Taken) using TakenBy(sender) replying Taken(self)
} }
@ -48,9 +48,9 @@ class Chopstick extends Actor with FSM[ChopstickState, TakenBy] {
// It will refuse to be taken by other hakkers // It will refuse to be taken by other hakkers
// But the owning hakker can put it back // But the owning hakker can put it back
when(Taken) { when(Taken) {
case Event(Take, currentState) case Event(Take, currentState) =>
stay replying Busy(self) stay replying Busy(self)
case Event(Put, TakenBy(hakker)) if sender == hakker case Event(Put, TakenBy(hakker)) if sender == hakker =>
goto(Available) using TakenBy(system.deadLetters) goto(Available) using TakenBy(system.deadLetters)
} }
@ -89,7 +89,7 @@ class FSMHakker(name: String, left: ActorRef, right: ActorRef) extends Actor wit
startWith(Waiting, TakenChopsticks(None, None)) startWith(Waiting, TakenChopsticks(None, None))
when(Waiting) { when(Waiting) {
case Event(Think, _) case Event(Think, _) =>
println("%s starts to think".format(name)) println("%s starts to think".format(name))
startThinking(5 seconds) startThinking(5 seconds)
} }
@ -97,7 +97,7 @@ class FSMHakker(name: String, left: ActorRef, right: ActorRef) extends Actor wit
//When a hakker is thinking it can become hungry //When a hakker is thinking it can become hungry
//and try to pick up its chopsticks and eat //and try to pick up its chopsticks and eat
when(Thinking) { when(Thinking) {
case Event(StateTimeout, _) case Event(StateTimeout, _) =>
left ! Take left ! Take
right ! Take right ! Take
goto(Hungry) goto(Hungry)
@ -108,11 +108,11 @@ class FSMHakker(name: String, left: ActorRef, right: ActorRef) extends Actor wit
// If the hakkers first attempt at grabbing a chopstick fails, // If the hakkers first attempt at grabbing a chopstick fails,
// it starts to wait for the response of the other grab // it starts to wait for the response of the other grab
when(Hungry) { when(Hungry) {
case Event(Taken(`left`), _) case Event(Taken(`left`), _) =>
goto(WaitForOtherChopstick) using TakenChopsticks(Some(left), None) goto(WaitForOtherChopstick) using TakenChopsticks(Some(left), None)
case Event(Taken(`right`), _) case Event(Taken(`right`), _) =>
goto(WaitForOtherChopstick) using TakenChopsticks(None, Some(right)) goto(WaitForOtherChopstick) using TakenChopsticks(None, Some(right))
case Event(Busy(_), _) case Event(Busy(_), _) =>
goto(FirstChopstickDenied) goto(FirstChopstickDenied)
} }
@ -120,9 +120,9 @@ class FSMHakker(name: String, left: ActorRef, right: ActorRef) extends Actor wit
// and start eating, or the other chopstick was busy, and the hakker goes // and start eating, or the other chopstick was busy, and the hakker goes
// back to think about how he should obtain his chopsticks :-) // back to think about how he should obtain his chopsticks :-)
when(WaitForOtherChopstick) { when(WaitForOtherChopstick) {
case Event(Taken(`left`), TakenChopsticks(None, Some(right))) startEating(left, right) case Event(Taken(`left`), TakenChopsticks(None, Some(right))) => startEating(left, right)
case Event(Taken(`right`), TakenChopsticks(Some(left), None)) startEating(left, right) case Event(Taken(`right`), TakenChopsticks(Some(left), None)) => startEating(left, right)
case Event(Busy(chopstick), TakenChopsticks(leftOption, rightOption)) case Event(Busy(chopstick), TakenChopsticks(leftOption, rightOption)) =>
leftOption.foreach(_ ! Put) leftOption.foreach(_ ! Put)
rightOption.foreach(_ ! Put) rightOption.foreach(_ ! Put)
startThinking(10 milliseconds) startThinking(10 milliseconds)
@ -137,17 +137,17 @@ class FSMHakker(name: String, left: ActorRef, right: ActorRef) extends Actor wit
// he needs to put it back if he got the other one. // he needs to put it back if he got the other one.
// Then go back and think and try to grab the chopsticks again // Then go back and think and try to grab the chopsticks again
when(FirstChopstickDenied) { when(FirstChopstickDenied) {
case Event(Taken(secondChopstick), _) case Event(Taken(secondChopstick), _) =>
secondChopstick ! Put secondChopstick ! Put
startThinking(10 milliseconds) startThinking(10 milliseconds)
case Event(Busy(chopstick), _) case Event(Busy(chopstick), _) =>
startThinking(10 milliseconds) startThinking(10 milliseconds)
} }
// When a hakker is eating, he can decide to start to think, // When a hakker is eating, he can decide to start to think,
// then he puts down his chopsticks and starts to think // then he puts down his chopsticks and starts to think
when(Eating) { when(Eating) {
case Event(StateTimeout, _) case Event(StateTimeout, _) =>
println("%s puts down his chopsticks and starts to think".format(name)) println("%s puts down his chopsticks and starts to think".format(name))
left ! Put left ! Put
right ! Put right ! Put
@ -173,10 +173,10 @@ object DiningHakkersOnFsm {
def run(): Unit = { def run(): Unit = {
// Create 5 chopsticks // Create 5 chopsticks
val chopsticks = for (i 1 to 5) yield system.actorOf(Props[Chopstick], "Chopstick" + i) val chopsticks = for (i <- 1 to 5) yield system.actorOf(Props[Chopstick], "Chopstick" + i)
// Create 5 awesome fsm hakkers and assign them their left and right chopstick // Create 5 awesome fsm hakkers and assign them their left and right chopstick
val hakkers = for { val hakkers = for {
(name, i) List("Ghosh", "Boner", "Klang", "Krasser", "Manie").zipWithIndex (name, i) <- List("Ghosh", "Boner", "Klang", "Krasser", "Manie").zipWithIndex
} yield system.actorOf(Props(classOf[FSMHakker], name, chopsticks(i), chopsticks((i + 1) % 5))) } yield system.actorOf(Props(classOf[FSMHakker], name, chopsticks(i), chopsticks((i + 1) % 5)))
hakkers.foreach(_ ! Think) hakkers.foreach(_ ! Think)

View file

@ -12,15 +12,15 @@ class HelloActor extends Actor {
val worldActor = context.actorOf(Props[WorldActor]) val worldActor = context.actorOf(Props[WorldActor])
def receive = { def receive = {
case Start worldActor ! "Hello" case Start => worldActor ! "Hello"
case message: String case message: String =>
println("Received message '%s'" format message) println("Received message '%s'" format message)
} }
} }
class WorldActor extends Actor { class WorldActor extends Actor {
def receive = { def receive = {
case message: String sender ! (message.toUpperCase + " world!") case message: String => sender ! (message.toUpperCase + " world!")
} }
} }

View file

@ -12,7 +12,7 @@ object Greeter {
class Greeter extends Actor { class Greeter extends Actor {
def receive = { def receive = {
case Greeter.Greet case Greeter.Greet =>
println("Hello World!") println("Hello World!")
sender ! Greeter.Done sender ! Greeter.Done
} }

View file

@ -17,7 +17,7 @@ class HelloWorld extends Actor {
def receive = { def receive = {
// when the greeter is done, stop this actor and with it the application // when the greeter is done, stop this actor and with it the application
case Greeter.Done context.stop(self) case Greeter.Done => context.stop(self)
} }
} }

View file

@ -21,7 +21,7 @@ object Main2 {
class Terminator(ref: ActorRef) extends Actor with ActorLogging { class Terminator(ref: ActorRef) extends Actor with ActorLogging {
context watch ref context watch ref
def receive = { def receive = {
case Terminated(_) case Terminated(_) =>
log.info("{} has terminated, shutting down system", ref.path) log.info("{} has terminated, shutting down system", ref.path)
context.system.shutdown() context.system.shutdown()
} }

View file

@ -46,7 +46,7 @@ class MultiNodeSample extends MultiNodeSpec(MultiNodeSampleConfig)
runOn(node2) { runOn(node2) {
system.actorOf(Props(new Actor { system.actorOf(Props(new Actor {
def receive = { def receive = {
case "ping" sender ! "pong" case "ping" => sender ! "pong"
} }
}), "ponger") }), "ponger")
enterBarrier("deployed") enterBarrier("deployed")

View file

@ -27,15 +27,15 @@ class Chopstick extends Actor {
//It will refuse to be taken by other hakkers //It will refuse to be taken by other hakkers
//But the owning hakker can put it back //But the owning hakker can put it back
def takenBy(hakker: ActorRef): Receive = { def takenBy(hakker: ActorRef): Receive = {
case Take(otherHakker) case Take(otherHakker) =>
otherHakker ! Busy(self) otherHakker ! Busy(self)
case Put(`hakker`) case Put(`hakker`) =>
become(available) become(available)
} }
//When a Chopstick is available, it can be taken by a hakker //When a Chopstick is available, it can be taken by a hakker
def available: Receive = { def available: Receive = {
case Take(hakker) case Take(hakker) =>
log.info(self.path + " is taken by " + hakker) log.info(self.path + " is taken by " + hakker)
become(takenBy(hakker)) become(takenBy(hakker))
hakker ! Taken(self) hakker ! Taken(self)
@ -71,11 +71,11 @@ class Hakker(name: String, chair: Int) extends Actor {
//When a hakker is thinking it can become hungry //When a hakker is thinking it can become hungry
//and try to pick up its chopsticks and eat //and try to pick up its chopsticks and eat
def thinking(left: ActorRef, right: ActorRef): Receive = { def thinking(left: ActorRef, right: ActorRef): Receive = {
case Eat case Eat =>
become(hungry(left, right) orElse (clusterEvents)) become(hungry(left, right) orElse (clusterEvents))
left ! Take(self) left ! Take(self)
right ! Take(self) right ! Take(self)
case Identify identify("Thinking") case Identify => identify("Thinking")
} }
//When a hakker is hungry it tries to pick up its chopsticks and eat //When a hakker is hungry it tries to pick up its chopsticks and eat
@ -83,28 +83,28 @@ class Hakker(name: String, chair: Int) extends Actor {
//If the hakkers first attempt at grabbing a chopstick fails, //If the hakkers first attempt at grabbing a chopstick fails,
//it starts to wait for the response of the other grab //it starts to wait for the response of the other grab
def hungry(left: ActorRef, right: ActorRef): Receive = { def hungry(left: ActorRef, right: ActorRef): Receive = {
case Taken(`left`) case Taken(`left`) =>
become(waiting_for(left, right, false) orElse (clusterEvents)) become(waiting_for(left, right, false) orElse (clusterEvents))
case Taken(`right`) case Taken(`right`) =>
become(waiting_for(left, right, true) orElse (clusterEvents)) become(waiting_for(left, right, true) orElse (clusterEvents))
case Busy(chopstick) case Busy(chopstick) =>
become(denied_a_chopstick(left, right) orElse (clusterEvents)) become(denied_a_chopstick(left, right) orElse (clusterEvents))
case Identify identify("Hungry") case Identify => identify("Hungry")
} }
//When a hakker is waiting for the last chopstick it can either obtain it //When a hakker is waiting for the last chopstick it can either obtain it
//and start eating, or the other chopstick was busy, and the hakker goes //and start eating, or the other chopstick was busy, and the hakker goes
//back to think about how he should obtain his chopsticks :-) //back to think about how he should obtain his chopsticks :-)
def waiting_for(left: ActorRef, right: ActorRef, waitingForLeft: Boolean): Receive = { def waiting_for(left: ActorRef, right: ActorRef, waitingForLeft: Boolean): Receive = {
case Taken(`left`) if waitingForLeft case Taken(`left`) if waitingForLeft =>
log.info("%s has picked up %s and %s and starts to eat".format(name, left.path.name, right.path.name)) log.info("%s has picked up %s and %s and starts to eat".format(name, left.path.name, right.path.name))
become(eating(left, right) orElse (clusterEvents)) become(eating(left, right) orElse (clusterEvents))
system.scheduler.scheduleOnce(5 seconds, self, Think) system.scheduler.scheduleOnce(5 seconds, self, Think)
case Taken(`right`) if !waitingForLeft case Taken(`right`) if !waitingForLeft =>
log.info("%s has picked up %s and %s and starts to eat".format(name, left.path.name, right.path.name)) log.info("%s has picked up %s and %s and starts to eat".format(name, left.path.name, right.path.name))
become(eating(left, right) orElse (clusterEvents)) become(eating(left, right) orElse (clusterEvents))
system.scheduler.scheduleOnce(5 seconds, self, Think) system.scheduler.scheduleOnce(5 seconds, self, Think)
case Busy(chopstick) case Busy(chopstick) =>
become(thinking(left, right) orElse (clusterEvents)) become(thinking(left, right) orElse (clusterEvents))
if (waitingForLeft) { if (waitingForLeft) {
right ! Put(self) right ! Put(self)
@ -112,44 +112,44 @@ class Hakker(name: String, chair: Int) extends Actor {
left ! Put(self) left ! Put(self)
} }
self ! Eat self ! Eat
case Identify identify("Waiting for Chopstick") case Identify => identify("Waiting for Chopstick")
} }
//When the results of the other grab comes back, //When the results of the other grab comes back,
//he needs to put it back if he got the other one. //he needs to put it back if he got the other one.
//Then go back and think and try to grab the chopsticks again //Then go back and think and try to grab the chopsticks again
def denied_a_chopstick(left: ActorRef, right: ActorRef): Receive = { def denied_a_chopstick(left: ActorRef, right: ActorRef): Receive = {
case Taken(chopstick) case Taken(chopstick) =>
become(thinking(left, right) orElse (clusterEvents)) become(thinking(left, right) orElse (clusterEvents))
chopstick ! Put(self) chopstick ! Put(self)
self ! Eat self ! Eat
case Busy(chopstick) case Busy(chopstick) =>
become(thinking(left, right) orElse (clusterEvents)) become(thinking(left, right) orElse (clusterEvents))
self ! Eat self ! Eat
case Identify identify("Denied a Chopstick") case Identify => identify("Denied a Chopstick")
} }
//When a hakker is eating, he can decide to start to think, //When a hakker is eating, he can decide to start to think,
//then he puts down his chopsticks and starts to think //then he puts down his chopsticks and starts to think
def eating(left: ActorRef, right: ActorRef): Receive = { def eating(left: ActorRef, right: ActorRef): Receive = {
case Think case Think =>
become(thinking(left, right) orElse (clusterEvents)) become(thinking(left, right) orElse (clusterEvents))
left ! Put(self) left ! Put(self)
right ! Put(self) right ! Put(self)
log.info("%s puts down his chopsticks and starts to think".format(name)) log.info("%s puts down his chopsticks and starts to think".format(name))
system.scheduler.scheduleOnce(5 seconds, self, Eat) system.scheduler.scheduleOnce(5 seconds, self, Eat)
case Identify identify("Eating") case Identify => identify("Eating")
} }
def waitForChopsticks: Receive = { def waitForChopsticks: Receive = {
case (left: ActorRef, right: ActorRef) case (left: ActorRef, right: ActorRef) =>
become(thinking(left, right) orElse (clusterEvents)) become(thinking(left, right) orElse (clusterEvents))
system.scheduler.scheduleOnce(5 seconds, self, Eat) system.scheduler.scheduleOnce(5 seconds, self, Eat)
} }
def clusterEvents: Receive = { def clusterEvents: Receive = {
case state: CurrentClusterState state.leader foreach updateTable case state: CurrentClusterState => state.leader foreach updateTable
case LeaderChanged(Some(leaderAddress)) updateTable(leaderAddress) case LeaderChanged(Some(leaderAddress)) => updateTable(leaderAddress)
} }
def identify(busyWith: String) { def identify(busyWith: String) {

View file

@ -18,9 +18,9 @@ package akka.sample.osgi.internal
import akka.actor.{ Props, Actor } import akka.actor.{ Props, Actor }
class Table extends Actor { class Table extends Actor {
val chopsticks = for (i 1 to 5) yield context.actorOf(Props[Chopstick], "Chopstick" + i) val chopsticks = for (i <- 1 to 5) yield context.actorOf(Props[Chopstick], "Chopstick" + i)
def receive = { def receive = {
case x: Int sender ! ((chopsticks(x), chopsticks((x + 1) % 5))) case x: Int => sender ! ((chopsticks(x), chopsticks((x + 1) % 5)))
} }
} }

View file

@ -100,7 +100,7 @@ java.io.EOFException
object HakkerStatusTest { object HakkerStatusTest {
class Interrogator(queue: SynchronousQueue[(String, String)]) extends Actor { class Interrogator(queue: SynchronousQueue[(String, String)]) extends Actor {
def receive = { def receive = {
case msg: Identification { case msg: Identification => {
queue.put((msg.name, msg.busyWith)) queue.put((msg.name, msg.busyWith))
} }
} }

View file

@ -16,13 +16,13 @@ object ConversationRecoveryExample extends App {
var counter = 0 var counter = 0
def receive = { def receive = {
case m @ ConfirmablePersistent(Ping, _, _) case m @ ConfirmablePersistent(Ping, _, _) =>
counter += 1 counter += 1
println(s"received ping ${counter} times ...") println(s"received ping ${counter} times ...")
m.confirm() m.confirm()
if (!recoveryRunning) Thread.sleep(1000) if (!recoveryRunning) Thread.sleep(1000)
pongChannel ! Deliver(m.withPayload(Pong), sender, Resolve.Destination) pongChannel ! Deliver(m.withPayload(Pong), sender, Resolve.Destination)
case "init" if (counter == 0) pongChannel ! Deliver(Persistent(Pong), sender) case "init" => if (counter == 0) pongChannel ! Deliver(Persistent(Pong), sender)
} }
override def preStart() = () override def preStart() = ()
@ -33,7 +33,7 @@ object ConversationRecoveryExample extends App {
var counter = 0 var counter = 0
def receive = { def receive = {
case m @ ConfirmablePersistent(Pong, _, _) case m @ ConfirmablePersistent(Pong, _, _) =>
counter += 1 counter += 1
println(s"received pong ${counter} times ...") println(s"received pong ${counter} times ...")
m.confirm() m.confirm()

View file

@ -27,30 +27,30 @@ class ExampleProcessor extends EventsourcedProcessor {
state.size state.size
val receiveReplay: Receive = { val receiveReplay: Receive = {
case evt: Evt updateState(evt) case evt: Evt => updateState(evt)
case SnapshotOffer(_, snapshot: ExampleState) state = snapshot case SnapshotOffer(_, snapshot: ExampleState) => state = snapshot
} }
val receiveCommand: Receive = { val receiveCommand: Receive = {
case Cmd(data) case Cmd(data) =>
persist(Evt(s"${data}-${numEvents}"))(updateState) persist(Evt(s"${data}-${numEvents}"))(updateState)
persist(Evt(s"${data}-${numEvents + 1}")) { event persist(Evt(s"${data}-${numEvents + 1}")) { event =>
updateState(event) updateState(event)
context.system.eventStream.publish(event) context.system.eventStream.publish(event)
if (data == "foo") context.become(otherCommandHandler) if (data == "foo") context.become(otherCommandHandler)
} }
case "snap" saveSnapshot(state) case "snap" => saveSnapshot(state)
case "print" println(state) case "print" => println(state)
} }
val otherCommandHandler: Receive = { val otherCommandHandler: Receive = {
case Cmd("bar") case Cmd("bar") =>
persist(Evt(s"bar-${numEvents}")) { event persist(Evt(s"bar-${numEvents}")) { event =>
updateState(event) updateState(event)
context.unbecome() context.unbecome()
} }
unstashAll() unstashAll()
case other stash() case other => stash()
} }
} }
//#eventsourced-example //#eventsourced-example

View file

@ -16,7 +16,7 @@ object ProcessorChannelExample extends App {
var received: List[Persistent] = Nil var received: List[Persistent] = Nil
def receive = { def receive = {
case p @ Persistent(payload, _) case p @ Persistent(payload, _) =>
println(s"processed ${payload}") println(s"processed ${payload}")
channel forward Deliver(p.withPayload(s"processed ${payload}"), destination) channel forward Deliver(p.withPayload(s"processed ${payload}"), destination)
} }
@ -24,7 +24,7 @@ object ProcessorChannelExample extends App {
class ExampleDestination extends Actor { class ExampleDestination extends Actor {
def receive = { def receive = {
case p @ ConfirmablePersistent(payload, snr, _) case p @ ConfirmablePersistent(payload, snr, _) =>
println(s"received ${payload}") println(s"received ${payload}")
sender ! s"re: ${payload} (${snr})" sender ! s"re: ${payload} (${snr})"
p.confirm() p.confirm()
@ -37,8 +37,8 @@ object ProcessorChannelExample extends App {
implicit val timeout = Timeout(3000) implicit val timeout = Timeout(3000)
import system.dispatcher import system.dispatcher
processor ? Persistent("a") onSuccess { case reply println(s"reply = ${reply}") } processor ? Persistent("a") onSuccess { case reply => println(s"reply = ${reply}") }
processor ? Persistent("b") onSuccess { case reply println(s"reply = ${reply}") } processor ? Persistent("b") onSuccess { case reply => println(s"reply = ${reply}") }
Thread.sleep(1000) Thread.sleep(1000)
system.shutdown() system.shutdown()

View file

@ -12,16 +12,16 @@ object ProcessorFailureExample extends App {
var received: List[String] = Nil // state var received: List[String] = Nil // state
def receive = { def receive = {
case "print" println(s"received ${received.reverse}") case "print" => println(s"received ${received.reverse}")
case "boom" throw new Exception("boom") case "boom" => throw new Exception("boom")
case Persistent("boom", _) throw new Exception("boom") case Persistent("boom", _) => throw new Exception("boom")
case Persistent(payload: String, _) received = payload :: received case Persistent(payload: String, _) => received = payload :: received
} }
override def preRestart(reason: Throwable, message: Option[Any]) { override def preRestart(reason: Throwable, message: Option[Any]) {
message match { message match {
case Some(p: Persistent) if !recoveryRunning deleteMessage(p.sequenceNr) // mark failing message as deleted case Some(p: Persistent) if !recoveryRunning => deleteMessage(p.sequenceNr) // mark failing message as deleted
case _ // ignore case _ => // ignore
} }
super.preRestart(reason, message) super.preRestart(reason, message)
} }

View file

@ -17,14 +17,14 @@ object SnapshotExample extends App {
var state = ExampleState() var state = ExampleState()
def receive = { def receive = {
case Persistent(s, snr) state = state.update(s"${s}-${snr}") case Persistent(s, snr) => state = state.update(s"${s}-${snr}")
case SaveSnapshotSuccess(metadata) // ... case SaveSnapshotSuccess(metadata) => // ...
case SaveSnapshotFailure(metadata, reason) // ... case SaveSnapshotFailure(metadata, reason) => // ...
case SnapshotOffer(_, s: ExampleState) case SnapshotOffer(_, s: ExampleState) =>
println("offered state = " + s) println("offered state = " + s)
state = s state = s
case "print" println("current state = " + state) case "print" => println("current state = " + state)
case "snap" saveSnapshot(state) case "snap" => saveSnapshot(state)
} }
} }

View file

@ -151,7 +151,7 @@ object AkkaBuild extends Build {
lazy val actor = Project( lazy val actor = Project(
id = "akka-actor", id = "akka-actor",
base = file("akka-actor"), base = file("akka-actor"),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ Seq(
// to fix scaladoc generation // to fix scaladoc generation
fullClasspath in doc in Compile <<= fullClasspath in Compile, fullClasspath in doc in Compile <<= fullClasspath in Compile,
libraryDependencies ++= Dependencies.actor, libraryDependencies ++= Dependencies.actor,
@ -168,7 +168,7 @@ object AkkaBuild extends Build {
id = "akka-dataflow", id = "akka-dataflow",
base = file("akka-dataflow"), base = file("akka-dataflow"),
dependencies = Seq(testkit % "test->test"), dependencies = Seq(testkit % "test->test"),
settings = defaultSettings ++ scaladocSettings ++ OSGi.dataflow ++ cpsPlugin ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ OSGi.dataflow ++ cpsPlugin ++ Seq(
previousArtifact := akkaPreviousArtifact("akka-dataflow") previousArtifact := akkaPreviousArtifact("akka-dataflow")
) )
) )
@ -177,7 +177,7 @@ object AkkaBuild extends Build {
id = "akka-testkit", id = "akka-testkit",
base = file("akka-testkit"), base = file("akka-testkit"),
dependencies = Seq(actor), dependencies = Seq(actor),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.testkit ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.testkit ++ Seq(
libraryDependencies ++= Dependencies.testkit, libraryDependencies ++= Dependencies.testkit,
initialCommands += "import akka.testkit._", initialCommands += "import akka.testkit._",
previousArtifact := akkaPreviousArtifact("akka-testkit") previousArtifact := akkaPreviousArtifact("akka-testkit")
@ -188,7 +188,7 @@ object AkkaBuild extends Build {
id = "akka-actor-tests", id = "akka-actor-tests",
base = file("akka-actor-tests"), base = file("akka-actor-tests"),
dependencies = Seq(testkit % "compile;test->test"), dependencies = Seq(testkit % "compile;test->test"),
settings = defaultSettings ++ scaladocSettings ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ Seq(
publishArtifact in Compile := false, publishArtifact in Compile := false,
libraryDependencies ++= Dependencies.actorTests, libraryDependencies ++= Dependencies.actorTests,
testOptions += Tests.Argument(TestFrameworks.JUnit, "-v", "-a"), testOptions += Tests.Argument(TestFrameworks.JUnit, "-v", "-a"),
@ -200,7 +200,7 @@ object AkkaBuild extends Build {
id = "akka-remote", id = "akka-remote",
base = file("akka-remote"), base = file("akka-remote"),
dependencies = Seq(actor, actorTests % "test->test", testkit % "test->test"), dependencies = Seq(actor, actorTests % "test->test", testkit % "test->test"),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.remote ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.remote ++ Seq(
libraryDependencies ++= Dependencies.remote, libraryDependencies ++= Dependencies.remote,
// disable parallel tests // disable parallel tests
parallelExecution in Test := false, parallelExecution in Test := false,
@ -212,7 +212,7 @@ object AkkaBuild extends Build {
id = "akka-multi-node-testkit", id = "akka-multi-node-testkit",
base = file("akka-multi-node-testkit"), base = file("akka-multi-node-testkit"),
dependencies = Seq(remote, testkit), dependencies = Seq(remote, testkit),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ Seq(
previousArtifact := akkaPreviousArtifact("akka-multi-node-testkit") previousArtifact := akkaPreviousArtifact("akka-multi-node-testkit")
) )
) )
@ -221,7 +221,7 @@ object AkkaBuild extends Build {
id = "akka-remote-tests", id = "akka-remote-tests",
base = file("akka-remote-tests"), base = file("akka-remote-tests"),
dependencies = Seq(actorTests % "test->test", multiNodeTestkit), dependencies = Seq(actorTests % "test->test", multiNodeTestkit),
settings = defaultSettings ++ scaladocSettings ++ multiJvmSettings ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ multiJvmSettings ++ Seq(
libraryDependencies ++= Dependencies.remoteTests, libraryDependencies ++= Dependencies.remoteTests,
// disable parallel tests // disable parallel tests
parallelExecution in Test := false, parallelExecution in Test := false,
@ -238,7 +238,7 @@ object AkkaBuild extends Build {
id = "akka-cluster", id = "akka-cluster",
base = file("akka-cluster"), base = file("akka-cluster"),
dependencies = Seq(remote, remoteTests % "test->test" , testkit % "test->test"), dependencies = Seq(remote, remoteTests % "test->test" , testkit % "test->test"),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ multiJvmSettings ++ OSGi.cluster ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ multiJvmSettings ++ OSGi.cluster ++ Seq(
libraryDependencies ++= Dependencies.cluster, libraryDependencies ++= Dependencies.cluster,
// disable parallel tests // disable parallel tests
parallelExecution in Test := false, parallelExecution in Test := false,
@ -254,7 +254,7 @@ object AkkaBuild extends Build {
id = "akka-slf4j", id = "akka-slf4j",
base = file("akka-slf4j"), base = file("akka-slf4j"),
dependencies = Seq(actor, testkit % "test->test"), dependencies = Seq(actor, testkit % "test->test"),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.slf4j ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.slf4j ++ Seq(
libraryDependencies ++= Dependencies.slf4j, libraryDependencies ++= Dependencies.slf4j,
previousArtifact := akkaPreviousArtifact("akka-slf4j") previousArtifact := akkaPreviousArtifact("akka-slf4j")
) )
@ -264,7 +264,7 @@ object AkkaBuild extends Build {
id = "akka-agent", id = "akka-agent",
base = file("akka-agent"), base = file("akka-agent"),
dependencies = Seq(actor, testkit % "test->test"), dependencies = Seq(actor, testkit % "test->test"),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.agent ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.agent ++ Seq(
libraryDependencies ++= Dependencies.agent, libraryDependencies ++= Dependencies.agent,
previousArtifact := akkaPreviousArtifact("akka-agent") previousArtifact := akkaPreviousArtifact("akka-agent")
) )
@ -274,7 +274,7 @@ object AkkaBuild extends Build {
id = "akka-transactor", id = "akka-transactor",
base = file("akka-transactor"), base = file("akka-transactor"),
dependencies = Seq(actor, testkit % "test->test"), dependencies = Seq(actor, testkit % "test->test"),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.transactor ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.transactor ++ Seq(
libraryDependencies ++= Dependencies.transactor, libraryDependencies ++= Dependencies.transactor,
previousArtifact := akkaPreviousArtifact("akka-transactor") previousArtifact := akkaPreviousArtifact("akka-transactor")
) )
@ -284,7 +284,7 @@ object AkkaBuild extends Build {
id = "akka-persistence-experimental", id = "akka-persistence-experimental",
base = file("akka-persistence"), base = file("akka-persistence"),
dependencies = Seq(actor, remote % "test->test", testkit % "test->test"), dependencies = Seq(actor, remote % "test->test", testkit % "test->test"),
settings = defaultSettings ++ scaladocSettings ++ experimentalSettings ++ javadocSettings ++ OSGi.persistence ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ experimentalSettings ++ javadocSettings ++ OSGi.persistence ++ Seq(
fork in Test := true, fork in Test := true,
libraryDependencies ++= Dependencies.persistence, libraryDependencies ++= Dependencies.persistence,
previousArtifact := akkaPreviousArtifact("akka-persistence") previousArtifact := akkaPreviousArtifact("akka-persistence")
@ -304,7 +304,7 @@ object AkkaBuild extends Build {
id = "akka-mailboxes-common", id = "akka-mailboxes-common",
base = file("akka-durable-mailboxes/akka-mailboxes-common"), base = file("akka-durable-mailboxes/akka-mailboxes-common"),
dependencies = Seq(remote, testkit % "compile;test->test"), dependencies = Seq(remote, testkit % "compile;test->test"),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.mailboxesCommon ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.mailboxesCommon ++ Seq(
libraryDependencies ++= Dependencies.mailboxes, libraryDependencies ++= Dependencies.mailboxes,
previousArtifact := akkaPreviousArtifact("akka-mailboxes-common"), previousArtifact := akkaPreviousArtifact("akka-mailboxes-common"),
publishArtifact in Test := true publishArtifact in Test := true
@ -315,7 +315,7 @@ object AkkaBuild extends Build {
id = "akka-file-mailbox", id = "akka-file-mailbox",
base = file("akka-durable-mailboxes/akka-file-mailbox"), base = file("akka-durable-mailboxes/akka-file-mailbox"),
dependencies = Seq(mailboxesCommon % "compile;test->test", testkit % "test"), dependencies = Seq(mailboxesCommon % "compile;test->test", testkit % "test"),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.fileMailbox ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.fileMailbox ++ Seq(
libraryDependencies ++= Dependencies.fileMailbox, libraryDependencies ++= Dependencies.fileMailbox,
previousArtifact := akkaPreviousArtifact("akka-file-mailbox") previousArtifact := akkaPreviousArtifact("akka-file-mailbox")
) )
@ -325,7 +325,7 @@ object AkkaBuild extends Build {
id = "akka-zeromq", id = "akka-zeromq",
base = file("akka-zeromq"), base = file("akka-zeromq"),
dependencies = Seq(actor, testkit % "test;test->test"), dependencies = Seq(actor, testkit % "test;test->test"),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.zeroMQ ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.zeroMQ ++ Seq(
libraryDependencies ++= Dependencies.zeroMQ, libraryDependencies ++= Dependencies.zeroMQ,
previousArtifact := akkaPreviousArtifact("akka-zeromq") previousArtifact := akkaPreviousArtifact("akka-zeromq")
) )
@ -335,7 +335,7 @@ object AkkaBuild extends Build {
id = "akka-kernel", id = "akka-kernel",
base = file("akka-kernel"), base = file("akka-kernel"),
dependencies = Seq(actor, testkit % "test->test"), dependencies = Seq(actor, testkit % "test->test"),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ Seq(
libraryDependencies ++= Dependencies.kernel, libraryDependencies ++= Dependencies.kernel,
previousArtifact := akkaPreviousArtifact("akka-kernel") previousArtifact := akkaPreviousArtifact("akka-kernel")
) )
@ -345,7 +345,7 @@ object AkkaBuild extends Build {
id = "akka-camel", id = "akka-camel",
base = file("akka-camel"), base = file("akka-camel"),
dependencies = Seq(actor, slf4j, testkit % "test->test"), dependencies = Seq(actor, slf4j, testkit % "test->test"),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.camel ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.camel ++ Seq(
libraryDependencies ++= Dependencies.camel, libraryDependencies ++= Dependencies.camel,
testOptions += Tests.Argument(TestFrameworks.JUnit, "-v", "-a"), testOptions += Tests.Argument(TestFrameworks.JUnit, "-v", "-a"),
previousArtifact := akkaPreviousArtifact("akka-camel") previousArtifact := akkaPreviousArtifact("akka-camel")
@ -406,7 +406,7 @@ object AkkaBuild extends Build {
id = "akka-osgi", id = "akka-osgi",
base = file("akka-osgi"), base = file("akka-osgi"),
dependencies = Seq(actor), dependencies = Seq(actor),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.osgi ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.osgi ++ Seq(
libraryDependencies ++= Dependencies.osgi, libraryDependencies ++= Dependencies.osgi,
cleanFiles <+= baseDirectory { base => base / "src/main/resources" } , cleanFiles <+= baseDirectory { base => base / "src/main/resources" } ,
ActorOsgiConfigurationReference <<= ActorOsgiConfigurationReferenceAction(projects.filter(p => !p.id.contains("test") && !p.id.contains("sample"))), ActorOsgiConfigurationReference <<= ActorOsgiConfigurationReferenceAction(projects.filter(p => !p.id.contains("test") && !p.id.contains("sample"))),
@ -421,7 +421,7 @@ object AkkaBuild extends Build {
id = "akka-osgi-aries", id = "akka-osgi-aries",
base = file("akka-osgi-aries"), base = file("akka-osgi-aries"),
dependencies = Seq(osgi % "compile;test->test"), dependencies = Seq(osgi % "compile;test->test"),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.osgiAries ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ OSGi.osgiAries ++ Seq(
libraryDependencies ++= Dependencies.osgiAries, libraryDependencies ++= Dependencies.osgiAries,
parallelExecution in Test := false, parallelExecution in Test := false,
reportBinaryIssues := () // disable bin comp check reportBinaryIssues := () // disable bin comp check
@ -431,7 +431,7 @@ object AkkaBuild extends Build {
lazy val akkaSbtPlugin = Project( lazy val akkaSbtPlugin = Project(
id = "akka-sbt-plugin", id = "akka-sbt-plugin",
base = file("akka-sbt-plugin"), base = file("akka-sbt-plugin"),
settings = defaultSettings ++ Seq( settings = defaultSettings ++ formatSettings ++ Seq(
sbtPlugin := true, sbtPlugin := true,
publishMavenStyle := false, // SBT Plugins should be published as Ivy publishMavenStyle := false, // SBT Plugins should be published as Ivy
publishTo <<= Publish.akkaPluginPublishTo, publishTo <<= Publish.akkaPluginPublishTo,
@ -519,7 +519,7 @@ object AkkaBuild extends Build {
id = "akka-sample-cluster-java", id = "akka-sample-cluster-java",
base = file("akka-samples/akka-sample-cluster-java"), base = file("akka-samples/akka-sample-cluster-java"),
dependencies = Seq(cluster, contrib, remoteTests % "test", testkit % "test"), dependencies = Seq(cluster, contrib, remoteTests % "test", testkit % "test"),
settings = sampleSettings ++ multiJvmSettings ++ Seq( settings = multiJvmSettings ++ sampleSettings ++ Seq(
libraryDependencies ++= Dependencies.clusterSample, libraryDependencies ++= Dependencies.clusterSample,
javaOptions in run ++= Seq( javaOptions in run ++= Seq(
"-Djava.library.path=./sigar", "-Djava.library.path=./sigar",
@ -537,7 +537,7 @@ object AkkaBuild extends Build {
id = "akka-sample-cluster-scala", id = "akka-sample-cluster-scala",
base = file("akka-samples/akka-sample-cluster-scala"), base = file("akka-samples/akka-sample-cluster-scala"),
dependencies = Seq(cluster, contrib, remoteTests % "test", testkit % "test"), dependencies = Seq(cluster, contrib, remoteTests % "test", testkit % "test"),
settings = sampleSettings ++ multiJvmSettings ++ Seq( settings = multiJvmSettings ++ sampleSettings ++ Seq(
libraryDependencies ++= Dependencies.clusterSample, libraryDependencies ++= Dependencies.clusterSample,
javaOptions in run ++= Seq( javaOptions in run ++= Seq(
"-Djava.library.path=./sigar", "-Djava.library.path=./sigar",
@ -555,7 +555,7 @@ object AkkaBuild extends Build {
id = "akka-sample-multi-node", id = "akka-sample-multi-node",
base = file("akka-samples/akka-sample-multi-node"), base = file("akka-samples/akka-sample-multi-node"),
dependencies = Seq(multiNodeTestkit % "test", testkit % "test"), dependencies = Seq(multiNodeTestkit % "test", testkit % "test"),
settings = sampleSettings ++ multiJvmSettings ++ experimentalSettings ++ Seq( settings = multiJvmSettings ++ sampleSettings ++ experimentalSettings ++ Seq(
libraryDependencies ++= Dependencies.multiNodeSample, libraryDependencies ++= Dependencies.multiNodeSample,
// disable parallel tests // disable parallel tests
parallelExecution in Test := false, parallelExecution in Test := false,
@ -623,7 +623,7 @@ object AkkaBuild extends Build {
dependencies = Seq(actor, testkit % "test->test", mailboxesCommon % "compile;test->test", channels, dependencies = Seq(actor, testkit % "test->test", mailboxesCommon % "compile;test->test", channels,
remote % "compile;test->test", cluster, slf4j, agent, dataflow, transactor, fileMailbox, zeroMQ, camel, osgi, osgiAries, remote % "compile;test->test", cluster, slf4j, agent, dataflow, transactor, fileMailbox, zeroMQ, camel, osgi, osgiAries,
persistence % "compile;test->test"), persistence % "compile;test->test"),
settings = defaultSettings ++ site.settings ++ site.sphinxSupport() ++ site.publishSite ++ sphinxPreprocessing ++ cpsPlugin ++ Seq( settings = defaultSettings ++ docFormatSettings ++ site.settings ++ site.sphinxSupport() ++ site.publishSite ++ sphinxPreprocessing ++ cpsPlugin ++ Seq(
sourceDirectory in Sphinx <<= baseDirectory / "rst", sourceDirectory in Sphinx <<= baseDirectory / "rst",
sphinxPackages in Sphinx <+= baseDirectory { _ / "_sphinx" / "pygments" }, sphinxPackages in Sphinx <+= baseDirectory { _ / "_sphinx" / "pygments" },
// copy akka-contrib/docs into our rst_preprocess/contrib (and apply substitutions) // copy akka-contrib/docs into our rst_preprocess/contrib (and apply substitutions)
@ -653,7 +653,7 @@ object AkkaBuild extends Build {
id = "akka-contrib", id = "akka-contrib",
base = file("akka-contrib"), base = file("akka-contrib"),
dependencies = Seq(remote, remoteTests % "test->test", cluster), dependencies = Seq(remote, remoteTests % "test->test", cluster),
settings = defaultSettings ++ scaladocSettings ++ javadocSettings ++ multiJvmSettings ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ javadocSettings ++ multiJvmSettings ++ Seq(
libraryDependencies ++= Dependencies.contrib, libraryDependencies ++= Dependencies.contrib,
testOptions += Tests.Argument(TestFrameworks.JUnit, "-v"), testOptions += Tests.Argument(TestFrameworks.JUnit, "-v"),
reportBinaryIssues := (), // disable bin comp check reportBinaryIssues := (), // disable bin comp check
@ -674,7 +674,7 @@ object AkkaBuild extends Build {
id = "akka-channels-experimental", id = "akka-channels-experimental",
base = file("akka-channels"), base = file("akka-channels"),
dependencies = Seq(actor), dependencies = Seq(actor),
settings = defaultSettings ++ scaladocSettings ++ experimentalSettings ++ Seq( settings = defaultSettings ++ formatSettings ++ scaladocSettings ++ experimentalSettings ++ Seq(
libraryDependencies +=("org.scala-lang" % "scala-reflect" % scalaVersion.value), libraryDependencies +=("org.scala-lang" % "scala-reflect" % scalaVersion.value),
reportBinaryIssues := () // disable bin comp check reportBinaryIssues := () // disable bin comp check
) )
@ -690,7 +690,7 @@ object AkkaBuild extends Build {
id = "akka-channels-tests", id = "akka-channels-tests",
base = file("akka-channels-tests"), base = file("akka-channels-tests"),
dependencies = Seq(channels, testkit % "compile;test->test"), dependencies = Seq(channels, testkit % "compile;test->test"),
settings = defaultSettings ++ experimentalSettings ++ Seq( settings = defaultSettings ++ formatSettings ++ experimentalSettings ++ Seq(
publishArtifact in Compile := false, publishArtifact in Compile := false,
libraryDependencies += excludeOldModules("org.scala-lang" % "scala-compiler" % scalaVersion.value), libraryDependencies += excludeOldModules("org.scala-lang" % "scala-compiler" % scalaVersion.value),
reportBinaryIssues := () // disable bin comp check reportBinaryIssues := () // disable bin comp check
@ -714,7 +714,7 @@ object AkkaBuild extends Build {
reportBinaryIssues := () // disable bin comp check reportBinaryIssues := () // disable bin comp check
) )
lazy val sampleSettings = defaultSettings ++ Seq( lazy val sampleSettings = defaultSettings ++ docFormatSettings ++ Seq(
publishArtifact in (Compile, packageBin) := false, publishArtifact in (Compile, packageBin) := false,
reportBinaryIssues := () // disable bin comp check reportBinaryIssues := () // disable bin comp check
) )
@ -800,7 +800,7 @@ object AkkaBuild extends Build {
else Seq.empty else Seq.empty
} }
lazy val defaultSettings = baseSettings ++ formatSettings ++ mimaSettings ++ lsSettings ++ resolverSettings ++ lazy val defaultSettings = baseSettings ++ mimaSettings ++ lsSettings ++ resolverSettings ++
Protobuf.settings ++ Seq( Protobuf.settings ++ Seq(
// compile options // compile options
scalacOptions in Compile ++= Seq("-encoding", "UTF-8", "-target:jvm-1.6", "-deprecation", "-feature", "-unchecked", "-Xlog-reflective-calls", "-Xlint"), scalacOptions in Compile ++= Seq("-encoding", "UTF-8", "-target:jvm-1.6", "-deprecation", "-feature", "-unchecked", "-Xlog-reflective-calls", "-Xlint"),
@ -910,8 +910,14 @@ object AkkaBuild extends Build {
) )
lazy val formatSettings = SbtScalariform.scalariformSettings ++ Seq( lazy val formatSettings = SbtScalariform.scalariformSettings ++ Seq(
ScalariformKeys.preferences in Compile := formattingPreferences, ScalariformKeys.preferences in Compile := formattingPreferences,
ScalariformKeys.preferences in Test := formattingPreferences ScalariformKeys.preferences in Test := formattingPreferences
)
lazy val docFormatSettings = SbtScalariform.scalariformSettings ++ Seq(
ScalariformKeys.preferences in Compile := docFormattingPreferences,
ScalariformKeys.preferences in Test := docFormattingPreferences,
ScalariformKeys.preferences in MultiJvm := docFormattingPreferences
) )
def formattingPreferences = { def formattingPreferences = {
@ -922,6 +928,14 @@ object AkkaBuild extends Build {
.setPreference(AlignSingleLineCaseStatements, true) .setPreference(AlignSingleLineCaseStatements, true)
} }
def docFormattingPreferences = {
import scalariform.formatter.preferences._
FormattingPreferences()
.setPreference(RewriteArrowSymbols, false)
.setPreference(AlignParameters, true)
.setPreference(AlignSingleLineCaseStatements, true)
}
lazy val multiJvmSettings = SbtMultiJvm.multiJvmSettings ++ inConfig(MultiJvm)(SbtScalariform.configScalariformSettings) ++ Seq( lazy val multiJvmSettings = SbtMultiJvm.multiJvmSettings ++ inConfig(MultiJvm)(SbtScalariform.configScalariformSettings) ++ Seq(
jvmOptions in MultiJvm := defaultMultiJvmOptions, jvmOptions in MultiJvm := defaultMultiJvmOptions,
compileInputs in (MultiJvm, compile) <<= (compileInputs in (MultiJvm, compile)) dependsOn (ScalariformKeys.format in MultiJvm), compileInputs in (MultiJvm, compile) <<= (compileInputs in (MultiJvm, compile)) dependsOn (ScalariformKeys.format in MultiJvm),