diff --git a/akka-actor-tests/src/main/scala/akka/testing/TestBarrier.scala b/akka-actor-tests/src/main/scala/akka/testing/TestBarrier.scala
index 650ef7de79..8806bf903e 100644
--- a/akka-actor-tests/src/main/scala/akka/testing/TestBarrier.scala
+++ b/akka-actor-tests/src/main/scala/akka/testing/TestBarrier.scala
@@ -5,8 +5,7 @@
package akka.testing
import akka.util.Duration
-import java.util.concurrent.{CyclicBarrier, TimeUnit, TimeoutException}
-
+import java.util.concurrent.{ CyclicBarrier, TimeUnit, TimeoutException }
class TestBarrierTimeoutException(message: String) extends RuntimeException(message)
@@ -31,7 +30,7 @@ class TestBarrier(count: Int) {
try {
barrier.await(Testing.testTime(timeout.toNanos), TimeUnit.NANOSECONDS)
} catch {
- case e: TimeoutException =>
+ case e: TimeoutException ⇒
throw new TestBarrierTimeoutException("Timeout of %s and time factor of %s" format (timeout.toString, Testing.timeFactor))
}
}
diff --git a/akka-actor-tests/src/main/scala/akka/testing/TestLatch.scala b/akka-actor-tests/src/main/scala/akka/testing/TestLatch.scala
index aeefa04dd7..239aa6987f 100644
--- a/akka-actor-tests/src/main/scala/akka/testing/TestLatch.scala
+++ b/akka-actor-tests/src/main/scala/akka/testing/TestLatch.scala
@@ -5,8 +5,7 @@
package akka.testing
import akka.util.Duration
-import java.util.concurrent.{CountDownLatch, TimeUnit}
-
+import java.util.concurrent.{ CountDownLatch, TimeUnit }
class TestLatchTimeoutException(message: String) extends RuntimeException(message)
class TestLatchNoTimeoutException(message: String) extends RuntimeException(message)
diff --git a/akka-actor-tests/src/main/scala/akka/testing/Testing.scala b/akka-actor-tests/src/main/scala/akka/testing/Testing.scala
index 98733c5434..730f35f840 100644
--- a/akka-actor-tests/src/main/scala/akka/testing/Testing.scala
+++ b/akka-actor-tests/src/main/scala/akka/testing/Testing.scala
@@ -16,7 +16,7 @@ object Testing {
try {
factor.toDouble
} catch {
- case e: java.lang.NumberFormatException => 1.0
+ case e: java.lang.NumberFormatException ⇒ 1.0
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/actor/ActorFireForgetRequestReplySpec.scala b/akka-actor-tests/src/test/scala/akka/actor/actor/ActorFireForgetRequestReplySpec.scala
index f76c328573..dd0cb87990 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/actor/ActorFireForgetRequestReplySpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/actor/ActorFireForgetRequestReplySpec.scala
@@ -16,14 +16,13 @@ import Actor._
import akka.config.Supervision._
import akka.dispatch.Dispatchers
-
object ActorFireForgetRequestReplySpec {
class ReplyActor extends Actor {
def receive = {
- case "Send" =>
+ case "Send" ⇒
self.reply("Reply")
- case "SendImplicit" =>
+ case "SendImplicit" ⇒
self.sender.get ! "ReplyImplicit"
}
}
@@ -32,7 +31,7 @@ object ActorFireForgetRequestReplySpec {
self.lifeCycle = Temporary
def receive = {
- case "Die" =>
+ case "Die" ⇒
state.finished.await
throw new Exception("Expected exception")
}
@@ -40,14 +39,14 @@ object ActorFireForgetRequestReplySpec {
class SenderActor(replyActor: ActorRef) extends Actor {
def receive = {
- case "Init" =>
+ case "Init" ⇒
replyActor ! "Send"
- case "Reply" => {
+ case "Reply" ⇒ {
state.s = "Reply"
state.finished.await
}
- case "InitImplicit" => replyActor ! "SendImplicit"
- case "ReplyImplicit" => {
+ case "InitImplicit" ⇒ replyActor ! "SendImplicit"
+ case "ReplyImplicit" ⇒ {
state.s = "ReplyImplicit"
state.finished.await
}
@@ -65,16 +64,16 @@ class ActorFireForgetRequestReplySpec extends WordSpec with MustMatchers with Be
override def beforeEach() = {
state.finished.reset
- }
-
+ }
+
"An Actor" must {
- "reply to bang message using reply" in {
+ "reply to bang message using reply" in {
val replyActor = actorOf[ReplyActor].start()
val senderActor = actorOf(new SenderActor(replyActor)).start()
senderActor ! "Init"
state.finished.await
- state.s must be ("Reply")
+ state.s must be("Reply")
}
"reply to bang message using implicit sender" in {
@@ -82,16 +81,16 @@ class ActorFireForgetRequestReplySpec extends WordSpec with MustMatchers with Be
val senderActor = actorOf(new SenderActor(replyActor)).start()
senderActor ! "InitImplicit"
state.finished.await
- state.s must be ("ReplyImplicit")
+ state.s must be("ReplyImplicit")
}
"should shutdown crashed temporary actor" in {
val actor = actorOf[CrashingTemporaryActor].start()
- actor.isRunning must be (true)
+ actor.isRunning must be(true)
actor ! "Die"
state.finished.await
sleepFor(1 second)
- actor.isShutdown must be (true)
+ actor.isShutdown must be(true)
}
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/actor/ActorRefSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/actor/ActorRefSpec.scala
index 6c4374809e..944e334712 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/actor/ActorRefSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/actor/ActorRefSpec.scala
@@ -10,10 +10,10 @@ import org.scalatest.matchers.MustMatchers
import akka.testing._
import akka.util.duration._
import akka.testing.Testing.sleepFor
-import akka.config.Supervision.{OneForOneStrategy}
+import akka.config.Supervision.{ OneForOneStrategy }
import akka.actor._
import akka.dispatch.Future
-import java.util.concurrent.{TimeUnit, CountDownLatch}
+import java.util.concurrent.{ TimeUnit, CountDownLatch }
object ActorRefSpec {
@@ -23,27 +23,27 @@ object ActorRefSpec {
var replyTo: Channel[Any] = null
def receive = {
- case "complexRequest" => {
+ case "complexRequest" ⇒ {
replyTo = self.channel
val worker = Actor.actorOf[WorkerActor].start()
worker ! "work"
}
- case "complexRequest2" =>
+ case "complexRequest2" ⇒
val worker = Actor.actorOf[WorkerActor].start()
worker ! self.channel
- case "workDone" => replyTo ! "complexReply"
- case "simpleRequest" => self.reply("simpleReply")
+ case "workDone" ⇒ replyTo ! "complexReply"
+ case "simpleRequest" ⇒ self.reply("simpleReply")
}
}
class WorkerActor() extends Actor {
def receive = {
- case "work" => {
+ case "work" ⇒ {
work
self.reply("workDone")
self.stop()
}
- case replyTo: Channel[Any] => {
+ case replyTo: Channel[Any] ⇒ {
work
replyTo ! "complexReply"
}
@@ -57,13 +57,13 @@ object ActorRefSpec {
class SenderActor(replyActor: ActorRef) extends Actor {
def receive = {
- case "complex" => replyActor ! "complexRequest"
- case "complex2" => replyActor ! "complexRequest2"
- case "simple" => replyActor ! "simpleRequest"
- case "complexReply" => {
+ case "complex" ⇒ replyActor ! "complexRequest"
+ case "complex2" ⇒ replyActor ! "complexRequest2"
+ case "simple" ⇒ replyActor ! "simpleRequest"
+ case "complexReply" ⇒ {
latch.countDown()
}
- case "simpleReply" => {
+ case "simpleReply" ⇒ {
latch.countDown()
}
}
@@ -77,14 +77,14 @@ class ActorRefSpec extends WordSpec with MustMatchers {
"not allow Actors to be created outside of an actorOf" in {
intercept[akka.actor.ActorInitializationException] {
- new Actor { def receive = { case _ => } }
+ new Actor { def receive = { case _ ⇒ } }
fail("shouldn't get here")
}
intercept[akka.actor.ActorInitializationException] {
val a = Actor.actorOf(new Actor {
- val nested = new Actor { def receive = { case _ => } }
- def receive = { case _ => }
+ val nested = new Actor { def receive = { case _ ⇒ } }
+ def receive = { case _ ⇒ }
}).start()
fail("shouldn't get here")
}
@@ -92,8 +92,8 @@ class ActorRefSpec extends WordSpec with MustMatchers {
"support nested actorOfs" in {
val a = Actor.actorOf(new Actor {
- val nested = Actor.actorOf(new Actor { def receive = { case _ => } }).start()
- def receive = { case _ => self reply nested }
+ val nested = Actor.actorOf(new Actor { def receive = { case _ ⇒ } }).start()
+ def receive = { case _ ⇒ self reply nested }
}).start()
val nested = (a !! "any").get.asInstanceOf[ActorRef]
@@ -101,7 +101,7 @@ class ActorRefSpec extends WordSpec with MustMatchers {
nested must not be null
(a ne nested) must be === true
}
-
+
"support reply via channel" in {
val serverRef = Actor.actorOf[ReplyActor].start()
val clientRef = Actor.actorOf(new SenderActor(serverRef)).start()
@@ -130,11 +130,10 @@ class ActorRefSpec extends WordSpec with MustMatchers {
val ref = Actor.actorOf(
new Actor {
def receive = {
- case 5 => self reply_? "five"
- case null => self reply_? "null"
+ case 5 ⇒ self reply_? "five"
+ case null ⇒ self reply_? "null"
}
- }
- ).start()
+ }).start()
val ffive: Future[String] = ref !!! 5
val fnull: Future[String] = ref !!! null
@@ -144,30 +143,29 @@ class ActorRefSpec extends WordSpec with MustMatchers {
fail("shouldn't get here")
}
- ffive.resultOrException.get must be ("five")
- fnull.resultOrException.get must be ("null")
+ ffive.resultOrException.get must be("five")
+ fnull.resultOrException.get must be("null")
- ref.isRunning must be (false)
- ref.isShutdown must be (true)
+ ref.isRunning must be(false)
+ ref.isShutdown must be(true)
}
"restart when Kill:ed" in {
val latch = new CountDownLatch(2)
- val boss = Actor.actorOf(new Actor{
+ val boss = Actor.actorOf(new Actor {
self.faultHandler = OneForOneStrategy(List(classOf[Throwable]), scala.Some(2), scala.Some(1000))
val ref = Actor.actorOf(
new Actor {
- def receive = { case _ => }
+ def receive = { case _ ⇒ }
override def preRestart(reason: Throwable) = latch.countDown()
override def postRestart(reason: Throwable) = latch.countDown()
- }
- ).start()
+ }).start()
self link ref
- protected def receive = { case "sendKill" => ref ! Kill }
+ protected def receive = { case "sendKill" ⇒ ref ! Kill }
}).start()
boss ! "sendKill"
diff --git a/akka-actor-tests/src/test/scala/akka/actor/actor/Bench.scala b/akka-actor-tests/src/test/scala/akka/actor/actor/Bench.scala
index 1f121babd5..258809c5b6 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/actor/Bench.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/actor/Bench.scala
@@ -27,51 +27,51 @@ object Chameneos {
var end = 0L
class Chameneo(var mall: ActorRef, var colour: Colour, cid: Int) extends Actor {
- var meetings = 0
- self.start()
- mall ! Meet(self, colour)
+ var meetings = 0
+ self.start()
+ mall ! Meet(self, colour)
- def receive = {
- case Meet(from, otherColour) =>
- colour = complement(otherColour)
- meetings = meetings +1
- from ! Change(colour)
- mall ! Meet(self, colour)
+ def receive = {
+ case Meet(from, otherColour) ⇒
+ colour = complement(otherColour)
+ meetings = meetings + 1
+ from ! Change(colour)
+ mall ! Meet(self, colour)
- case Change(newColour) =>
- colour = newColour
- meetings = meetings +1
- mall ! Meet(self, colour)
+ case Change(newColour) ⇒
+ colour = newColour
+ meetings = meetings + 1
+ mall ! Meet(self, colour)
- case Exit =>
- colour = FADED
- self.sender.get ! MeetingCount(meetings)
- }
+ case Exit ⇒
+ colour = FADED
+ self.sender.get ! MeetingCount(meetings)
+ }
- def complement(otherColour: Colour): Colour = colour match {
- case RED => otherColour match {
- case RED => RED
- case YELLOW => BLUE
- case BLUE => YELLOW
- case FADED => FADED
- }
- case YELLOW => otherColour match {
- case RED => BLUE
- case YELLOW => YELLOW
- case BLUE => RED
- case FADED => FADED
- }
- case BLUE => otherColour match {
- case RED => YELLOW
- case YELLOW => RED
- case BLUE => BLUE
- case FADED => FADED
- }
- case FADED => FADED
- }
+ def complement(otherColour: Colour): Colour = colour match {
+ case RED ⇒ otherColour match {
+ case RED ⇒ RED
+ case YELLOW ⇒ BLUE
+ case BLUE ⇒ YELLOW
+ case FADED ⇒ FADED
+ }
+ case YELLOW ⇒ otherColour match {
+ case RED ⇒ BLUE
+ case YELLOW ⇒ YELLOW
+ case BLUE ⇒ RED
+ case FADED ⇒ FADED
+ }
+ case BLUE ⇒ otherColour match {
+ case RED ⇒ YELLOW
+ case YELLOW ⇒ RED
+ case BLUE ⇒ BLUE
+ case FADED ⇒ FADED
+ }
+ case FADED ⇒ FADED
+ }
- override def toString = cid + "(" + colour + ")"
- }
+ override def toString = cid + "(" + colour + ")"
+ }
class Mall(var n: Int, numChameneos: Int) extends Actor {
var waitingChameneo: Option[ActorRef] = None
@@ -79,11 +79,11 @@ object Chameneos {
var numFaded = 0
override def preStart() = {
- for (i <- 0 until numChameneos) actorOf(new Chameneo(self, colours(i % 3), i))
+ for (i ← 0 until numChameneos) actorOf(new Chameneo(self, colours(i % 3), i))
}
def receive = {
- case MeetingCount(i) =>
+ case MeetingCount(i) ⇒
numFaded += 1
sumMeetings += i
if (numFaded == numChameneos) {
@@ -91,14 +91,14 @@ object Chameneos {
self.stop()
}
- case msg @ Meet(a, c) =>
+ case msg@Meet(a, c) ⇒
if (n > 0) {
waitingChameneo match {
- case Some(chameneo) =>
+ case Some(chameneo) ⇒
n -= 1
chameneo ! msg
waitingChameneo = None
- case None => waitingChameneo = self.sender
+ case None ⇒ waitingChameneo = self.sender
}
} else {
waitingChameneo.foreach(_ ! Exit)
@@ -108,12 +108,12 @@ object Chameneos {
}
def run {
-// System.setProperty("akka.config", "akka.conf")
- Chameneos.start = System.currentTimeMillis
+ // System.setProperty("akka.config", "akka.conf")
+ Chameneos.start = System.currentTimeMillis
actorOf(new Mall(1000000, 4)).start()
Thread.sleep(10000)
println("Elapsed: " + (end - start))
}
- def main(args : Array[String]): Unit = run
+ def main(args: Array[String]): Unit = run
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/actor/DeployerSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/actor/DeployerSpec.scala
index 97bed65628..9cd00f976a 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/actor/DeployerSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/actor/DeployerSpec.scala
@@ -13,16 +13,16 @@ class DeployerSpec extends WordSpec with MustMatchers {
"A Deployer" must {
"be able to parse 'akka.actor.deployment._' config elements" in {
val deployment = Deployer.lookupInConfig("service-pi")
- deployment must be ('defined)
- deployment must equal (Some(
+ deployment must be('defined)
+ deployment must equal(Some(
Deploy(
"service-pi",
RoundRobin,
"akka.serialization.Format$Default$",
Clustered(
- Node("test-1"),
- Replicate(3),
- Stateless))))
+ Node("test-1"),
+ Replicate(3),
+ Stateless))))
}
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/actor/FSMActorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/actor/FSMActorSpec.scala
index 9489c1e64f..8e97f05500 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/actor/FSMActorSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/actor/FSMActorSpec.scala
@@ -13,7 +13,6 @@ import FSM._
import akka.util.Duration
import akka.util.duration._
-
object FSMActorSpec {
val unlockedLatch = TestLatch()
@@ -31,52 +30,52 @@ object FSMActorSpec {
class Lock(code: String, timeout: Duration) extends Actor with FSM[LockState, CodeState] {
startWith(Locked, CodeState("", code))
-
+
when(Locked) {
- case Event(digit: Char, CodeState(soFar, code)) => {
+ case Event(digit: Char, CodeState(soFar, code)) ⇒ {
soFar + digit match {
- case incomplete if incomplete.length < code.length =>
+ case incomplete if incomplete.length < code.length ⇒
stay using CodeState(incomplete, code)
- case codeTry if (codeTry == code) => {
+ case codeTry if (codeTry == code) ⇒ {
doUnlock
goto(Open) using CodeState("", code) forMax timeout
}
- case wrong => {
+ case wrong ⇒ {
stay using CodeState("", code)
}
}
}
- case Event("hello", _) => stay replying "world"
- case Event("bye", _) => stop(Shutdown)
+ case Event("hello", _) ⇒ stay replying "world"
+ case Event("bye", _) ⇒ stop(Shutdown)
}
when(Open) {
- case Event(StateTimeout, _) => {
+ case Event(StateTimeout, _) ⇒ {
doLock
goto(Locked)
}
}
whenUnhandled {
- case Event(_, stateData) => {
+ case Event(_, stateData) ⇒ {
unhandledLatch.open
stay
}
}
onTransition {
- case Locked -> Open => transitionLatch.open
+ case Locked -> Open ⇒ transitionLatch.open
}
// verify that old-style does still compile
- onTransition (transitionHandler _)
+ onTransition(transitionHandler _)
def transitionHandler(from: LockState, to: LockState) = {
// dummy
}
onTermination {
- case StopEvent(Shutdown, Locked, _) =>
+ case StopEvent(Shutdown, Locked, _) ⇒
// stop is called from lockstate with shutdown as reason...
terminatedLatch.open
}
@@ -102,14 +101,16 @@ class FSMActorSpec extends WordSpec with MustMatchers {
"An FSM Actor" must {
"unlock the lock" in {
-
+
// lock that locked after being open for 1 sec
val lock = Actor.actorOf(new Lock("33221", 1 second)).start()
- val transitionTester = Actor.actorOf(new Actor { def receive = {
- case Transition(_, _, _) => transitionCallBackLatch.open
- case CurrentState(_, Locked) => initialStateLatch.open
- }}).start()
+ val transitionTester = Actor.actorOf(new Actor {
+ def receive = {
+ case Transition(_, _, _) ⇒ transitionCallBackLatch.open
+ case CurrentState(_, Locked) ⇒ initialStateLatch.open
+ }
+ }).start()
lock ! SubscribeTransitionCallBack(transitionTester)
initialStateLatch.await
@@ -133,9 +134,9 @@ class FSMActorSpec extends WordSpec with MustMatchers {
object Bye
val tester = Actor.actorOf(new Actor {
protected def receive = {
- case Hello => lock ! "hello"
- case "world" => answerLatch.open
- case Bye => lock ! "bye"
+ case Hello ⇒ lock ! "hello"
+ case "world" ⇒ answerLatch.open
+ case Bye ⇒ lock ! "bye"
}
}).start()
tester ! Hello
diff --git a/akka-actor-tests/src/test/scala/akka/actor/actor/FSMTimingSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/actor/FSMTimingSpec.scala
index 158bd3f0ee..3a61015f13 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/actor/FSMTimingSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/actor/FSMTimingSpec.scala
@@ -7,7 +7,6 @@ import akka.testkit.TestKit
import akka.util.Duration
import akka.util.duration._
-
class FSMTimingSpec extends WordSpec with MustMatchers with TestKit {
import FSMTimingSpec._
import FSM._
@@ -17,13 +16,13 @@ class FSMTimingSpec extends WordSpec with MustMatchers with TestKit {
expectMsg(200 millis, CurrentState(fsm, Initial))
ignoreMsg {
- case Transition(_, Initial, _) => true
+ case Transition(_, Initial, _) ⇒ true
}
"A Finite State Machine" must {
"receive StateTimeout" in {
- within (50 millis, 150 millis) {
+ within(50 millis, 150 millis) {
fsm ! TestStateTimeout
expectMsg(Transition(fsm, TestStateTimeout, Initial))
expectNoMsg
@@ -31,11 +30,11 @@ class FSMTimingSpec extends WordSpec with MustMatchers with TestKit {
}
"allow StateTimeout override" in {
- within (500 millis) {
+ within(500 millis) {
fsm ! TestStateTimeoutOverride
expectNoMsg
}
- within (50 millis) {
+ within(50 millis) {
fsm ! Cancel
expectMsg(Cancel)
expectMsg(Transition(fsm, TestStateTimeout, Initial))
@@ -43,7 +42,7 @@ class FSMTimingSpec extends WordSpec with MustMatchers with TestKit {
}
"receive single-shot timer" in {
- within (50 millis, 150 millis) {
+ within(50 millis, 150 millis) {
fsm ! TestSingleTimer
expectMsg(Tick)
expectMsg(Transition(fsm, TestSingleTimer, Initial))
@@ -54,7 +53,7 @@ class FSMTimingSpec extends WordSpec with MustMatchers with TestKit {
"receive and cancel a repeated timer" in {
fsm ! TestRepeatedTimer
val seq = receiveWhile(600 millis) {
- case Tick => Tick
+ case Tick ⇒ Tick
}
seq must have length (5)
within(250 millis) {
@@ -103,34 +102,34 @@ object FSMTimingSpec {
case object Cancel
case object SetHandler
- case class Unhandled(msg : AnyRef)
+ case class Unhandled(msg: AnyRef)
- class StateMachine(tester : ActorRef) extends Actor with FSM[State, Int] {
+ class StateMachine(tester: ActorRef) extends Actor with FSM[State, Int] {
import FSM._
startWith(Initial, 0)
when(Initial) {
- case Ev(TestSingleTimer) =>
+ case Ev(TestSingleTimer) ⇒
setTimer("tester", Tick, 100 millis, false)
goto(TestSingleTimer)
- case Ev(TestRepeatedTimer) =>
+ case Ev(TestRepeatedTimer) ⇒
setTimer("tester", Tick, 100 millis, true)
goto(TestRepeatedTimer) using 4
- case Ev(TestStateTimeoutOverride) =>
+ case Ev(TestStateTimeoutOverride) ⇒
goto(TestStateTimeout) forMax (Duration.Inf)
- case Ev(x : FSMTimingSpec.State) => goto(x)
+ case Ev(x: FSMTimingSpec.State) ⇒ goto(x)
}
when(TestStateTimeout, stateTimeout = 100 millis) {
- case Ev(StateTimeout) => goto(Initial)
- case Ev(Cancel) => goto(Initial) replying (Cancel)
+ case Ev(StateTimeout) ⇒ goto(Initial)
+ case Ev(Cancel) ⇒ goto(Initial) replying (Cancel)
}
when(TestSingleTimer) {
- case Ev(Tick) =>
+ case Ev(Tick) ⇒
tester ! Tick
goto(Initial)
}
when(TestRepeatedTimer) {
- case Event(Tick, remaining) =>
+ case Event(Tick, remaining) ⇒
tester ! Tick
if (remaining == 0) {
cancelTimer("tester")
@@ -140,14 +139,14 @@ object FSMTimingSpec {
}
}
when(TestUnhandled) {
- case Ev(SetHandler) =>
+ case Ev(SetHandler) ⇒
whenUnhandled {
- case Ev(Tick) =>
+ case Ev(Tick) ⇒
tester ! Unhandled(Tick)
stay
}
stay
- case Ev(Cancel) =>
+ case Ev(Cancel) ⇒
goto(Initial)
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/actor/FSMTransitionSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/actor/FSMTransitionSpec.scala
index fd0485a116..a2a258a11a 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/actor/FSMTransitionSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/actor/FSMTransitionSpec.scala
@@ -14,26 +14,26 @@ object FSMTransitionSpec {
class Supervisor extends Actor {
self.faultHandler = OneForOneStrategy(List(classOf[Throwable]), None, None)
- def receive = { case _ => }
+ def receive = { case _ ⇒ }
}
- class MyFSM(target : ActorRef) extends Actor with FSM[Int, Unit] {
+ class MyFSM(target: ActorRef) extends Actor with FSM[Int, Unit] {
startWith(0, Unit)
when(0) {
- case Ev("tick") => goto(1)
+ case Ev("tick") ⇒ goto(1)
}
when(1) {
- case Ev("tick") => goto(0)
+ case Ev("tick") ⇒ goto(0)
}
whenUnhandled {
- case Ev("reply") => stay replying "reply"
+ case Ev("reply") ⇒ stay replying "reply"
}
initialize
- override def preRestart(reason : Throwable) { target ! "restarted" }
+ override def preRestart(reason: Throwable) { target ! "restarted" }
}
- class Forwarder(target : ActorRef) extends Actor {
- def receive = { case x => target ! x }
+ class Forwarder(target: ActorRef) extends Actor {
+ def receive = { case x ⇒ target ! x }
}
}
@@ -41,7 +41,7 @@ object FSMTransitionSpec {
class FSMTransitionSpec extends WordSpec with MustMatchers with TestKit {
import FSMTransitionSpec._
-
+
"A FSM transition notifier" must {
"notify listeners" in {
diff --git a/akka-actor-tests/src/test/scala/akka/actor/actor/ForwardActorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/actor/ForwardActorSpec.scala
index 29d9fc5e10..2c6773bc1c 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/actor/ForwardActorSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/actor/ForwardActorSpec.scala
@@ -12,7 +12,6 @@ import akka.util.duration._
import Actor._
-
object ForwardActorSpec {
object ForwardState {
var sender: Option[ActorRef] = None
@@ -21,21 +20,20 @@ object ForwardActorSpec {
class ReceiverActor extends Actor {
val latch = TestLatch()
def receive = {
- case "SendBang" => {
+ case "SendBang" ⇒ {
ForwardState.sender = self.sender
latch.countDown()
}
- case "SendBangBang" => self.reply("SendBangBang")
+ case "SendBangBang" ⇒ self.reply("SendBangBang")
}
}
-
class ForwardActor extends Actor {
val receiverActor = actorOf[ReceiverActor]
receiverActor.start()
def receive = {
- case "SendBang" => receiverActor.forward("SendBang")
- case "SendBangBang" => receiverActor.forward("SendBangBang")
+ case "SendBang" ⇒ receiverActor.forward("SendBang")
+ case "SendBangBang" ⇒ receiverActor.forward("SendBangBang")
}
}
@@ -44,7 +42,7 @@ object ForwardActorSpec {
forwardActor.start()
forwardActor ! "SendBang"
def receive = {
- case _ => {}
+ case _ ⇒ {}
}
}
@@ -53,11 +51,11 @@ object ForwardActorSpec {
val forwardActor = actorOf[ForwardActor]
forwardActor.start()
(forwardActor !! "SendBangBang") match {
- case Some(_) => latch.countDown()
- case None => {}
+ case Some(_) ⇒ latch.countDown()
+ case None ⇒ {}
}
def receive = {
- case _ => {}
+ case _ ⇒ {}
}
}
}
@@ -69,13 +67,13 @@ class ForwardActorSpec extends WordSpec with MustMatchers {
"forward actor reference when invoking forward on bang" in {
val senderActor = actorOf[BangSenderActor]
val latch = senderActor.actor.asInstanceOf[BangSenderActor]
- .forwardActor.actor.asInstanceOf[ForwardActor]
- .receiverActor.actor.asInstanceOf[ReceiverActor]
- .latch
+ .forwardActor.actor.asInstanceOf[ForwardActor]
+ .receiverActor.actor.asInstanceOf[ReceiverActor]
+ .latch
senderActor.start()
latch.await
ForwardState.sender must not be (null)
- senderActor.toString must be (ForwardState.sender.get.toString)
+ senderActor.toString must be(ForwardState.sender.get.toString)
}
"forward actor reference when invoking forward on bang bang" in {
diff --git a/akka-actor-tests/src/test/scala/akka/actor/actor/HotSwapSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/actor/HotSwapSpec.scala
index 6cb1da93e8..2e5babcc34 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/actor/HotSwapSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/actor/HotSwapSpec.scala
@@ -11,37 +11,38 @@ import akka.testing._
import Actor._
-
class HotSwapSpec extends WordSpec with MustMatchers {
"An Actor" must {
"be able to hotswap its behavior with HotSwap(..)" in {
val barrier = TestBarrier(2)
- @volatile var _log = ""
- val a = actorOf( new Actor {
- def receive = { case _ => _log += "default" }
+ @volatile
+ var _log = ""
+ val a = actorOf(new Actor {
+ def receive = { case _ ⇒ _log += "default" }
}).start()
- a ! HotSwap( self => {
- case _ =>
+ a ! HotSwap(self ⇒ {
+ case _ ⇒
_log += "swapped"
barrier.await
})
a ! "swapped"
barrier.await
- _log must be ("swapped")
+ _log must be("swapped")
}
"be able to hotswap its behavior with become(..)" in {
val barrier = TestBarrier(2)
- @volatile var _log = ""
+ @volatile
+ var _log = ""
val a = actorOf(new Actor {
def receive = {
- case "init" =>
+ case "init" ⇒
_log += "init"
barrier.await
- case "swap" => become({
- case _ =>
+ case "swap" ⇒ become({
+ case _ ⇒
_log += "swapped"
barrier.await
})
@@ -50,42 +51,43 @@ class HotSwapSpec extends WordSpec with MustMatchers {
a ! "init"
barrier.await
- _log must be ("init")
+ _log must be("init")
barrier.reset
_log = ""
a ! "swap"
a ! "swapped"
barrier.await
- _log must be ("swapped")
+ _log must be("swapped")
}
"be able to revert hotswap its behavior with RevertHotSwap(..)" in {
val barrier = TestBarrier(2)
- @volatile var _log = ""
- val a = actorOf( new Actor {
+ @volatile
+ var _log = ""
+ val a = actorOf(new Actor {
def receive = {
- case "init" =>
+ case "init" ⇒
_log += "init"
barrier.await
- }
+ }
}).start()
a ! "init"
barrier.await
- _log must be ("init")
+ _log must be("init")
barrier.reset
_log = ""
- a ! HotSwap(self => {
- case "swapped" =>
+ a ! HotSwap(self ⇒ {
+ case "swapped" ⇒
_log += "swapped"
barrier.await
})
a ! "swapped"
barrier.await
- _log must be ("swapped")
+ _log must be("swapped")
barrier.reset
_log = ""
@@ -93,7 +95,7 @@ class HotSwapSpec extends WordSpec with MustMatchers {
a ! "init"
barrier.await
- _log must be ("init")
+ _log must be("init")
// try to revert hotswap below the bottom of the stack
barrier.reset
@@ -102,23 +104,24 @@ class HotSwapSpec extends WordSpec with MustMatchers {
a ! "init"
barrier.await
- _log must be ("init")
+ _log must be("init")
}
"be able to revert hotswap its behavior with unbecome" in {
val barrier = TestBarrier(2)
- @volatile var _log = ""
+ @volatile
+ var _log = ""
val a = actorOf(new Actor {
def receive = {
- case "init" =>
+ case "init" ⇒
_log += "init"
barrier.await
- case "swap" =>
+ case "swap" ⇒
become({
- case "swapped" =>
+ case "swapped" ⇒
_log += "swapped"
barrier.await
- case "revert" =>
+ case "revert" ⇒
unbecome()
})
barrier.await
@@ -127,7 +130,7 @@ class HotSwapSpec extends WordSpec with MustMatchers {
a ! "init"
barrier.await
- _log must be ("init")
+ _log must be("init")
barrier.reset
_log = ""
@@ -138,14 +141,14 @@ class HotSwapSpec extends WordSpec with MustMatchers {
_log = ""
a ! "swapped"
barrier.await
- _log must be ("swapped")
+ _log must be("swapped")
barrier.reset
_log = ""
a ! "revert"
a ! "init"
barrier.await
- _log must be ("init")
+ _log must be("init")
}
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/actor/ReceiveTimeoutSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/actor/ReceiveTimeoutSpec.scala
index 00298e10c0..491d37a6a3 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/actor/ReceiveTimeoutSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/actor/ReceiveTimeoutSpec.scala
@@ -13,7 +13,6 @@ import akka.util.duration._
import Actor._
import java.util.concurrent.atomic.AtomicInteger
-
class ReceiveTimeoutSpec extends WordSpec with MustMatchers {
import Actor._
@@ -26,7 +25,7 @@ class ReceiveTimeoutSpec extends WordSpec with MustMatchers {
self.receiveTimeout = Some(500L)
protected def receive = {
- case ReceiveTimeout => timeoutLatch.open
+ case ReceiveTimeout ⇒ timeoutLatch.open
}
}).start()
@@ -41,7 +40,7 @@ class ReceiveTimeoutSpec extends WordSpec with MustMatchers {
self.receiveTimeout = Some(500L)
protected def receive = {
- case ReceiveTimeout => timeoutLatch.open
+ case ReceiveTimeout ⇒ timeoutLatch.open
}
}).start()
@@ -49,14 +48,14 @@ class ReceiveTimeoutSpec extends WordSpec with MustMatchers {
val swappedLatch = TestLatch()
- timeoutActor ! HotSwap(self => {
- case ReceiveTimeout => swappedLatch.open
- })
+ timeoutActor ! HotSwap(self ⇒ {
+ case ReceiveTimeout ⇒ swappedLatch.open
+ })
swappedLatch.await
timeoutActor.stop()
}
-
+
"reschedule timeout after regular receive" in {
val timeoutLatch = TestLatch()
case object Tick
@@ -65,8 +64,8 @@ class ReceiveTimeoutSpec extends WordSpec with MustMatchers {
self.receiveTimeout = Some(500L)
protected def receive = {
- case Tick => ()
- case ReceiveTimeout => timeoutLatch.open
+ case Tick ⇒ ()
+ case ReceiveTimeout ⇒ timeoutLatch.open
}
}).start()
@@ -85,8 +84,8 @@ class ReceiveTimeoutSpec extends WordSpec with MustMatchers {
self.receiveTimeout = Some(500L)
protected def receive = {
- case Tick => ()
- case ReceiveTimeout =>
+ case Tick ⇒ ()
+ case ReceiveTimeout ⇒
count.incrementAndGet
timeoutLatch.open
self.receiveTimeout = None
@@ -96,7 +95,7 @@ class ReceiveTimeoutSpec extends WordSpec with MustMatchers {
timeoutActor ! Tick
timeoutLatch.await
- count.get must be (1)
+ count.get must be(1)
timeoutActor.stop()
}
@@ -105,7 +104,7 @@ class ReceiveTimeoutSpec extends WordSpec with MustMatchers {
val timeoutActor = actorOf(new Actor {
protected def receive = {
- case ReceiveTimeout => timeoutLatch.open
+ case ReceiveTimeout ⇒ timeoutLatch.open
}
}).start()
diff --git a/akka-actor-tests/src/test/scala/akka/actor/supervisor/RestartStrategySpec.scala b/akka-actor-tests/src/test/scala/akka/actor/supervisor/RestartStrategySpec.scala
index c2af94ba1a..0823369c20 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/supervisor/RestartStrategySpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/supervisor/RestartStrategySpec.scala
@@ -10,8 +10,8 @@ import org.scalatest.junit.JUnitSuite
import org.junit.Test
import Actor._
-import java.util.concurrent.{TimeUnit, CountDownLatch}
-import akka.config.Supervision.{Permanent, LifeCycle, OneForOneStrategy}
+import java.util.concurrent.{ TimeUnit, CountDownLatch }
+import akka.config.Supervision.{ Permanent, LifeCycle, OneForOneStrategy }
import org.multiverse.api.latches.StandardLatch
class RestartStrategySpec extends JUnitSuite {
@@ -22,9 +22,9 @@ class RestartStrategySpec extends JUnitSuite {
@Test
def slaveShouldStayDeadAfterMaxRestartsWithinTimeRange = {
- val boss = actorOf(new Actor{
+ val boss = actorOf(new Actor {
self.faultHandler = OneForOneStrategy(List(classOf[Throwable]), Some(2), Some(1000))
- protected def receive = { case _ => () }
+ protected def receive = { case _ ⇒ () }
}).start()
val restartLatch = new StandardLatch
@@ -32,12 +32,11 @@ class RestartStrategySpec extends JUnitSuite {
val countDownLatch = new CountDownLatch(3)
val stopLatch = new StandardLatch
-
- val slave = actorOf(new Actor{
+ val slave = actorOf(new Actor {
protected def receive = {
- case Ping => countDownLatch.countDown()
- case Crash => throw new Exception("Crashing...")
+ case Ping ⇒ countDownLatch.countDown()
+ case Crash ⇒ throw new Exception("Crashing...")
}
override def postRestart(reason: Throwable) = {
if (!restartLatch.isOpen)
@@ -77,17 +76,17 @@ class RestartStrategySpec extends JUnitSuite {
@Test
def slaveShouldBeImmortalWithoutMaxRestartsAndTimeRange = {
- val boss = actorOf(new Actor{
+ val boss = actorOf(new Actor {
self.faultHandler = OneForOneStrategy(List(classOf[Throwable]), None, None)
- protected def receive = { case _ => () }
+ protected def receive = { case _ ⇒ () }
}).start()
val countDownLatch = new CountDownLatch(100)
- val slave = actorOf(new Actor{
+ val slave = actorOf(new Actor {
protected def receive = {
- case Crash => throw new Exception("Crashing...")
+ case Crash ⇒ throw new Exception("Crashing...")
}
override def postRestart(reason: Throwable) = {
@@ -96,7 +95,7 @@ class RestartStrategySpec extends JUnitSuite {
})
boss.startLink(slave)
- (1 to 100) foreach { _ => slave ! Crash }
+ (1 to 100) foreach { _ ⇒ slave ! Crash }
assert(countDownLatch.await(120, TimeUnit.SECONDS))
assert(slave.isRunning)
}
@@ -104,9 +103,9 @@ class RestartStrategySpec extends JUnitSuite {
@Test
def slaveShouldRestartAfterNumberOfCrashesNotWithinTimeRange = {
- val boss = actorOf(new Actor{
+ val boss = actorOf(new Actor {
self.faultHandler = OneForOneStrategy(List(classOf[Throwable]), Some(2), Some(500))
- protected def receive = { case _ => () }
+ protected def receive = { case _ ⇒ () }
}).start()
val restartLatch = new StandardLatch
@@ -115,12 +114,12 @@ class RestartStrategySpec extends JUnitSuite {
val pingLatch = new StandardLatch
val secondPingLatch = new StandardLatch
- val slave = actorOf(new Actor{
+ val slave = actorOf(new Actor {
protected def receive = {
- case Ping =>
+ case Ping ⇒
if (!pingLatch.isOpen) pingLatch.open else secondPingLatch.open
- case Crash => throw new Exception("Crashing...")
+ case Crash ⇒ throw new Exception("Crashing...")
}
override def postRestart(reason: Throwable) = {
if (!restartLatch.isOpen)
@@ -165,9 +164,9 @@ class RestartStrategySpec extends JUnitSuite {
@Test
def slaveShouldNotRestartAfterMaxRetries = {
- val boss = actorOf(new Actor{
+ val boss = actorOf(new Actor {
self.faultHandler = OneForOneStrategy(List(classOf[Throwable]), Some(2), None)
- protected def receive = { case _ => () }
+ protected def receive = { case _ ⇒ () }
}).start()
val restartLatch = new StandardLatch
@@ -175,12 +174,11 @@ class RestartStrategySpec extends JUnitSuite {
val countDownLatch = new CountDownLatch(3)
val stopLatch = new StandardLatch
-
- val slave = actorOf(new Actor{
+ val slave = actorOf(new Actor {
protected def receive = {
- case Ping => countDownLatch.countDown()
- case Crash => throw new Exception("Crashing...")
+ case Ping ⇒ countDownLatch.countDown()
+ case Crash ⇒ throw new Exception("Crashing...")
}
override def postRestart(reason: Throwable) = {
if (!restartLatch.isOpen)
@@ -222,21 +220,21 @@ class RestartStrategySpec extends JUnitSuite {
@Test
def slaveShouldNotRestartWithinsTimeRange = {
- val restartLatch,stopLatch,maxNoOfRestartsLatch = new StandardLatch
+ val restartLatch, stopLatch, maxNoOfRestartsLatch = new StandardLatch
val countDownLatch = new CountDownLatch(2)
- val boss = actorOf(new Actor{
+ val boss = actorOf(new Actor {
self.faultHandler = OneForOneStrategy(List(classOf[Throwable]), None, Some(1000))
protected def receive = {
- case m:MaximumNumberOfRestartsWithinTimeRangeReached => maxNoOfRestartsLatch.open
+ case m: MaximumNumberOfRestartsWithinTimeRangeReached ⇒ maxNoOfRestartsLatch.open
}
}).start()
- val slave = actorOf(new Actor{
+ val slave = actorOf(new Actor {
protected def receive = {
- case Ping => countDownLatch.countDown()
- case Crash => throw new Exception("Crashing...")
+ case Ping ⇒ countDownLatch.countDown()
+ case Crash ⇒ throw new Exception("Crashing...")
}
override def postRestart(reason: Throwable) = {
@@ -265,7 +263,7 @@ class RestartStrategySpec extends JUnitSuite {
try {
slave ! Ping
} catch {
- case e: ActorInitializationException => ()
+ case e: ActorInitializationException ⇒ ()
}
assert(countDownLatch.await(1, TimeUnit.SECONDS))
@@ -274,12 +272,12 @@ class RestartStrategySpec extends JUnitSuite {
try {
slave ! Crash
} catch {
- case e: ActorInitializationException => ()
+ case e: ActorInitializationException ⇒ ()
}
assert(stopLatch.tryAwait(1, TimeUnit.SECONDS))
- assert(maxNoOfRestartsLatch.tryAwait(1,TimeUnit.SECONDS))
+ assert(maxNoOfRestartsLatch.tryAwait(1, TimeUnit.SECONDS))
assert(!slave.isRunning)
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorHierarchySpec.scala b/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorHierarchySpec.scala
index 529d2ef208..c0cf6a554c 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorHierarchySpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorHierarchySpec.scala
@@ -10,18 +10,18 @@ import org.junit.Test
import Actor._
import akka.config.Supervision.OneForOneStrategy
-import java.util.concurrent.{TimeUnit, CountDownLatch}
+import java.util.concurrent.{ TimeUnit, CountDownLatch }
object SupervisorHierarchySpec {
class FireWorkerException(msg: String) extends Exception(msg)
class CountDownActor(countDown: CountDownLatch) extends Actor {
- protected def receive = { case _ => () }
+ protected def receive = { case _ ⇒ () }
override def postRestart(reason: Throwable) = countDown.countDown()
}
class CrasherActor extends Actor {
- protected def receive = { case _ => () }
+ protected def receive = { case _ ⇒ () }
}
}
@@ -36,10 +36,10 @@ class SupervisorHierarchySpec extends JUnitSuite {
val workerTwo = actorOf(new CountDownActor(countDown))
val workerThree = actorOf(new CountDownActor(countDown))
- val boss = actorOf(new Actor{
+ val boss = actorOf(new Actor {
self.faultHandler = OneForOneStrategy(List(classOf[Throwable]), 5, 1000)
- protected def receive = { case _ => () }
+ protected def receive = { case _ ⇒ () }
}).start()
val manager = actorOf(new CountDownActor(countDown))
@@ -61,10 +61,10 @@ class SupervisorHierarchySpec extends JUnitSuite {
def supervisorShouldReceiveNotificationMessageWhenMaximumNumberOfRestartsWithinTimeRangeIsReached = {
val countDown = new CountDownLatch(2)
val crasher = actorOf(new CountDownActor(countDown))
- val boss = actorOf(new Actor{
+ val boss = actorOf(new Actor {
self.faultHandler = OneForOneStrategy(List(classOf[Throwable]), 1, 5000)
protected def receive = {
- case MaximumNumberOfRestartsWithinTimeRangeReached(_, _, _, _) =>
+ case MaximumNumberOfRestartsWithinTimeRangeReached(_, _, _, _) ⇒
countDown.countDown()
}
}).start()
diff --git a/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorMiscSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorMiscSpec.scala
index 5a812c3f8a..c81455b9e8 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorMiscSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorMiscSpec.scala
@@ -6,7 +6,7 @@ package akka.actor
import org.scalatest.WordSpec
import org.scalatest.matchers.MustMatchers
import akka.dispatch.Dispatchers
-import akka.config.Supervision.{SupervisorConfig, OneForOneStrategy, Supervise, Permanent}
+import akka.config.Supervision.{ SupervisorConfig, OneForOneStrategy, Supervise, Permanent }
import java.util.concurrent.CountDownLatch
class SupervisorMiscSpec extends WordSpec with MustMatchers {
@@ -17,52 +17,52 @@ class SupervisorMiscSpec extends WordSpec with MustMatchers {
val actor1 = Actor.actorOf(new Actor {
self.dispatcher = Dispatchers.newThreadBasedDispatcher(self)
- override def postRestart(cause: Throwable) {countDownLatch.countDown()}
+ override def postRestart(cause: Throwable) { countDownLatch.countDown() }
protected def receive = {
- case "kill" => throw new Exception("killed")
- case _ => println("received unknown message")
+ case "kill" ⇒ throw new Exception("killed")
+ case _ ⇒ println("received unknown message")
}
}).start()
val actor2 = Actor.actorOf(new Actor {
self.dispatcher = Dispatchers.newThreadBasedDispatcher(self)
- override def postRestart(cause: Throwable) {countDownLatch.countDown()}
+ override def postRestart(cause: Throwable) { countDownLatch.countDown() }
protected def receive = {
- case "kill" => throw new Exception("killed")
- case _ => println("received unknown message")
+ case "kill" ⇒ throw new Exception("killed")
+ case _ ⇒ println("received unknown message")
}
}).start()
val actor3 = Actor.actorOf(new Actor {
self.dispatcher = Dispatchers.newExecutorBasedEventDrivenDispatcher("test").build
- override def postRestart(cause: Throwable) {countDownLatch.countDown()}
+ override def postRestart(cause: Throwable) { countDownLatch.countDown() }
protected def receive = {
- case "kill" => throw new Exception("killed")
- case _ => println("received unknown message")
+ case "kill" ⇒ throw new Exception("killed")
+ case _ ⇒ println("received unknown message")
}
}).start()
val actor4 = Actor.actorOf(new Actor {
self.dispatcher = Dispatchers.newThreadBasedDispatcher(self)
- override def postRestart(cause: Throwable) {countDownLatch.countDown()}
+ override def postRestart(cause: Throwable) { countDownLatch.countDown() }
protected def receive = {
- case "kill" => throw new Exception("killed")
- case _ => println("received unknown message")
+ case "kill" ⇒ throw new Exception("killed")
+ case _ ⇒ println("received unknown message")
}
}).start()
val sup = Supervisor(
SupervisorConfig(
- OneForOneStrategy(List(classOf[Exception]),3, 5000),
+ OneForOneStrategy(List(classOf[Exception]), 3, 5000),
Supervise(actor1, Permanent) ::
- Supervise(actor2, Permanent) ::
- Supervise(actor3, Permanent) ::
- Supervise(actor4, Permanent) ::
- Nil))
+ Supervise(actor2, Permanent) ::
+ Supervise(actor3, Permanent) ::
+ Supervise(actor4, Permanent) ::
+ Nil))
actor1 ! "kill"
actor2 ! "kill"
diff --git a/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorSpec.scala
index 67b2a00c54..e2aa812e34 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorSpec.scala
@@ -9,16 +9,15 @@ import org.scalatest.matchers.MustMatchers
import org.scalatest.BeforeAndAfterEach
import akka.testing._
-import akka.testing.Testing.{testMillis, sleepFor}
+import akka.testing.Testing.{ testMillis, sleepFor }
import akka.util.duration._
import akka.config.Supervision._
-import akka.{Die, Ping}
+import akka.{ Die, Ping }
import Actor._
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.LinkedBlockingQueue
-
object SupervisorSpec {
val Timeout = 5 seconds
val TimeoutMillis = testMillis(Timeout).toInt
@@ -41,10 +40,10 @@ object SupervisorSpec {
class PingPongActor extends Actor {
def receive = {
- case Ping =>
+ case Ping ⇒
messageLog.put(PingMessage)
self.reply_?(PongMessage)
- case Die =>
+ case Die ⇒
throw new RuntimeException(ExceptionMessage)
}
@@ -67,7 +66,7 @@ object SupervisorSpec {
}
override def receive = {
- case Die => temp !! (Die, TimeoutMillis)
+ case Die ⇒ temp !! (Die, TimeoutMillis)
}
}
@@ -84,7 +83,7 @@ object SupervisorSpec {
Supervise(
temporaryActor,
Temporary)
- :: Nil))
+ :: Nil))
(temporaryActor, supervisor)
}
@@ -98,7 +97,7 @@ object SupervisorSpec {
Supervise(
pingpong,
Permanent)
- :: Nil))
+ :: Nil))
(pingpong, supervisor)
}
@@ -112,7 +111,7 @@ object SupervisorSpec {
Supervise(
pingpong,
Permanent)
- :: Nil))
+ :: Nil))
(pingpong, supervisor)
}
@@ -128,15 +127,15 @@ object SupervisorSpec {
Supervise(
pingpong1,
Permanent)
- ::
- Supervise(
- pingpong2,
- Permanent)
- ::
- Supervise(
- pingpong3,
- Permanent)
- :: Nil))
+ ::
+ Supervise(
+ pingpong2,
+ Permanent)
+ ::
+ Supervise(
+ pingpong3,
+ Permanent)
+ :: Nil))
(pingpong1, pingpong2, pingpong3, supervisor)
}
@@ -152,15 +151,15 @@ object SupervisorSpec {
Supervise(
pingpong1,
Permanent)
- ::
- Supervise(
- pingpong2,
- Permanent)
- ::
- Supervise(
- pingpong3,
- Permanent)
- :: Nil))
+ ::
+ Supervise(
+ pingpong2,
+ Permanent)
+ ::
+ Supervise(
+ pingpong3,
+ Permanent)
+ :: Nil))
(pingpong1, pingpong2, pingpong3, supervisor)
}
@@ -176,21 +175,21 @@ object SupervisorSpec {
Supervise(
pingpong1,
Permanent)
- ::
- SupervisorConfig(
- AllForOneStrategy(Nil, 3, TimeoutMillis),
- Supervise(
- pingpong2,
- Permanent)
::
- Supervise(
- pingpong3,
- Permanent)
- :: Nil)
- :: Nil))
+ SupervisorConfig(
+ AllForOneStrategy(Nil, 3, TimeoutMillis),
+ Supervise(
+ pingpong2,
+ Permanent)
+ ::
+ Supervise(
+ pingpong3,
+ Permanent)
+ :: Nil)
+ :: Nil))
(pingpong1, pingpong2, pingpong3, supervisor)
- }
+ }
}
class SupervisorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach {
@@ -201,13 +200,13 @@ class SupervisorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach
}
def ping(pingPongActor: ActorRef) = {
- (pingPongActor !! (Ping, TimeoutMillis)).getOrElse("nil") must be (PongMessage)
- messageLogPoll must be (PingMessage)
+ (pingPongActor !! (Ping, TimeoutMillis)).getOrElse("nil") must be(PongMessage)
+ messageLogPoll must be(PingMessage)
}
def kill(pingPongActor: ActorRef) = {
intercept[RuntimeException] { pingPongActor !! (Die, TimeoutMillis) }
- messageLogPoll must be (ExceptionMessage)
+ messageLogPoll must be(ExceptionMessage)
}
"A supervisor" must {
@@ -220,7 +219,7 @@ class SupervisorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach
}
sleepFor(1 second)
- messageLog.size must be (0)
+ messageLog.size must be(0)
}
"not restart temporary actor" in {
@@ -231,7 +230,7 @@ class SupervisorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach
}
sleepFor(1 second)
- messageLog.size must be (0)
+ messageLog.size must be(0)
}
"start server for nested supervisor hierarchy" in {
@@ -293,10 +292,10 @@ class SupervisorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach
kill(actor2)
// and two more exception messages
- messageLogPoll must be (ExceptionMessage)
- messageLogPoll must be (ExceptionMessage)
+ messageLogPoll must be(ExceptionMessage)
+ messageLogPoll must be(ExceptionMessage)
}
-
+
"call-kill-call multiple actors AllForOne" in {
val (actor1, actor2, actor3, supervisor) = multipleActorsAllForOne
@@ -307,8 +306,8 @@ class SupervisorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach
kill(actor2)
// and two more exception messages
- messageLogPoll must be (ExceptionMessage)
- messageLogPoll must be (ExceptionMessage)
+ messageLogPoll must be(ExceptionMessage)
+ messageLogPoll must be(ExceptionMessage)
ping(actor1)
ping(actor2)
@@ -319,22 +318,22 @@ class SupervisorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach
val (actor, supervisor) = singleActorOneForOne
actor ! Die
- messageLogPoll must be (ExceptionMessage)
+ messageLogPoll must be(ExceptionMessage)
}
"one-way call-kill-call single actor OneForOne" in {
val (actor, supervisor) = singleActorOneForOne
actor ! Ping
- messageLogPoll must be (PingMessage)
+ messageLogPoll must be(PingMessage)
actor ! Die
- messageLogPoll must be (ExceptionMessage)
+ messageLogPoll must be(ExceptionMessage)
actor ! Ping
- messageLogPoll must be (PingMessage)
+ messageLogPoll must be(PingMessage)
}
-
+
"restart killed actors in nested superviser hierarchy" in {
val (actor1, actor2, actor3, supervisor) = nestedSupervisorsAllForOne
@@ -345,8 +344,8 @@ class SupervisorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach
kill(actor2)
// and two more exception messages
- messageLogPoll must be (ExceptionMessage)
- messageLogPoll must be (ExceptionMessage)
+ messageLogPoll must be(ExceptionMessage)
+ messageLogPoll must be(ExceptionMessage)
ping(actor1)
ping(actor2)
@@ -363,8 +362,8 @@ class SupervisorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach
if (inits.get % 2 == 0) throw new IllegalStateException("Don't wanna!")
def receive = {
- case Ping => self.reply_?(PongMessage)
- case Die => throw new Exception("expected")
+ case Ping ⇒ self.reply_?(PongMessage)
+ case Die ⇒ throw new Exception("expected")
}
})
@@ -381,9 +380,9 @@ class SupervisorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach
// give time for restart
sleepFor(3 seconds)
- (dyingActor !! (Ping, TimeoutMillis)).getOrElse("nil") must be (PongMessage)
+ (dyingActor !! (Ping, TimeoutMillis)).getOrElse("nil") must be(PongMessage)
- inits.get must be (3)
+ inits.get must be(3)
supervisor.shutdown()
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorTreeSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorTreeSpec.scala
index 3b338c5195..f55f8940cf 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorTreeSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/supervisor/SupervisorTreeSpec.scala
@@ -9,7 +9,7 @@ import org.scalatest.matchers.MustMatchers
import akka.util.duration._
import akka.testing.Testing.sleepFor
import akka.dispatch.Dispatchers
-import akka.config.Supervision.{SupervisorConfig, OneForOneStrategy, Supervise, Permanent}
+import akka.config.Supervision.{ SupervisorConfig, OneForOneStrategy, Supervise, Permanent }
import Actor._
class SupervisorTreeSpec extends WordSpec with MustMatchers {
@@ -22,7 +22,7 @@ class SupervisorTreeSpec extends WordSpec with MustMatchers {
a.foreach(self.link(_))
def receive = {
- case Die => throw new Exception(self.address + " is dying...")
+ case Die ⇒ throw new Exception(self.address + " is dying...")
}
override def preRestart(reason: Throwable) {
@@ -35,13 +35,13 @@ class SupervisorTreeSpec extends WordSpec with MustMatchers {
"be able to kill the middle actor and see itself and its child restarted" in {
log = "INIT"
- val lastActor = actorOf(new Chainer, "lastActor").start
+ val lastActor = actorOf(new Chainer, "lastActor").start
val middleActor = actorOf(new Chainer(Some(lastActor)), "middleActor").start
- val headActor = actorOf(new Chainer(Some(middleActor)), "headActor").start
+ val headActor = actorOf(new Chainer(Some(middleActor)), "headActor").start
middleActor ! Die
sleepFor(500 millis)
- log must equal ("INITmiddleActorlastActor")
+ log must equal("INITmiddleActorlastActor")
}
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/supervisor/Ticket669Spec.scala b/akka-actor-tests/src/test/scala/akka/actor/supervisor/Ticket669Spec.scala
index 6ca1d2d7c9..0a70058c7b 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/supervisor/Ticket669Spec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/supervisor/Ticket669Spec.scala
@@ -3,12 +3,12 @@
*/
package akka.actor.supervisor
-import java.util.concurrent.{CountDownLatch, TimeUnit}
+import java.util.concurrent.{ CountDownLatch, TimeUnit }
import akka.actor._
import akka.config.Supervision._
-import org.scalatest.{BeforeAndAfterAll, WordSpec}
+import org.scalatest.{ BeforeAndAfterAll, WordSpec }
import org.scalatest.matchers.MustMatchers
class Ticket669Spec extends WordSpec with MustMatchers with BeforeAndAfterAll {
@@ -24,11 +24,10 @@ class Ticket669Spec extends WordSpec with MustMatchers with BeforeAndAfterAll {
val supervised = Actor.actorOf[Supervised]
val supervisor = Supervisor(SupervisorConfig(
AllForOneStrategy(List(classOf[Exception]), 5, 10000),
- Supervise(supervised, Permanent) :: Nil)
- )
+ Supervise(supervised, Permanent) :: Nil))
supervised.!("test")(Some(sender))
- latch.await(5, TimeUnit.SECONDS) must be (true)
+ latch.await(5, TimeUnit.SECONDS) must be(true)
}
"be able to reply on failure during postStop" in {
@@ -38,11 +37,10 @@ class Ticket669Spec extends WordSpec with MustMatchers with BeforeAndAfterAll {
val supervised = Actor.actorOf[Supervised]
val supervisor = Supervisor(SupervisorConfig(
AllForOneStrategy(List(classOf[Exception]), 5, 10000),
- Supervise(supervised, Temporary) :: Nil)
- )
+ Supervise(supervised, Temporary) :: Nil))
supervised.!("test")(Some(sender))
- latch.await(5, TimeUnit.SECONDS) must be (true)
+ latch.await(5, TimeUnit.SECONDS) must be(true)
}
}
}
@@ -50,15 +48,15 @@ class Ticket669Spec extends WordSpec with MustMatchers with BeforeAndAfterAll {
object Ticket669Spec {
class Sender(latch: CountDownLatch) extends Actor {
def receive = {
- case "failure1" => latch.countDown()
- case "failure2" => latch.countDown()
- case _ => { }
+ case "failure1" ⇒ latch.countDown()
+ case "failure2" ⇒ latch.countDown()
+ case _ ⇒ {}
}
}
class Supervised extends Actor {
def receive = {
- case msg => throw new Exception("test")
+ case msg ⇒ throw new Exception("test")
}
override def preRestart(reason: scala.Throwable) {
diff --git a/akka-actor-tests/src/test/scala/akka/dataflow/DataFlowSpec.scala b/akka-actor-tests/src/test/scala/akka/dataflow/DataFlowSpec.scala
index 412605c02b..6b6d8effb5 100644
--- a/akka-actor-tests/src/test/scala/akka/dataflow/DataFlowSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dataflow/DataFlowSpec.scala
@@ -12,64 +12,65 @@ import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import akka.dispatch.DefaultCompletableFuture
-import java.util.concurrent.{TimeUnit, CountDownLatch}
+import java.util.concurrent.{ TimeUnit, CountDownLatch }
import annotation.tailrec
-import java.util.concurrent.atomic.{AtomicLong, AtomicReference, AtomicInteger}
+import java.util.concurrent.atomic.{ AtomicLong, AtomicReference, AtomicInteger }
import akka.actor.ActorRegistry
@RunWith(classOf[JUnitRunner])
class DataFlowTest extends Spec with ShouldMatchers with BeforeAndAfterAll {
- describe("DataflowVariable") {
- it("should be able to set the value of one variable from other variables") {
- import DataFlow._
+ describe("DataflowVariable") {
+ it("should be able to set the value of one variable from other variables") {
+ import DataFlow._
- val latch = new CountDownLatch(1)
- val result = new AtomicInteger(0)
- val x, y, z = new DataFlowVariable[Int]
- thread {
- z << x() + y()
- result.set(z())
- latch.countDown()
- }
- thread { x << 40 }
- thread { y << 2 }
+ val latch = new CountDownLatch(1)
+ val result = new AtomicInteger(0)
+ val x, y, z = new DataFlowVariable[Int]
+ thread {
+ z << x() + y()
+ result.set(z())
+ latch.countDown()
+ }
+ thread { x << 40 }
+ thread { y << 2 }
- latch.await(10,TimeUnit.SECONDS) should equal (true)
- result.get should equal (42)
- List(x,y,z).foreach(_.shutdown())
+ latch.await(10, TimeUnit.SECONDS) should equal(true)
+ result.get should equal(42)
+ List(x, y, z).foreach(_.shutdown())
+ }
+
+ it("should be able to sum a sequence of ints") {
+ import DataFlow._
+
+ def ints(n: Int, max: Int): List[Int] =
+ if (n == max) Nil
+ else n :: ints(n + 1, max)
+
+ def sum(s: Int, stream: List[Int]): List[Int] = stream match {
+ case Nil ⇒ s :: Nil
+ case h :: t ⇒ s :: sum(h + s, t)
}
- it("should be able to sum a sequence of ints") {
- import DataFlow._
+ val latch = new CountDownLatch(1)
+ val result = new AtomicReference[List[Int]](Nil)
+ val x = new DataFlowVariable[List[Int]]
+ val y = new DataFlowVariable[List[Int]]
+ val z = new DataFlowVariable[List[Int]]
- def ints(n: Int, max: Int): List[Int] =
- if (n == max) Nil
- else n :: ints(n + 1, max)
+ thread { x << ints(0, 1000) }
+ thread { y << sum(0, x()) }
- def sum(s: Int, stream: List[Int]): List[Int] = stream match {
- case Nil => s :: Nil
- case h :: t => s :: sum(h + s, t)
- }
-
- val latch = new CountDownLatch(1)
- val result = new AtomicReference[List[Int]](Nil)
- val x = new DataFlowVariable[List[Int]]
- val y = new DataFlowVariable[List[Int]]
- val z = new DataFlowVariable[List[Int]]
-
- thread { x << ints(0, 1000) }
- thread { y << sum(0, x()) }
-
- thread { z << y()
- result.set(z())
- latch.countDown()
- }
-
- latch.await(10,TimeUnit.SECONDS) should equal (true)
- result.get should equal (sum(0,ints(0,1000)))
- List(x,y,z).foreach(_.shutdown())
+ thread {
+ z << y()
+ result.set(z())
+ latch.countDown()
}
-/*
+
+ latch.await(10, TimeUnit.SECONDS) should equal(true)
+ result.get should equal(sum(0, ints(0, 1000)))
+ List(x, y, z).foreach(_.shutdown())
+ }
+ /*
it("should be able to join streams") {
import DataFlow._
Actor.registry.shutdownAll()
@@ -135,8 +136,8 @@ class DataFlowTest extends Spec with ShouldMatchers with BeforeAndAfterAll {
latch.await(15,TimeUnit.SECONDS) should equal (true)
}
*/
- /* Test not ready for prime time, causes some sort of deadlock */
- /* it("should be able to conditionally set variables") {
+ /* Test not ready for prime time, causes some sort of deadlock */
+ /* it("should be able to conditionally set variables") {
import DataFlow._
Actor.registry.shutdownAll()
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ActorModelSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/ActorModelSpec.scala
index d5cea19bf5..c6af345d68 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/ActorModelSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/ActorModelSpec.scala
@@ -8,12 +8,12 @@ import org.junit.Test
import org.scalatest.Assertions._
import akka.testing._
import akka.dispatch._
-import akka.actor.{ActorRef, Actor}
+import akka.actor.{ ActorRef, Actor }
import akka.actor.Actor._
import java.util.concurrent.atomic.AtomicLong
-import java.util.concurrent. {ConcurrentHashMap, CountDownLatch, TimeUnit}
+import java.util.concurrent.{ ConcurrentHashMap, CountDownLatch, TimeUnit }
import akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor
-import akka.util.{Duration, Switch}
+import akka.util.{ Duration, Switch }
import org.multiverse.api.latches.StandardLatch
object ActorModelSpec {
@@ -21,7 +21,7 @@ object ActorModelSpec {
sealed trait ActorModelMessage
case class Reply_?(expect: Any) extends ActorModelMessage
case class Reply(expect: Any) extends ActorModelMessage
- case class Forward(to: ActorRef,msg: Any) extends ActorModelMessage
+ case class Forward(to: ActorRef, msg: Any) extends ActorModelMessage
case class CountDown(latch: CountDownLatch) extends ActorModelMessage
case class Increment(counter: AtomicLong) extends ActorModelMessage
case class Await(latch: CountDownLatch) extends ActorModelMessage
@@ -52,37 +52,37 @@ object ActorModelSpec {
}
def receive = {
- case Await(latch) => ack; latch.await(); busy.switchOff()
- case Meet(sign, wait) => ack; sign.countDown(); wait.await(); busy.switchOff()
- case Wait(time) => ack; Thread.sleep(time); busy.switchOff()
- case WaitAck(time, l) => ack; Thread.sleep(time); l.countDown(); busy.switchOff()
- case Reply(msg) => ack; self.reply(msg); busy.switchOff()
- case Reply_?(msg) => ack; self.reply_?(msg); busy.switchOff()
- case Forward(to,msg) => ack; to.forward(msg); busy.switchOff()
- case CountDown(latch) => ack; latch.countDown(); busy.switchOff()
- case Increment(count) => ack; count.incrementAndGet(); busy.switchOff()
- case CountDownNStop(l)=> ack; l.countDown(); self.stop(); busy.switchOff()
- case Restart => ack; busy.switchOff(); throw new Exception("Restart requested")
+ case Await(latch) ⇒ ack; latch.await(); busy.switchOff()
+ case Meet(sign, wait) ⇒ ack; sign.countDown(); wait.await(); busy.switchOff()
+ case Wait(time) ⇒ ack; Thread.sleep(time); busy.switchOff()
+ case WaitAck(time, l) ⇒ ack; Thread.sleep(time); l.countDown(); busy.switchOff()
+ case Reply(msg) ⇒ ack; self.reply(msg); busy.switchOff()
+ case Reply_?(msg) ⇒ ack; self.reply_?(msg); busy.switchOff()
+ case Forward(to, msg) ⇒ ack; to.forward(msg); busy.switchOff()
+ case CountDown(latch) ⇒ ack; latch.countDown(); busy.switchOff()
+ case Increment(count) ⇒ ack; count.incrementAndGet(); busy.switchOff()
+ case CountDownNStop(l) ⇒ ack; l.countDown(); self.stop(); busy.switchOff()
+ case Restart ⇒ ack; busy.switchOff(); throw new Exception("Restart requested")
}
}
class InterceptorStats {
- val suspensions = new AtomicLong(0)
- val resumes = new AtomicLong(0)
- val registers = new AtomicLong(0)
- val unregisters = new AtomicLong(0)
- val msgsReceived = new AtomicLong(0)
+ val suspensions = new AtomicLong(0)
+ val resumes = new AtomicLong(0)
+ val registers = new AtomicLong(0)
+ val unregisters = new AtomicLong(0)
+ val msgsReceived = new AtomicLong(0)
val msgsProcessed = new AtomicLong(0)
- val restarts = new AtomicLong(0)
+ val restarts = new AtomicLong(0)
}
trait MessageDispatcherInterceptor extends MessageDispatcher {
- val stats = new ConcurrentHashMap[ActorRef,InterceptorStats]
+ val stats = new ConcurrentHashMap[ActorRef, InterceptorStats]
val starts = new AtomicLong(0)
- val stops = new AtomicLong(0)
+ val stops = new AtomicLong(0)
def getStats(actorRef: ActorRef) = {
- stats.putIfAbsent(actorRef,new InterceptorStats)
+ stats.putIfAbsent(actorRef, new InterceptorStats)
stats.get(actorRef)
}
@@ -123,70 +123,67 @@ object ActorModelSpec {
}
def assertDispatcher(dispatcher: MessageDispatcherInterceptor)(
- starts: Long = dispatcher.starts.get(),
- stops: Long = dispatcher.stops.get()
- ) {
+ starts: Long = dispatcher.starts.get(),
+ stops: Long = dispatcher.stops.get()) {
assert(starts === dispatcher.starts.get(), "Dispatcher starts")
- assert(stops === dispatcher.stops.get(), "Dispatcher stops")
+ assert(stops === dispatcher.stops.get(), "Dispatcher stops")
}
- def assertCountDown(latch: CountDownLatch,wait: Long,hint: AnyRef){
- assert(latch.await(wait,TimeUnit.MILLISECONDS) === true)
+ def assertCountDown(latch: CountDownLatch, wait: Long, hint: AnyRef) {
+ assert(latch.await(wait, TimeUnit.MILLISECONDS) === true)
}
- def assertNoCountDown(latch: CountDownLatch,wait: Long,hint: AnyRef){
- assert(latch.await(wait,TimeUnit.MILLISECONDS) === false)
+ def assertNoCountDown(latch: CountDownLatch, wait: Long, hint: AnyRef) {
+ assert(latch.await(wait, TimeUnit.MILLISECONDS) === false)
}
def statsFor(actorRef: ActorRef, dispatcher: MessageDispatcher = null) =
dispatcher.asInstanceOf[MessageDispatcherInterceptor].getStats(actorRef)
- def assertRefDefaultZero(actorRef: ActorRef,dispatcher: MessageDispatcher = null)(
- suspensions: Long = 0,
- resumes: Long = 0,
- registers: Long = 0,
- unregisters: Long = 0,
- msgsReceived: Long = 0,
- msgsProcessed: Long = 0,
- restarts: Long = 0) {
- assertRef(actorRef,dispatcher)(
+ def assertRefDefaultZero(actorRef: ActorRef, dispatcher: MessageDispatcher = null)(
+ suspensions: Long = 0,
+ resumes: Long = 0,
+ registers: Long = 0,
+ unregisters: Long = 0,
+ msgsReceived: Long = 0,
+ msgsProcessed: Long = 0,
+ restarts: Long = 0) {
+ assertRef(actorRef, dispatcher)(
suspensions,
resumes,
registers,
unregisters,
msgsReceived,
msgsProcessed,
- restarts
- )
+ restarts)
}
- def assertRef(actorRef: ActorRef,dispatcher: MessageDispatcher = null)(
- suspensions: Long = statsFor(actorRef).suspensions.get(),
- resumes: Long = statsFor(actorRef).resumes.get(),
- registers: Long = statsFor(actorRef).registers.get(),
- unregisters: Long = statsFor(actorRef).unregisters.get(),
- msgsReceived: Long = statsFor(actorRef).msgsReceived.get(),
- msgsProcessed: Long = statsFor(actorRef).msgsProcessed.get(),
- restarts: Long = statsFor(actorRef).restarts.get()
- ) {
- val stats = statsFor(actorRef,if (dispatcher eq null) actorRef.dispatcher else dispatcher)
- assert(stats.suspensions.get() === suspensions, "Suspensions")
- assert(stats.resumes.get() === resumes, "Resumes")
- assert(stats.registers.get() === registers, "Registers")
- assert(stats.unregisters.get() === unregisters, "Unregisters")
- assert(stats.msgsReceived.get() === msgsReceived, "Received")
+ def assertRef(actorRef: ActorRef, dispatcher: MessageDispatcher = null)(
+ suspensions: Long = statsFor(actorRef).suspensions.get(),
+ resumes: Long = statsFor(actorRef).resumes.get(),
+ registers: Long = statsFor(actorRef).registers.get(),
+ unregisters: Long = statsFor(actorRef).unregisters.get(),
+ msgsReceived: Long = statsFor(actorRef).msgsReceived.get(),
+ msgsProcessed: Long = statsFor(actorRef).msgsProcessed.get(),
+ restarts: Long = statsFor(actorRef).restarts.get()) {
+ val stats = statsFor(actorRef, if (dispatcher eq null) actorRef.dispatcher else dispatcher)
+ assert(stats.suspensions.get() === suspensions, "Suspensions")
+ assert(stats.resumes.get() === resumes, "Resumes")
+ assert(stats.registers.get() === registers, "Registers")
+ assert(stats.unregisters.get() === unregisters, "Unregisters")
+ assert(stats.msgsReceived.get() === msgsReceived, "Received")
assert(stats.msgsProcessed.get() === msgsProcessed, "Processed")
- assert(stats.restarts.get() === restarts, "Restarts")
+ assert(stats.restarts.get() === restarts, "Restarts")
}
- def await(condition: => Boolean)(withinMs: Long, intervalMs: Long = 25): Boolean = try {
+ def await(condition: ⇒ Boolean)(withinMs: Long, intervalMs: Long = 25): Boolean = try {
val until = System.currentTimeMillis() + withinMs
- while(System.currentTimeMillis() <= until) {
+ while (System.currentTimeMillis() <= until) {
try {
if (condition) return true
Thread.sleep(intervalMs)
- } catch { case e: InterruptedException => }
+ } catch { case e: InterruptedException ⇒ }
}
false
}
@@ -199,7 +196,8 @@ abstract class ActorModelSpec extends JUnitSuite {
protected def newInterceptedDispatcher: MessageDispatcherInterceptor
- @Test def dispatcherShouldDynamicallyHandleItsOwnLifeCycle {
+ @Test
+ def dispatcherShouldDynamicallyHandleItsOwnLifeCycle {
implicit val dispatcher = newInterceptedDispatcher
val a = newTestActor
assertDispatcher(dispatcher)(starts = 0, stops = 0)
@@ -208,23 +206,22 @@ abstract class ActorModelSpec extends JUnitSuite {
a.stop()
await(dispatcher.stops.get == 1)(withinMs = dispatcher.timeoutMs * 5)
assertDispatcher(dispatcher)(starts = 1, stops = 1)
- assertRef(a,dispatcher)(
+ assertRef(a, dispatcher)(
suspensions = 0,
resumes = 0,
registers = 1,
unregisters = 1,
msgsReceived = 0,
msgsProcessed = 0,
- restarts = 0
- )
+ restarts = 0)
- val futures = for(i <- 1 to 10) yield Future { i }
+ val futures = for (i ← 1 to 10) yield Future { i }
await(dispatcher.stops.get == 2)(withinMs = dispatcher.timeoutMs * 5)
assertDispatcher(dispatcher)(starts = 2, stops = 2)
val a2 = newTestActor
a2.start
- val futures2 = for(i <- 1 to 10) yield Future { i }
+ val futures2 = for (i ← 1 to 10) yield Future { i }
await(dispatcher.starts.get == 3)(withinMs = dispatcher.timeoutMs * 5)
assertDispatcher(dispatcher)(starts = 3, stops = 2)
@@ -234,10 +231,11 @@ abstract class ActorModelSpec extends JUnitSuite {
assertDispatcher(dispatcher)(starts = 3, stops = 3)
}
- @Test def dispatcherShouldProcessMessagesOneAtATime {
+ @Test
+ def dispatcherShouldProcessMessagesOneAtATime {
implicit val dispatcher = newInterceptedDispatcher
val a = newTestActor
- val start,oneAtATime = new CountDownLatch(1)
+ val start, oneAtATime = new CountDownLatch(1)
a.start()
a ! CountDown(start)
@@ -247,39 +245,41 @@ abstract class ActorModelSpec extends JUnitSuite {
a ! Wait(1000)
a ! CountDown(oneAtATime)
// in case of serialization violation, restart would happen instead of count down
- assertCountDown(oneAtATime, Testing.testTime(1500) ,"Processed message when allowed")
+ assertCountDown(oneAtATime, Testing.testTime(1500), "Processed message when allowed")
assertRefDefaultZero(a)(registers = 1, msgsReceived = 3, msgsProcessed = 3)
a.stop()
assertRefDefaultZero(a)(registers = 1, unregisters = 1, msgsReceived = 3, msgsProcessed = 3)
}
- @Test def dispatcherShouldHandleQueueingFromMultipleThreads {
+ @Test
+ def dispatcherShouldHandleQueueingFromMultipleThreads {
implicit val dispatcher = newInterceptedDispatcher
val a = newTestActor
val counter = new CountDownLatch(200)
a.start()
- def start = spawn { for (i <- 1 to 20) { a ! WaitAck(1, counter) } }
- for (i <- 1 to 10) { start }
+ def start = spawn { for (i ← 1 to 20) { a ! WaitAck(1, counter) } }
+ for (i ← 1 to 10) { start }
assertCountDown(counter, Testing.testTime(3000), "Should process 200 messages")
assertRefDefaultZero(a)(registers = 1, msgsReceived = 200, msgsProcessed = 200)
a.stop()
}
- def spawn(f : => Unit) = {
+ def spawn(f: ⇒ Unit) = {
val thread = new Thread { override def run { f } }
thread.start()
thread
}
- @Test def dispatcherShouldProcessMessagesInParallel: Unit = {
+ @Test
+ def dispatcherShouldProcessMessagesInParallel: Unit = {
implicit val dispatcher = newInterceptedDispatcher
val a, b = newTestActor.start()
- val aStart,aStop,bParallel = new CountDownLatch(1)
+ val aStart, aStop, bParallel = new CountDownLatch(1)
- a ! Meet(aStart,aStop)
+ a ! Meet(aStart, aStop)
assertCountDown(aStart, Testing.testTime(3000), "Should process first message within 3 seconds")
b ! CountDown(bParallel)
@@ -292,7 +292,8 @@ abstract class ActorModelSpec extends JUnitSuite {
assertRefDefaultZero(b)(registers = 1, unregisters = 1, msgsReceived = 1, msgsProcessed = 1)
}
- @Test def dispatcherShouldSuspendAndResumeAFailingNonSupervisedPermanentActor {
+ @Test
+ def dispatcherShouldSuspendAndResumeAFailingNonSupervisedPermanentActor {
implicit val dispatcher = newInterceptedDispatcher
val a = newTestActor.start()
val done = new CountDownLatch(1)
@@ -300,11 +301,12 @@ abstract class ActorModelSpec extends JUnitSuite {
a ! CountDown(done)
assertCountDown(done, Testing.testTime(3000), "Should be suspended+resumed and done with next message within 3 seconds")
a.stop()
- assertRefDefaultZero(a)(registers = 1,unregisters = 1, msgsReceived = 2,
+ assertRefDefaultZero(a)(registers = 1, unregisters = 1, msgsReceived = 2,
msgsProcessed = 2, suspensions = 1, resumes = 1)
}
- @Test def dispatcherShouldNotProcessMessagesForASuspendedActor {
+ @Test
+ def dispatcherShouldNotProcessMessagesForASuspendedActor {
implicit val dispatcher = newInterceptedDispatcher
val a = newTestActor.start()
val done = new CountDownLatch(1)
@@ -319,21 +321,22 @@ abstract class ActorModelSpec extends JUnitSuite {
suspensions = 1, resumes = 1)
a.stop()
- assertRefDefaultZero(a)(registers = 1,unregisters = 1, msgsReceived = 1, msgsProcessed = 1,
+ assertRefDefaultZero(a)(registers = 1, unregisters = 1, msgsReceived = 1, msgsProcessed = 1,
suspensions = 1, resumes = 1)
}
- @Test def dispatcherShouldHandleWavesOfActors {
+ @Test
+ def dispatcherShouldHandleWavesOfActors {
implicit val dispatcher = newInterceptedDispatcher
def flood(num: Int) {
val cachedMessage = CountDownNStop(new CountDownLatch(num))
- (1 to num) foreach {
- _ => newTestActor.start() ! cachedMessage
+ (1 to num) foreach { _ ⇒
+ newTestActor.start() ! cachedMessage
}
assertCountDown(cachedMessage.latch, Testing.testTime(10000), "Should process " + num + " countdowns")
}
- for(run <- 1 to 3) {
+ for (run ← 1 to 3) {
flood(10000)
await(dispatcher.stops.get == run)(withinMs = 10000)
assertDispatcher(dispatcher)(starts = run, stops = run)
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/DispatchersSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/DispatchersSpec.scala
index 984a5e91f6..cc75c5d43a 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/DispatchersSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/DispatchersSpec.scala
@@ -3,39 +3,38 @@
*/
package akka.actor.dispatch
-import java.util.concurrent.{CountDownLatch, TimeUnit}
+import java.util.concurrent.{ CountDownLatch, TimeUnit }
import org.scalatest.junit.JUnitSuite
import org.junit.Test
import akka.config.Configuration
-import scala.reflect.{Manifest}
+import scala.reflect.{ Manifest }
import akka.dispatch._
object DispatchersSpec {
import Dispatchers._
//
- val tipe = "type"
- val keepalivems = "keep-alive-time"
+ val tipe = "type"
+ val keepalivems = "keep-alive-time"
val corepoolsizefactor = "core-pool-size-factor"
- val maxpoolsizefactor = "max-pool-size-factor"
- val executorbounds = "executor-bounds"
- val allowcoretimeout = "allow-core-timeout"
- val rejectionpolicy = "rejection-policy" // abort, caller-runs, discard-oldest, discard
- val throughput = "throughput" // Throughput for ExecutorBasedEventDrivenDispatcher
+ val maxpoolsizefactor = "max-pool-size-factor"
+ val executorbounds = "executor-bounds"
+ val allowcoretimeout = "allow-core-timeout"
+ val rejectionpolicy = "rejection-policy" // abort, caller-runs, discard-oldest, discard
+ val throughput = "throughput" // Throughput for ExecutorBasedEventDrivenDispatcher
- def instance(dispatcher: MessageDispatcher): (MessageDispatcher) => Boolean = _ == dispatcher
- def ofType[T <: MessageDispatcher : Manifest]: (MessageDispatcher) => Boolean = _.getClass == manifest[T].erasure
+ def instance(dispatcher: MessageDispatcher): (MessageDispatcher) ⇒ Boolean = _ == dispatcher
+ def ofType[T <: MessageDispatcher: Manifest]: (MessageDispatcher) ⇒ Boolean = _.getClass == manifest[T].erasure
- def typesAndValidators: Map[String,(MessageDispatcher) => Boolean] = Map(
- "ExecutorBasedEventDrivenWorkStealing" -> ofType[ExecutorBasedEventDrivenWorkStealingDispatcher],
- "ExecutorBasedEventDriven" -> ofType[ExecutorBasedEventDrivenDispatcher],
- "GlobalExecutorBasedEventDriven" -> instance(globalExecutorBasedEventDrivenDispatcher)
- )
+ def typesAndValidators: Map[String, (MessageDispatcher) ⇒ Boolean] = Map(
+ "ExecutorBasedEventDrivenWorkStealing" -> ofType[ExecutorBasedEventDrivenWorkStealingDispatcher],
+ "ExecutorBasedEventDriven" -> ofType[ExecutorBasedEventDrivenDispatcher],
+ "GlobalExecutorBasedEventDriven" -> instance(globalExecutorBasedEventDrivenDispatcher))
def validTypes = typesAndValidators.keys.toList
- lazy val allDispatchers: Map[String,Option[MessageDispatcher]] = {
- validTypes.map(t => (t,from(Configuration.fromMap(Map(tipe -> t))))).toMap
+ lazy val allDispatchers: Map[String, Option[MessageDispatcher]] = {
+ validTypes.map(t ⇒ (t, from(Configuration.fromMap(Map(tipe -> t))))).toMap
}
}
@@ -44,7 +43,8 @@ class DispatchersSpec extends JUnitSuite {
import Dispatchers._
import DispatchersSpec._
- @Test def shouldYieldNoneIfTypeIsMissing {
+ @Test
+ def shouldYieldNoneIfTypeIsMissing {
assert(from(Configuration.fromMap(Map())) === None)
}
@@ -53,14 +53,16 @@ class DispatchersSpec extends JUnitSuite {
from(Configuration.fromMap(Map(tipe -> "typedoesntexist")))
}
- @Test def shouldGetTheCorrectTypesOfDispatchers {
+ @Test
+ def shouldGetTheCorrectTypesOfDispatchers {
//It can create/obtain all defined types
assert(allDispatchers.values.forall(_.isDefined))
//All created/obtained dispatchers are of the expeced type/instance
- assert(typesAndValidators.forall( tuple => tuple._2(allDispatchers(tuple._1).get) ))
+ assert(typesAndValidators.forall(tuple ⇒ tuple._2(allDispatchers(tuple._1).get)))
}
- @Test def defaultingToDefaultWhileLoadingTheDefaultShouldWork {
+ @Test
+ def defaultingToDefaultWhileLoadingTheDefaultShouldWork {
assert(from(Configuration.fromMap(Map())).getOrElse(defaultGlobalDispatcher) == defaultGlobalDispatcher)
}
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcherActorSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcherActorSpec.scala
index 8020c5acde..c330d948d3 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcherActorSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcherActorSpec.scala
@@ -1,20 +1,20 @@
package akka.actor.dispatch
-import java.util.concurrent.{CountDownLatch, TimeUnit}
+import java.util.concurrent.{ CountDownLatch, TimeUnit }
import org.scalatest.junit.JUnitSuite
import org.junit.Test
-import akka.dispatch.{Dispatchers,ExecutorBasedEventDrivenDispatcher}
+import akka.dispatch.{ Dispatchers, ExecutorBasedEventDrivenDispatcher }
import akka.actor.Actor
import Actor._
-import java.util.concurrent.atomic.{AtomicBoolean, AtomicInteger}
+import java.util.concurrent.atomic.{ AtomicBoolean, AtomicInteger }
object ExecutorBasedEventDrivenDispatcherActorSpec {
class TestActor extends Actor {
self.dispatcher = Dispatchers.newExecutorBasedEventDrivenDispatcher(self.uuid.toString).build
def receive = {
- case "Hello" =>
+ case "Hello" ⇒
self.reply("World")
- case "Failure" =>
+ case "Failure" ⇒
throw new RuntimeException("Expected exception; to test fault-tolerance")
}
}
@@ -25,7 +25,7 @@ object ExecutorBasedEventDrivenDispatcherActorSpec {
class OneWayTestActor extends Actor {
self.dispatcher = Dispatchers.newExecutorBasedEventDrivenDispatcher(self.uuid.toString).build
def receive = {
- case "OneWay" => OneWayTestActor.oneWay.countDown()
+ case "OneWay" ⇒ OneWayTestActor.oneWay.countDown()
}
}
}
@@ -34,105 +34,111 @@ class ExecutorBasedEventDrivenDispatcherActorSpec extends JUnitSuite {
private val unit = TimeUnit.MILLISECONDS
- @Test def shouldSendOneWay = {
+ @Test
+ def shouldSendOneWay = {
val actor = actorOf[OneWayTestActor].start()
val result = actor ! "OneWay"
assert(OneWayTestActor.oneWay.await(1, TimeUnit.SECONDS))
actor.stop()
}
- @Test def shouldSendReplySync = {
+ @Test
+ def shouldSendReplySync = {
val actor = actorOf[TestActor].start()
val result = (actor !! ("Hello", 10000)).as[String]
assert("World" === result.get)
actor.stop()
}
- @Test def shouldSendReplyAsync = {
+ @Test
+ def shouldSendReplyAsync = {
val actor = actorOf[TestActor].start()
val result = actor !! "Hello"
assert("World" === result.get.asInstanceOf[String])
actor.stop()
}
- @Test def shouldSendReceiveException = {
+ @Test
+ def shouldSendReceiveException = {
val actor = actorOf[TestActor].start()
try {
actor !! "Failure"
fail("Should have thrown an exception")
} catch {
- case e =>
+ case e ⇒
assert("Expected exception; to test fault-tolerance" === e.getMessage())
}
actor.stop()
}
- @Test def shouldRespectThroughput {
- val throughputDispatcher = Dispatchers.
- newExecutorBasedEventDrivenDispatcher("THROUGHPUT",101,0,Dispatchers.MAILBOX_TYPE).
- setCorePoolSize(1).
- build
+ @Test
+ def shouldRespectThroughput {
+ val throughputDispatcher = Dispatchers.
+ newExecutorBasedEventDrivenDispatcher("THROUGHPUT", 101, 0, Dispatchers.MAILBOX_TYPE).
+ setCorePoolSize(1).
+ build
- val works = new AtomicBoolean(true)
- val latch = new CountDownLatch(100)
- val start = new CountDownLatch(1)
- val fastOne = actorOf(
- new Actor {
- self.dispatcher = throughputDispatcher
- def receive = { case "sabotage" => works.set(false) }
- }).start()
+ val works = new AtomicBoolean(true)
+ val latch = new CountDownLatch(100)
+ val start = new CountDownLatch(1)
+ val fastOne = actorOf(
+ new Actor {
+ self.dispatcher = throughputDispatcher
+ def receive = { case "sabotage" ⇒ works.set(false) }
+ }).start()
- val slowOne = actorOf(
- new Actor {
- self.dispatcher = throughputDispatcher
- def receive = {
- case "hogexecutor" => start.await
- case "ping" => if (works.get) latch.countDown()
- }
- }).start()
+ val slowOne = actorOf(
+ new Actor {
+ self.dispatcher = throughputDispatcher
+ def receive = {
+ case "hogexecutor" ⇒ start.await
+ case "ping" ⇒ if (works.get) latch.countDown()
+ }
+ }).start()
- slowOne ! "hogexecutor"
- (1 to 100) foreach { _ => slowOne ! "ping"}
- fastOne ! "sabotage"
- start.countDown()
- val result = latch.await(3,TimeUnit.SECONDS)
- fastOne.stop()
- slowOne.stop()
- assert(result === true)
- }
+ slowOne ! "hogexecutor"
+ (1 to 100) foreach { _ ⇒ slowOne ! "ping" }
+ fastOne ! "sabotage"
+ start.countDown()
+ val result = latch.await(3, TimeUnit.SECONDS)
+ fastOne.stop()
+ slowOne.stop()
+ assert(result === true)
+ }
- @Test def shouldRespectThroughputDeadline {
- val deadlineMs = 100
- val throughputDispatcher = Dispatchers.
- newExecutorBasedEventDrivenDispatcher("THROUGHPUT",2,deadlineMs,Dispatchers.MAILBOX_TYPE).
- setCorePoolSize(1).
- build
- val works = new AtomicBoolean(true)
- val latch = new CountDownLatch(1)
- val start = new CountDownLatch(1)
- val ready = new CountDownLatch(1)
+ @Test
+ def shouldRespectThroughputDeadline {
+ val deadlineMs = 100
+ val throughputDispatcher = Dispatchers.
+ newExecutorBasedEventDrivenDispatcher("THROUGHPUT", 2, deadlineMs, Dispatchers.MAILBOX_TYPE).
+ setCorePoolSize(1).
+ build
+ val works = new AtomicBoolean(true)
+ val latch = new CountDownLatch(1)
+ val start = new CountDownLatch(1)
+ val ready = new CountDownLatch(1)
- val fastOne = actorOf(
- new Actor {
- self.dispatcher = throughputDispatcher
- def receive = { case "ping" => if(works.get) latch.countDown(); self.stop() }
- }).start()
+ val fastOne = actorOf(
+ new Actor {
+ self.dispatcher = throughputDispatcher
+ def receive = { case "ping" ⇒ if (works.get) latch.countDown(); self.stop() }
+ }).start()
- val slowOne = actorOf(
- new Actor {
- self.dispatcher = throughputDispatcher
- def receive = {
- case "hogexecutor" => ready.countDown(); start.await
- case "ping" => works.set(false); self.stop()
- }
- }).start()
+ val slowOne = actorOf(
+ new Actor {
+ self.dispatcher = throughputDispatcher
+ def receive = {
+ case "hogexecutor" ⇒ ready.countDown(); start.await
+ case "ping" ⇒ works.set(false); self.stop()
+ }
+ }).start()
- slowOne ! "hogexecutor"
- slowOne ! "ping"
- fastOne ! "ping"
- assert(ready.await(2,TimeUnit.SECONDS) === true)
- Thread.sleep(deadlineMs+10) // wait just a bit more than the deadline
- start.countDown()
- assert(latch.await(2,TimeUnit.SECONDS) === true)
- }
+ slowOne ! "hogexecutor"
+ slowOne ! "ping"
+ fastOne ! "ping"
+ assert(ready.await(2, TimeUnit.SECONDS) === true)
+ Thread.sleep(deadlineMs + 10) // wait just a bit more than the deadline
+ start.countDown()
+ assert(latch.await(2, TimeUnit.SECONDS) === true)
+ }
}
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcherActorsSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcherActorsSpec.scala
index 0897831375..d636ecc932 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcherActorsSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcherActorsSpec.scala
@@ -16,7 +16,7 @@ class ExecutorBasedEventDrivenDispatcherActorsSpec extends JUnitSuite with MustM
class SlowActor(finishedCounter: CountDownLatch) extends Actor {
def receive = {
- case x: Int => {
+ case x: Int ⇒ {
Thread.sleep(50) // slow actor
finishedCounter.countDown()
}
@@ -25,25 +25,26 @@ class ExecutorBasedEventDrivenDispatcherActorsSpec extends JUnitSuite with MustM
class FastActor(finishedCounter: CountDownLatch) extends Actor {
def receive = {
- case x: Int => {
+ case x: Int ⇒ {
finishedCounter.countDown()
}
}
}
- @Test def slowActorShouldntBlockFastActor {
+ @Test
+ def slowActorShouldntBlockFastActor {
val sFinished = new CountDownLatch(50)
val fFinished = new CountDownLatch(10)
val s = actorOf(new SlowActor(sFinished), "SlowActor").start
val f = actorOf(new FastActor(fFinished), "FastActor").start
// send a lot of stuff to s
- for (i <- 1 to 50) {
+ for (i ← 1 to 50) {
s ! i
}
// send some messages to f
- for (i <- 1 to 10) {
+ for (i ← 1 to 10) {
f ! i
}
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenWorkStealingDispatcherSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenWorkStealingDispatcherSpec.scala
index 980b14b22d..064433c6ca 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenWorkStealingDispatcherSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenWorkStealingDispatcherSpec.scala
@@ -5,23 +5,24 @@ import org.scalatest.junit.JUnitSuite
import org.junit.Test
-import java.util.concurrent.{TimeUnit, CountDownLatch}
-import akka.actor.{IllegalActorStateException, Actor}
+import java.util.concurrent.{ TimeUnit, CountDownLatch }
+import akka.actor.{ IllegalActorStateException, Actor }
import Actor._
-import akka.dispatch.{MessageQueue, Dispatchers}
+import akka.dispatch.{ MessageQueue, Dispatchers }
object ExecutorBasedEventDrivenWorkStealingDispatcherSpec {
- def newWorkStealer() = Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher("pooled-dispatcher",1).build
+ def newWorkStealer() = Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher("pooled-dispatcher", 1).build
val delayableActorDispatcher, sharedActorDispatcher, parentActorDispatcher = newWorkStealer()
class DelayableActor(delay: Int, finishedCounter: CountDownLatch) extends Actor {
self.dispatcher = delayableActorDispatcher
- @volatile var invocationCount = 0
+ @volatile
+ var invocationCount = 0
def receive = {
- case x: Int => {
+ case x: Int ⇒ {
Thread.sleep(delay)
invocationCount += 1
finishedCounter.countDown()
@@ -31,17 +32,17 @@ object ExecutorBasedEventDrivenWorkStealingDispatcherSpec {
class FirstActor extends Actor {
self.dispatcher = sharedActorDispatcher
- def receive = {case _ => {}}
+ def receive = { case _ ⇒ {} }
}
class SecondActor extends Actor {
self.dispatcher = sharedActorDispatcher
- def receive = {case _ => {}}
+ def receive = { case _ ⇒ {} }
}
class ParentActor extends Actor {
self.dispatcher = parentActorDispatcher
- def receive = {case _ => {}}
+ def receive = { case _ ⇒ {} }
}
class ChildActor extends ParentActor {
@@ -54,7 +55,8 @@ object ExecutorBasedEventDrivenWorkStealingDispatcherSpec {
class ExecutorBasedEventDrivenWorkStealingDispatcherSpec extends JUnitSuite with MustMatchers {
import ExecutorBasedEventDrivenWorkStealingDispatcherSpec._
- @Test def fastActorShouldStealWorkFromSlowActor {
+ @Test
+ def fastActorShouldStealWorkFromSlowActor {
val finishedCounter = new CountDownLatch(110)
val slow = actorOf(new DelayableActor(50, finishedCounter), "slow").start
@@ -62,24 +64,22 @@ class ExecutorBasedEventDrivenWorkStealingDispatcherSpec extends JUnitSuite with
var sentToFast = 0
- for (i <- 1 to 100) {
+ for (i ← 1 to 100) {
// send most work to slow actor
if (i % 20 == 0) {
fast ! i
sentToFast += 1
- }
- else
+ } else
slow ! i
}
// now send some messages to actors to keep the dispatcher dispatching messages
- for (i <- 1 to 10) {
+ for (i ← 1 to 10) {
Thread.sleep(150)
if (i % 2 == 0) {
fast ! i
sentToFast += 1
- }
- else
+ } else
slow ! i
}
@@ -88,12 +88,13 @@ class ExecutorBasedEventDrivenWorkStealingDispatcherSpec extends JUnitSuite with
slow.mailbox.asInstanceOf[MessageQueue].isEmpty must be(true)
fast.actor.asInstanceOf[DelayableActor].invocationCount must be > sentToFast
fast.actor.asInstanceOf[DelayableActor].invocationCount must be >
- (slow.actor.asInstanceOf[DelayableActor].invocationCount)
+ (slow.actor.asInstanceOf[DelayableActor].invocationCount)
slow.stop()
fast.stop()
}
- @Test def canNotUseActorsOfDifferentTypesInSameDispatcher(): Unit = {
+ @Test
+ def canNotUseActorsOfDifferentTypesInSameDispatcher(): Unit = {
val first = actorOf[FirstActor]
val second = actorOf[SecondActor]
@@ -103,7 +104,8 @@ class ExecutorBasedEventDrivenWorkStealingDispatcherSpec extends JUnitSuite with
}
}
- @Test def canNotUseActorsOfDifferentSubTypesInSameDispatcher(): Unit = {
+ @Test
+ def canNotUseActorsOfDifferentSubTypesInSameDispatcher(): Unit = {
val parent = actorOf[ParentActor]
val child = actorOf[ChildActor]
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/FutureSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/FutureSpec.scala
index 857bcbcd5f..9a52d8f34d 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/FutureSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/FutureSpec.scala
@@ -5,26 +5,26 @@ import org.junit.Test
import akka.actor.{ Actor, ActorRef }
import Actor._
import org.multiverse.api.latches.StandardLatch
-import java.util.concurrent. {TimeUnit, CountDownLatch}
+import java.util.concurrent.{ TimeUnit, CountDownLatch }
object FutureSpec {
class TestActor extends Actor {
def receive = {
- case "Hello" =>
+ case "Hello" ⇒
self.reply("World")
- case "NoReply" => {}
- case "Failure" =>
+ case "NoReply" ⇒ {}
+ case "Failure" ⇒
throw new RuntimeException("Expected exception; to test fault-tolerance")
}
}
class TestDelayActor(await: StandardLatch) extends Actor {
def receive = {
- case "Hello" =>
+ case "Hello" ⇒
await.await
self.reply("World")
- case "NoReply" => { await.await }
- case "Failure" =>
+ case "NoReply" ⇒ { await.await }
+ case "Failure" ⇒
await.await
throw new RuntimeException("Expected exception; to test fault-tolerance")
}
@@ -36,7 +36,8 @@ class JavaFutureSpec extends JavaFutureTests with JUnitSuite
class FutureSpec extends JUnitSuite {
import FutureSpec._
- @Test def shouldActorReplyResultThroughExplicitFuture {
+ @Test
+ def shouldActorReplyResultThroughExplicitFuture {
val actor = actorOf[TestActor]
actor.start()
val future = actor !!! "Hello"
@@ -46,7 +47,8 @@ class FutureSpec extends JUnitSuite {
actor.stop()
}
- @Test def shouldActorReplyExceptionThroughExplicitFuture {
+ @Test
+ def shouldActorReplyExceptionThroughExplicitFuture {
val actor = actorOf[TestActor]
actor.start()
val future = actor !!! "Failure"
@@ -56,10 +58,11 @@ class FutureSpec extends JUnitSuite {
actor.stop()
}
- @Test def shouldFutureCompose {
+ @Test
+ def shouldFutureCompose {
val actor1 = actorOf[TestActor].start()
- val actor2 = actorOf(new Actor { def receive = { case s: String => self reply s.toUpperCase } } ).start()
- val future1 = actor1 !!! "Hello" flatMap ((s: String) => actor2 !!! s)
+ val actor2 = actorOf(new Actor { def receive = { case s: String ⇒ self reply s.toUpperCase } }).start()
+ val future1 = actor1 !!! "Hello" flatMap ((s: String) ⇒ actor2 !!! s)
val future2 = actor1 !!! "Hello" flatMap (actor2 !!! (_: String))
val future3 = actor1 !!! "Hello" flatMap (actor2 !!! (_: Int))
assert((future1.get: Any) === "WORLD")
@@ -69,37 +72,39 @@ class FutureSpec extends JUnitSuite {
actor2.stop()
}
- @Test def shouldFutureComposePatternMatch {
+ @Test
+ def shouldFutureComposePatternMatch {
val actor1 = actorOf[TestActor].start()
- val actor2 = actorOf(new Actor { def receive = { case s: String => self reply s.toUpperCase } } ).start()
- val future1 = actor1 !!! "Hello" collect { case (s: String) => s } flatMap (actor2 !!! _)
- val future2 = actor1 !!! "Hello" collect { case (n: Int) => n } flatMap (actor2 !!! _)
+ val actor2 = actorOf(new Actor { def receive = { case s: String ⇒ self reply s.toUpperCase } }).start()
+ val future1 = actor1 !!! "Hello" collect { case (s: String) ⇒ s } flatMap (actor2 !!! _)
+ val future2 = actor1 !!! "Hello" collect { case (n: Int) ⇒ n } flatMap (actor2 !!! _)
assert((future1.get: Any) === "WORLD")
intercept[MatchError] { future2.get }
actor1.stop()
actor2.stop()
}
- @Test def shouldFutureForComprehension {
+ @Test
+ def shouldFutureForComprehension {
val actor = actorOf(new Actor {
def receive = {
- case s: String => self reply s.length
- case i: Int => self reply (i * 2).toString
+ case s: String ⇒ self reply s.length
+ case i: Int ⇒ self reply (i * 2).toString
}
}).start()
val future0 = actor !!! "Hello"
val future1 = for {
- a: Int <- future0 // returns 5
- b: String <- actor !!! a // returns "10"
- c: String <- actor !!! 7 // returns "14"
+ a: Int ← future0 // returns 5
+ b: String ← actor !!! a // returns "10"
+ c: String ← actor !!! 7 // returns "14"
} yield b + "-" + c
val future2 = for {
- a: Int <- future0
- b: Int <- actor !!! a
- c: String <- actor !!! 7
+ a: Int ← future0
+ b: Int ← actor !!! a
+ c: String ← actor !!! 7
} yield b + "-" + c
assert(future1.get === "10-14")
@@ -107,26 +112,27 @@ class FutureSpec extends JUnitSuite {
actor.stop()
}
- @Test def shouldFutureForComprehensionPatternMatch {
+ @Test
+ def shouldFutureForComprehensionPatternMatch {
case class Req[T](req: T)
case class Res[T](res: T)
val actor = actorOf(new Actor {
def receive = {
- case Req(s: String) => self reply Res(s.length)
- case Req(i: Int) => self reply Res((i * 2).toString)
+ case Req(s: String) ⇒ self reply Res(s.length)
+ case Req(i: Int) ⇒ self reply Res((i * 2).toString)
}
}).start()
val future1 = for {
- Res(a: Int) <- actor !!! Req("Hello")
- Res(b: String) <- actor !!! Req(a)
- Res(c: String) <- actor !!! Req(7)
+ Res(a: Int) ← actor !!! Req("Hello")
+ Res(b: String) ← actor !!! Req(a)
+ Res(c: String) ← actor !!! Req(7)
} yield b + "-" + c
val future2 = for {
- Res(a: Int) <- actor !!! Req("Hello")
- Res(b: Int) <- actor !!! Req(a)
- Res(c: Int) <- actor !!! Req(7)
+ Res(a: Int) ← actor !!! Req("Hello")
+ Res(b: Int) ← actor !!! Req(a)
+ Res(c: Int) ← actor !!! Req(7)
} yield b + "-" + c
assert(future1.get === "10-14")
@@ -134,35 +140,36 @@ class FutureSpec extends JUnitSuite {
actor.stop()
}
- @Test def shouldMapMatchedExceptionsToResult {
+ @Test
+ def shouldMapMatchedExceptionsToResult {
val future1 = Future(5)
val future2 = future1 map (_ / 0)
val future3 = future2 map (_.toString)
val future4 = future1 failure {
- case e: ArithmeticException => 0
+ case e: ArithmeticException ⇒ 0
} map (_.toString)
val future5 = future2 failure {
- case e: ArithmeticException => 0
+ case e: ArithmeticException ⇒ 0
} map (_.toString)
val future6 = future2 failure {
- case e: MatchError => 0
+ case e: MatchError ⇒ 0
} map (_.toString)
- val future7 = future3 failure { case e: ArithmeticException => "You got ERROR" }
+ val future7 = future3 failure { case e: ArithmeticException ⇒ "You got ERROR" }
val actor = actorOf[TestActor].start()
val future8 = actor !!! "Failure"
val future9 = actor !!! "Failure" failure {
- case e: RuntimeException => "FAIL!"
+ case e: RuntimeException ⇒ "FAIL!"
}
val future10 = actor !!! "Hello" failure {
- case e: RuntimeException => "FAIL!"
+ case e: RuntimeException ⇒ "FAIL!"
}
- val future11 = actor !!! "Failure" failure { case _ => "Oops!" }
+ val future11 = actor !!! "Failure" failure { case _ ⇒ "Oops!" }
assert(future1.get === 5)
intercept[ArithmeticException] { future2.get }
@@ -179,32 +186,35 @@ class FutureSpec extends JUnitSuite {
actor.stop()
}
- @Test def shouldFoldResults {
- val actors = (1 to 10).toList map { _ =>
+ @Test
+ def shouldFoldResults {
+ val actors = (1 to 10).toList map { _ ⇒
actorOf(new Actor {
- def receive = { case (add: Int, wait: Int) => Thread.sleep(wait); self reply_? add }
+ def receive = { case (add: Int, wait: Int) ⇒ Thread.sleep(wait); self reply_? add }
}).start()
}
val timeout = 10000
- def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) => actor.!!, timeout) }
+ def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.!!, timeout) }
assert(Futures.fold(0, timeout)(futures)(_ + _).await.result.get === 45)
}
- @Test def shouldFoldResultsByComposing {
- val actors = (1 to 10).toList map { _ =>
+ @Test
+ def shouldFoldResultsByComposing {
+ val actors = (1 to 10).toList map { _ ⇒
actorOf(new Actor {
- def receive = { case (add: Int, wait: Int) => Thread.sleep(wait); self reply_? add }
+ def receive = { case (add: Int, wait: Int) ⇒ Thread.sleep(wait); self reply_? add }
}).start()
}
- def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) => actor.!!, 10000) }
- assert(futures.foldLeft(Future(0))((fr, fa) => for (r <- fr; a <- fa) yield (r + a)).get === 45)
+ def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.!!, 10000) }
+ assert(futures.foldLeft(Future(0))((fr, fa) ⇒ for (r ← fr; a ← fa) yield (r + a)).get === 45)
}
- @Test def shouldFoldResultsWithException {
- val actors = (1 to 10).toList map { _ =>
+ @Test
+ def shouldFoldResultsWithException {
+ val actors = (1 to 10).toList map { _ ⇒
actorOf(new Actor {
def receive = {
- case (add: Int, wait: Int) =>
+ case (add: Int, wait: Int) ⇒
Thread.sleep(wait)
if (add == 6) throw new IllegalArgumentException("shouldFoldResultsWithException: expected")
self reply_? add
@@ -212,30 +222,33 @@ class FutureSpec extends JUnitSuite {
}).start()
}
val timeout = 10000
- def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) => actor.!!, timeout) }
+ def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.!!, timeout) }
assert(Futures.fold(0, timeout)(futures)(_ + _).await.exception.get.getMessage === "shouldFoldResultsWithException: expected")
}
- @Test def shouldFoldReturnZeroOnEmptyInput {
+ @Test
+ def shouldFoldReturnZeroOnEmptyInput {
assert(Futures.fold(0)(List[Future[Int]]())(_ + _).get === 0)
}
- @Test def shouldReduceResults {
- val actors = (1 to 10).toList map { _ =>
+ @Test
+ def shouldReduceResults {
+ val actors = (1 to 10).toList map { _ ⇒
actorOf(new Actor {
- def receive = { case (add: Int, wait: Int) => Thread.sleep(wait); self reply_? add }
+ def receive = { case (add: Int, wait: Int) ⇒ Thread.sleep(wait); self reply_? add }
}).start()
}
val timeout = 10000
- def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) => actor.!!, timeout) }
+ def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.!!, timeout) }
assert(Futures.reduce(futures, timeout)(_ + _).get === 45)
}
- @Test def shouldReduceResultsWithException {
- val actors = (1 to 10).toList map { _ =>
+ @Test
+ def shouldReduceResultsWithException {
+ val actors = (1 to 10).toList map { _ ⇒
actorOf(new Actor {
def receive = {
- case (add: Int, wait: Int) =>
+ case (add: Int, wait: Int) ⇒
Thread.sleep(wait)
if (add == 6) throw new IllegalArgumentException("shouldFoldResultsWithException: expected")
self reply_? add
@@ -243,27 +256,30 @@ class FutureSpec extends JUnitSuite {
}).start()
}
val timeout = 10000
- def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) => actor.!!, timeout) }
+ def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.!!, timeout) }
assert(Futures.reduce(futures, timeout)(_ + _).await.exception.get.getMessage === "shouldFoldResultsWithException: expected")
}
- @Test(expected = classOf[UnsupportedOperationException]) def shouldReduceThrowIAEOnEmptyInput {
+ @Test(expected = classOf[UnsupportedOperationException])
+ def shouldReduceThrowIAEOnEmptyInput {
Futures.reduce(List[Future[Int]]())(_ + _).await.resultOrException
}
- @Test def receiveShouldExecuteOnComplete {
+ @Test
+ def receiveShouldExecuteOnComplete {
val latch = new StandardLatch
val actor = actorOf[TestActor].start()
- actor !!! "Hello" receive { case "World" => latch.open }
+ actor !!! "Hello" receive { case "World" ⇒ latch.open }
assert(latch.tryAwait(5, TimeUnit.SECONDS))
actor.stop()
}
- @Test def shouldTraverseFutures {
+ @Test
+ def shouldTraverseFutures {
val oddActor = actorOf(new Actor {
var counter = 1
def receive = {
- case 'GetNext =>
+ case 'GetNext ⇒
self reply counter
counter += 2
}
@@ -274,10 +290,11 @@ class FutureSpec extends JUnitSuite {
oddActor.stop()
val list = (1 to 100).toList
- assert(Future.traverse(list)(x => Future(x * 2 - 1)).get.sum === 10000)
+ assert(Future.traverse(list)(x ⇒ Future(x * 2 - 1)).get.sum === 10000)
}
- @Test def shouldHandleThrowables {
+ @Test
+ def shouldHandleThrowables {
class ThrowableTest(m: String) extends Throwable(m)
val f1 = Future { throw new ThrowableTest("test") }
@@ -286,14 +303,14 @@ class FutureSpec extends JUnitSuite {
val latch = new StandardLatch
val f2 = Future { latch.tryAwait(5, TimeUnit.SECONDS); "success" }
- f2 foreach (_ => throw new ThrowableTest("dispatcher foreach"))
- f2 receive { case _ => throw new ThrowableTest("dispatcher receive") }
- val f3 = f2 map (s => s.toUpperCase)
+ f2 foreach (_ ⇒ throw new ThrowableTest("dispatcher foreach"))
+ f2 receive { case _ ⇒ throw new ThrowableTest("dispatcher receive") }
+ val f3 = f2 map (s ⇒ s.toUpperCase)
latch.open
f2.await
assert(f2.resultOrException === Some("success"))
- f2 foreach (_ => throw new ThrowableTest("current thread foreach"))
- f2 receive { case _ => throw new ThrowableTest("current thread receive") }
+ f2 foreach (_ ⇒ throw new ThrowableTest("current thread foreach"))
+ f2 receive { case _ ⇒ throw new ThrowableTest("current thread receive") }
f3.await
assert(f3.resultOrException === Some("SUCCESS"))
@@ -301,23 +318,25 @@ class FutureSpec extends JUnitSuite {
assert(Dispatchers.defaultGlobalDispatcher.pendingFutures === 0)
}
- @Test def shouldBlockUntilResult {
+ @Test
+ def shouldBlockUntilResult {
val latch = new StandardLatch
- val f = Future({ latch.await; 5})
+ val f = Future({ latch.await; 5 })
val f2 = Future({ f.get + 5 })
assert(f2.resultOrException === None)
latch.open
assert(f2.get === 10)
- val f3 = Future({ Thread.sleep(100); 5}, 10)
+ val f3 = Future({ Thread.sleep(100); 5 }, 10)
intercept[FutureTimeoutException] {
f3.get
}
}
- @Test def futureComposingWithContinuations {
+ @Test
+ def futureComposingWithContinuations {
import Future.flow
val actor = actorOf[TestActor].start
@@ -332,7 +351,8 @@ class FutureSpec extends JUnitSuite {
actor.stop
}
- @Test def futureComposingWithContinuationsFailureDivideZero {
+ @Test
+ def futureComposingWithContinuationsFailureDivideZero {
import Future.flow
val x = Future("Hello")
@@ -343,7 +363,8 @@ class FutureSpec extends JUnitSuite {
intercept[java.lang.ArithmeticException](r.get)
}
- @Test def futureComposingWithContinuationsFailureCastInt {
+ @Test
+ def futureComposingWithContinuationsFailureCastInt {
import Future.flow
val actor = actorOf[TestActor].start
@@ -356,7 +377,8 @@ class FutureSpec extends JUnitSuite {
intercept[ClassCastException](r.get)
}
- @Test def futureComposingWithContinuationsFailureCastNothing {
+ @Test
+ def futureComposingWithContinuationsFailureCastNothing {
import Future.flow
val actor = actorOf[TestActor].start
@@ -369,7 +391,8 @@ class FutureSpec extends JUnitSuite {
intercept[ClassCastException](r.get)
}
- @Test def futureCompletingWithContinuations {
+ @Test
+ def futureCompletingWithContinuations {
import Future.flow
val x, y, z = Promise[Int]()
@@ -413,11 +436,12 @@ class FutureSpec extends JUnitSuite {
assert(Dispatchers.defaultGlobalDispatcher.pendingFutures === 0)
}
- @Test def shouldNotAddOrRunCallbacksAfterFailureToBeCompletedBeforeExpiry {
+ @Test
+ def shouldNotAddOrRunCallbacksAfterFailureToBeCompletedBeforeExpiry {
val latch = new StandardLatch
val f = Promise[Int](0)
Thread.sleep(25)
- f.onComplete( _ => latch.open ) //Shouldn't throw any exception here
+ f.onComplete(_ ⇒ latch.open) //Shouldn't throw any exception here
assert(f.isExpired) //Should be expired
@@ -427,7 +451,8 @@ class FutureSpec extends JUnitSuite {
assert(!latch.isOpen) //Shouldn't run the listener
}
- @Test def futureDataFlowShouldEmulateBlocking1 {
+ @Test
+ def futureDataFlowShouldEmulateBlocking1 {
import Future.flow
val one, two = Promise[Int](1000 * 60)
@@ -449,7 +474,8 @@ class FutureSpec extends JUnitSuite {
}
- @Test def futureDataFlowShouldEmulateBlocking2 {
+ @Test
+ def futureDataFlowShouldEmulateBlocking2 {
import Future.flow
val x1, x2, y1, y2 = Promise[Int](1000 * 60)
val lx, ly, lz = new StandardLatch
@@ -464,7 +490,7 @@ class FutureSpec extends JUnitSuite {
assert(lx.isOpen)
assert(!ly.isOpen)
assert(!lz.isOpen)
- assert(List(x1,x2,y1,y2).forall(_.isCompleted == false))
+ assert(List(x1, x2, y1, y2).forall(_.isCompleted == false))
flow { y1 << 1 } // When this is set, it should cascade down the line
@@ -477,12 +503,13 @@ class FutureSpec extends JUnitSuite {
assert(lz.tryAwaitUninterruptible(2000, TimeUnit.MILLISECONDS))
assert(x2.get === 9)
- assert(List(x1,x2,y1,y2).forall(_.isCompleted == true))
+ assert(List(x1, x2, y1, y2).forall(_.isCompleted == true))
assert(result.get === 10)
}
- @Test def dataFlowAPIshouldbeSlick {
+ @Test
+ def dataFlowAPIshouldbeSlick {
import Future.flow
val i1, i2, s1, s2 = new StandardLatch
@@ -502,7 +529,8 @@ class FutureSpec extends JUnitSuite {
assert(result.get === 10)
}
- @Test def futureCompletingWithContinuationsFailure {
+ @Test
+ def futureCompletingWithContinuationsFailure {
import Future.flow
val x, y, z = Promise[Int]()
@@ -528,7 +556,8 @@ class FutureSpec extends JUnitSuite {
assert(!lz.isOpen)
}
- @Test def futureContinuationsShouldNotBlock {
+ @Test
+ def futureContinuationsShouldNotBlock {
import Future.flow
val latch = new StandardLatch
@@ -548,7 +577,8 @@ class FutureSpec extends JUnitSuite {
assert(result.get === Some("Hello"))
}
- @Test def futureFlowShouldBeTypeSafe {
+ @Test
+ def futureFlowShouldBeTypeSafe {
import Future.flow
def checkType[A: Manifest, B](in: Future[A], refmanifest: Manifest[B]): Boolean = manifest[A] == refmanifest
@@ -574,7 +604,8 @@ class FutureSpec extends JUnitSuite {
rInt.await
}
- @Test def futureFlowSimpleAssign {
+ @Test
+ def futureFlowSimpleAssign {
import Future.flow
val x, y, z = Promise[Int]()
@@ -588,10 +619,11 @@ class FutureSpec extends JUnitSuite {
assert(z.get === 42)
}
- @Test def ticket812FutureDispatchCleanup {
+ @Test
+ def ticket812FutureDispatchCleanup {
val dispatcher = implicitly[MessageDispatcher]
assert(dispatcher.pendingFutures === 0)
- val future = Future({Thread.sleep(100);"Done"}, 10)
+ val future = Future({ Thread.sleep(100); "Done" }, 10)
intercept[FutureTimeoutException] { future.await }
assert(dispatcher.pendingFutures === 1)
Thread.sleep(100)
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala
index 0da861350d..773a68ef89 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala
@@ -1,158 +1,153 @@
package akka.dispatch
import org.scalatest.WordSpec
import org.scalatest.matchers.MustMatchers
-import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach}
+import org.scalatest.{ BeforeAndAfterAll, BeforeAndAfterEach }
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
-import akka.actor. {Actor, ActorRegistry}
-import akka.actor.Actor.{actorOf}
-import java.util.concurrent. {TimeUnit, CountDownLatch, BlockingQueue}
-import java.util.{Queue}
+import akka.actor.{ Actor, ActorRegistry }
+import akka.actor.Actor.{ actorOf }
+import java.util.concurrent.{ TimeUnit, CountDownLatch, BlockingQueue }
+import java.util.{ Queue }
import akka.util._
import akka.util.Duration._
-
@RunWith(classOf[JUnitRunner])
-abstract class MailboxSpec extends
- WordSpec with
- MustMatchers with
- BeforeAndAfterAll with
- BeforeAndAfterEach {
- def name: String
+abstract class MailboxSpec extends WordSpec with MustMatchers with BeforeAndAfterAll with BeforeAndAfterEach {
+ def name: String
- def factory: MailboxType => MessageQueue
+ def factory: MailboxType ⇒ MessageQueue
- name should {
- "create an unbounded mailbox" in {
- val config = UnboundedMailbox()
- val q = factory(config)
- ensureInitialMailboxState(config, q)
+ name should {
+ "create an unbounded mailbox" in {
+ val config = UnboundedMailbox()
+ val q = factory(config)
+ ensureInitialMailboxState(config, q)
- implicit val within = Duration(1,TimeUnit.SECONDS)
+ implicit val within = Duration(1, TimeUnit.SECONDS)
- val f = spawn {
- q.dequeue
- }
-
- f.await.resultOrException must be === Some(null)
+ val f = spawn {
+ q.dequeue
}
- "create a bounded mailbox with 10 capacity and with push timeout" in {
- val config = BoundedMailbox(10, Duration(10,TimeUnit.MILLISECONDS))
- val q = factory(config)
- ensureInitialMailboxState(config, q)
-
- val exampleMessage = createMessageInvocation("test")
-
- for(i <- 1 to config.capacity) q.enqueue(exampleMessage)
-
- q.size must be === config.capacity
- q.isEmpty must be === false
-
- intercept[MessageQueueAppendFailedException] {
- q.enqueue(exampleMessage)
- }
-
- q.dequeue must be === exampleMessage
- q.size must be (config.capacity - 1)
- q.isEmpty must be === false
- }
-
- "dequeue what was enqueued properly for unbounded mailboxes" in {
- testEnqueueDequeue(UnboundedMailbox())
- }
-
- "dequeue what was enqueued properly for bounded mailboxes" in {
- testEnqueueDequeue(BoundedMailbox(10000, Duration(-1, TimeUnit.MILLISECONDS)))
- }
-
- "dequeue what was enqueued properly for bounded mailboxes with pushTimeout" in {
- testEnqueueDequeue(BoundedMailbox(10000, Duration(100, TimeUnit.MILLISECONDS)))
- }
+ f.await.resultOrException must be === Some(null)
}
- //CANDIDATE FOR TESTKIT
- def spawn[T <: AnyRef](fun: => T)(implicit within: Duration): Future[T] = {
- val result = new DefaultCompletableFuture[T](within.length, within.unit)
- val t = new Thread(new Runnable {
- def run = try {
- result.completeWithResult(fun)
- } catch {
- case e: Throwable => result.completeWithException(e)
- }
- })
- t.start()
- result
- }
+ "create a bounded mailbox with 10 capacity and with push timeout" in {
+ val config = BoundedMailbox(10, Duration(10, TimeUnit.MILLISECONDS))
+ val q = factory(config)
+ ensureInitialMailboxState(config, q)
- def createMessageInvocation(msg: Any): MessageInvocation = {
- new MessageInvocation(
- actorOf(new Actor { //Dummy actor
- def receive = { case _ => }
- }), msg, None, None)
- }
+ val exampleMessage = createMessageInvocation("test")
- def ensureInitialMailboxState(config: MailboxType, q: MessageQueue) {
- q must not be null
- q match {
- case aQueue: BlockingQueue[_] =>
- config match {
- case BoundedMailbox(capacity,_) => aQueue.remainingCapacity must be === capacity
- case UnboundedMailbox() => aQueue.remainingCapacity must be === Int.MaxValue
- }
- case _ =>
+ for (i ← 1 to config.capacity) q.enqueue(exampleMessage)
+
+ q.size must be === config.capacity
+ q.isEmpty must be === false
+
+ intercept[MessageQueueAppendFailedException] {
+ q.enqueue(exampleMessage)
}
- q.size must be === 0
- q.isEmpty must be === true
+
+ q.dequeue must be === exampleMessage
+ q.size must be(config.capacity - 1)
+ q.isEmpty must be === false
}
- def testEnqueueDequeue(config: MailboxType) {
- implicit val within = Duration(10,TimeUnit.SECONDS)
- val q = factory(config)
- ensureInitialMailboxState(config, q)
+ "dequeue what was enqueued properly for unbounded mailboxes" in {
+ testEnqueueDequeue(UnboundedMailbox())
+ }
- def createProducer(fromNum: Int, toNum: Int): Future[Vector[MessageInvocation]] = spawn {
- val messages = Vector() ++ (for(i <- fromNum to toNum) yield createMessageInvocation(i))
- for(i <- messages) q.enqueue(i)
- messages
- }
+ "dequeue what was enqueued properly for bounded mailboxes" in {
+ testEnqueueDequeue(BoundedMailbox(10000, Duration(-1, TimeUnit.MILLISECONDS)))
+ }
- val totalMessages = 10000
- val step = 500
-
- val producers = for(i <- (1 to totalMessages by step).toList) yield createProducer(i,i+step-1)
-
- def createConsumer: Future[Vector[MessageInvocation]] = spawn {
- var r = Vector[MessageInvocation]()
- while(producers.exists(_.isCompleted == false) || !q.isEmpty) {
- q.dequeue match {
- case null =>
- case message => r = r :+ message
- }
- }
- r
- }
-
- val consumers = for(i <- (1 to 4).toList) yield createConsumer
-
- val ps = producers.map(_.await.resultOrException.get)
- val cs = consumers.map(_.await.resultOrException.get)
-
- ps.map(_.size).sum must be === totalMessages //Must have produced 1000 messages
- cs.map(_.size).sum must be === totalMessages //Must have consumed all produced messages
- //No message is allowed to be consumed by more than one consumer
- cs.flatten.distinct.size must be === totalMessages
- //All produced messages should have been consumed
- (cs.flatten diff ps.flatten).size must be === 0
- (ps.flatten diff cs.flatten).size must be === 0
+ "dequeue what was enqueued properly for bounded mailboxes with pushTimeout" in {
+ testEnqueueDequeue(BoundedMailbox(10000, Duration(100, TimeUnit.MILLISECONDS)))
}
}
+ //CANDIDATE FOR TESTKIT
+ def spawn[T <: AnyRef](fun: ⇒ T)(implicit within: Duration): Future[T] = {
+ val result = new DefaultCompletableFuture[T](within.length, within.unit)
+ val t = new Thread(new Runnable {
+ def run = try {
+ result.completeWithResult(fun)
+ } catch {
+ case e: Throwable ⇒ result.completeWithException(e)
+ }
+ })
+ t.start()
+ result
+ }
+
+ def createMessageInvocation(msg: Any): MessageInvocation = {
+ new MessageInvocation(
+ actorOf(new Actor { //Dummy actor
+ def receive = { case _ ⇒ }
+ }), msg, None, None)
+ }
+
+ def ensureInitialMailboxState(config: MailboxType, q: MessageQueue) {
+ q must not be null
+ q match {
+ case aQueue: BlockingQueue[_] ⇒
+ config match {
+ case BoundedMailbox(capacity, _) ⇒ aQueue.remainingCapacity must be === capacity
+ case UnboundedMailbox() ⇒ aQueue.remainingCapacity must be === Int.MaxValue
+ }
+ case _ ⇒
+ }
+ q.size must be === 0
+ q.isEmpty must be === true
+ }
+
+ def testEnqueueDequeue(config: MailboxType) {
+ implicit val within = Duration(10, TimeUnit.SECONDS)
+ val q = factory(config)
+ ensureInitialMailboxState(config, q)
+
+ def createProducer(fromNum: Int, toNum: Int): Future[Vector[MessageInvocation]] = spawn {
+ val messages = Vector() ++ (for (i ← fromNum to toNum) yield createMessageInvocation(i))
+ for (i ← messages) q.enqueue(i)
+ messages
+ }
+
+ val totalMessages = 10000
+ val step = 500
+
+ val producers = for (i ← (1 to totalMessages by step).toList) yield createProducer(i, i + step - 1)
+
+ def createConsumer: Future[Vector[MessageInvocation]] = spawn {
+ var r = Vector[MessageInvocation]()
+ while (producers.exists(_.isCompleted == false) || !q.isEmpty) {
+ q.dequeue match {
+ case null ⇒
+ case message ⇒ r = r :+ message
+ }
+ }
+ r
+ }
+
+ val consumers = for (i ← (1 to 4).toList) yield createConsumer
+
+ val ps = producers.map(_.await.resultOrException.get)
+ val cs = consumers.map(_.await.resultOrException.get)
+
+ ps.map(_.size).sum must be === totalMessages //Must have produced 1000 messages
+ cs.map(_.size).sum must be === totalMessages //Must have consumed all produced messages
+ //No message is allowed to be consumed by more than one consumer
+ cs.flatten.distinct.size must be === totalMessages
+ //All produced messages should have been consumed
+ (cs.flatten diff ps.flatten).size must be === 0
+ (ps.flatten diff cs.flatten).size must be === 0
+ }
+}
+
class DefaultMailboxSpec extends MailboxSpec {
lazy val name = "The default mailbox implementation"
def factory = {
- case UnboundedMailbox() => new DefaultUnboundedMessageQueue()
- case BoundedMailbox(capacity, pushTimeOut) => new DefaultBoundedMessageQueue(capacity, pushTimeOut)
+ case UnboundedMailbox() ⇒ new DefaultUnboundedMessageQueue()
+ case BoundedMailbox(capacity, pushTimeOut) ⇒ new DefaultBoundedMessageQueue(capacity, pushTimeOut)
}
}
@@ -160,7 +155,7 @@ class PriorityMailboxSpec extends MailboxSpec {
val comparator = PriorityGenerator(_.##)
lazy val name = "The priority mailbox implementation"
def factory = {
- case UnboundedMailbox() => new UnboundedPriorityMessageQueue(comparator)
- case BoundedMailbox(capacity, pushTimeOut) => new BoundedPriorityMessageQueue(capacity, pushTimeOut, comparator)
+ case UnboundedMailbox() ⇒ new UnboundedPriorityMessageQueue(comparator)
+ case BoundedMailbox(capacity, pushTimeOut) ⇒ new BoundedPriorityMessageQueue(capacity, pushTimeOut, comparator)
}
}
\ No newline at end of file
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala
index 002267a6c7..ff2e85fb05 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala
@@ -20,32 +20,31 @@ class PriorityDispatcherSpec extends WordSpec with MustMatchers {
def testOrdering(mboxType: MailboxType) {
val dispatcher = new PriorityExecutorBasedEventDrivenDispatcher("Test",
- PriorityGenerator({
- case i: Int => i //Reverse order
- case 'Result => Int.MaxValue
- }: Any => Int),
- throughput = 1,
- mailboxType = mboxType
- )
+ PriorityGenerator({
+ case i: Int ⇒ i //Reverse order
+ case 'Result ⇒ Int.MaxValue
+ }: Any ⇒ Int),
+ throughput = 1,
+ mailboxType = mboxType)
- val actor = actorOf(new Actor {
- self.dispatcher = dispatcher
- var acc: List[Int] = Nil
+ val actor = actorOf(new Actor {
+ self.dispatcher = dispatcher
+ var acc: List[Int] = Nil
- def receive = {
- case i: Int => acc = i :: acc
- case 'Result => self reply_? acc
- }
- }).start()
+ def receive = {
+ case i: Int ⇒ acc = i :: acc
+ case 'Result ⇒ self reply_? acc
+ }
+ }).start()
- dispatcher.suspend(actor) //Make sure the actor isn't treating any messages, let it buffer the incoming messages
+ dispatcher.suspend(actor) //Make sure the actor isn't treating any messages, let it buffer the incoming messages
- val msgs = (1 to 100).toList
- for(m <- msgs) actor ! m
+ val msgs = (1 to 100).toList
+ for (m ← msgs) actor ! m
- dispatcher.resume(actor) //Signal the actor to start treating it's message backlog
+ dispatcher.resume(actor) //Signal the actor to start treating it's message backlog
- actor.!!![List[Int]]('Result).await.result.get must be === (msgs.reverse)
+ actor.!!![List[Int]]('Result).await.result.get must be === (msgs.reverse)
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ThreadBasedActorSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/ThreadBasedActorSpec.scala
index c6d6e2cb46..fd127c1a14 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/ThreadBasedActorSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/ThreadBasedActorSpec.scala
@@ -1,6 +1,6 @@
package akka.actor.dispatch
-import java.util.concurrent.{CountDownLatch, TimeUnit}
+import java.util.concurrent.{ CountDownLatch, TimeUnit }
import org.scalatest.junit.JUnitSuite
import org.junit.Test
@@ -13,9 +13,9 @@ object ThreadBasedActorSpec {
self.dispatcher = Dispatchers.newThreadBasedDispatcher(self)
def receive = {
- case "Hello" =>
+ case "Hello" ⇒
self.reply("World")
- case "Failure" =>
+ case "Failure" ⇒
throw new RuntimeException("Expected exception; to test fault-tolerance")
}
}
@@ -26,12 +26,13 @@ class ThreadBasedActorSpec extends JUnitSuite {
private val unit = TimeUnit.MILLISECONDS
- @Test def shouldSendOneWay {
+ @Test
+ def shouldSendOneWay {
var oneWay = new CountDownLatch(1)
val actor = actorOf(new Actor {
self.dispatcher = Dispatchers.newThreadBasedDispatcher(self)
def receive = {
- case "OneWay" => oneWay.countDown()
+ case "OneWay" ⇒ oneWay.countDown()
}
}).start()
val result = actor ! "OneWay"
@@ -39,27 +40,30 @@ class ThreadBasedActorSpec extends JUnitSuite {
actor.stop()
}
- @Test def shouldSendReplySync = {
+ @Test
+ def shouldSendReplySync = {
val actor = actorOf[TestActor].start()
val result = (actor !! ("Hello", 10000)).as[String]
assert("World" === result.get)
actor.stop()
}
- @Test def shouldSendReplyAsync = {
+ @Test
+ def shouldSendReplyAsync = {
val actor = actorOf[TestActor].start()
val result = actor !! "Hello"
assert("World" === result.get.asInstanceOf[String])
actor.stop()
}
- @Test def shouldSendReceiveException = {
+ @Test
+ def shouldSendReceiveException = {
val actor = actorOf[TestActor].start()
try {
actor !! "Failure"
fail("Should have thrown an exception")
} catch {
- case e =>
+ case e ⇒
assert("Expected exception; to test fault-tolerance" === e.getMessage())
}
actor.stop()
diff --git a/akka-actor-tests/src/test/scala/akka/misc/ActorRegistrySpec.scala b/akka-actor-tests/src/test/scala/akka/misc/ActorRegistrySpec.scala
index 59acf99b4f..6214c84da3 100644
--- a/akka-actor-tests/src/test/scala/akka/misc/ActorRegistrySpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/misc/ActorRegistrySpec.scala
@@ -3,14 +3,14 @@ package akka.actor
import org.scalatest.junit.JUnitSuite
import org.junit.Test
import Actor._
-import java.util.concurrent.{CyclicBarrier, TimeUnit, CountDownLatch}
+import java.util.concurrent.{ CyclicBarrier, TimeUnit, CountDownLatch }
import org.scalatest.Assertions._
object ActorRegistrySpec {
var record = ""
class TestActor extends Actor {
def receive = {
- case "ping" =>
+ case "ping" ⇒
record = "pong" + record
self.reply("got ping")
}
@@ -18,10 +18,10 @@ object ActorRegistrySpec {
class TestActor2 extends Actor {
def receive = {
- case "ping" =>
+ case "ping" ⇒
record = "pong" + record
self.reply("got ping")
- case "ping2" =>
+ case "ping2" ⇒
record = "pong" + record
self.reply("got ping")
}
@@ -31,7 +31,8 @@ object ActorRegistrySpec {
class ActorRegistrySpec extends JUnitSuite {
import ActorRegistrySpec._
- @Test def shouldGetActorByAddressFromActorRegistry {
+ @Test
+ def shouldGetActorByAddressFromActorRegistry {
Actor.registry.local.shutdownAll
val actor1 = actorOf[TestActor]("test-actor-1")
actor1.start
@@ -42,7 +43,8 @@ class ActorRegistrySpec extends JUnitSuite {
actor2.get.stop
}
- @Test def shouldGetActorByUUIDFromLocalActorRegistry {
+ @Test
+ def shouldGetActorByUUIDFromLocalActorRegistry {
Actor.registry.local.shutdownAll
val actor = actorOf[TestActor]("test-actor-1")
val uuid = actor.uuid
@@ -54,18 +56,20 @@ class ActorRegistrySpec extends JUnitSuite {
actor.stop
}
- @Test def shouldFindThingsFromLocalActorRegistry {
+ @Test
+ def shouldFindThingsFromLocalActorRegistry {
Actor.registry.local.shutdownAll
val actor = actorOf[TestActor]("test-actor-1")
actor.start
- val found = Actor.registry.local.find({ case a: ActorRef if a.actor.isInstanceOf[TestActor] => a })
+ val found = Actor.registry.local.find({ case a: ActorRef if a.actor.isInstanceOf[TestActor] ⇒ a })
assert(found.isDefined)
assert(found.get.actor.isInstanceOf[TestActor])
assert(found.get.address === "test-actor-1")
actor.stop
}
- @Test def shouldGetAllActorsFromLocalActorRegistry {
+ @Test
+ def shouldGetAllActorsFromLocalActorRegistry {
Actor.registry.local.shutdownAll
val actor1 = actorOf[TestActor]("test-actor-1")
actor1.start
@@ -81,20 +85,22 @@ class ActorRegistrySpec extends JUnitSuite {
actor2.stop
}
- @Test def shouldGetResponseByAllActorsInLocalActorRegistryWhenInvokingForeach {
+ @Test
+ def shouldGetResponseByAllActorsInLocalActorRegistryWhenInvokingForeach {
Actor.registry.local.shutdownAll
val actor1 = actorOf[TestActor]("test-actor-1")
actor1.start
val actor2 = actorOf[TestActor]("test-actor-2")
actor2.start
record = ""
- Actor.registry.local.foreach(actor => actor !! "ping")
+ Actor.registry.local.foreach(actor ⇒ actor !! "ping")
assert(record === "pongpong")
actor1.stop()
actor2.stop()
}
- @Test def shouldShutdownAllActorsInLocalActorRegistry {
+ @Test
+ def shouldShutdownAllActorsInLocalActorRegistry {
Actor.registry.local.shutdownAll
val actor1 = actorOf[TestActor]("test-actor-1")
actor1.start
@@ -104,7 +110,8 @@ class ActorRegistrySpec extends JUnitSuite {
assert(Actor.registry.local.actors.size === 0)
}
- @Test def shouldRemoveUnregisterActorInLocalActorRegistry {
+ @Test
+ def shouldRemoveUnregisterActorInLocalActorRegistry {
Actor.registry.local.shutdownAll
val actor1 = actorOf[TestActor]("test-actor-1")
actor1.start
diff --git a/akka-actor-tests/src/test/scala/akka/misc/SchedulerSpec.scala b/akka-actor-tests/src/test/scala/akka/misc/SchedulerSpec.scala
index 910b8b142b..6b5dbd684c 100644
--- a/akka-actor-tests/src/test/scala/akka/misc/SchedulerSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/misc/SchedulerSpec.scala
@@ -2,26 +2,26 @@ package akka.actor
import org.scalatest.junit.JUnitSuite
import Actor._
-import java.util.concurrent.{CountDownLatch, TimeUnit}
+import java.util.concurrent.{ CountDownLatch, TimeUnit }
import akka.config.Supervision._
import org.multiverse.api.latches.StandardLatch
import org.junit.Test
class SchedulerSpec extends JUnitSuite {
- def withCleanEndState(action: => Unit) {
+ def withCleanEndState(action: ⇒ Unit) {
action
Scheduler.restart
Actor.registry.local.shutdownAll
}
-
- @Test def schedulerShouldScheduleMoreThanOnce = withCleanEndState {
+ @Test
+ def schedulerShouldScheduleMoreThanOnce = withCleanEndState {
case object Tick
val countDownLatch = new CountDownLatch(3)
val tickActor = actorOf(new Actor {
- def receive = { case Tick => countDownLatch.countDown() }
+ def receive = { case Tick ⇒ countDownLatch.countDown() }
}).start()
// run every 50 millisec
Scheduler.schedule(tickActor, Tick, 0, 50, TimeUnit.MILLISECONDS)
@@ -31,21 +31,22 @@ class SchedulerSpec extends JUnitSuite {
val countDownLatch2 = new CountDownLatch(3)
- Scheduler.schedule( () => countDownLatch2.countDown(), 0, 50, TimeUnit.MILLISECONDS)
+ Scheduler.schedule(() ⇒ countDownLatch2.countDown(), 0, 50, TimeUnit.MILLISECONDS)
// after max 1 second it should be executed at least the 3 times already
assert(countDownLatch2.await(1, TimeUnit.SECONDS))
}
- @Test def schedulerShouldScheduleOnce = withCleanEndState {
+ @Test
+ def schedulerShouldScheduleOnce = withCleanEndState {
case object Tick
val countDownLatch = new CountDownLatch(3)
val tickActor = actorOf(new Actor {
- def receive = { case Tick => countDownLatch.countDown() }
+ def receive = { case Tick ⇒ countDownLatch.countDown() }
}).start()
// run every 50 millisec
Scheduler.scheduleOnce(tickActor, Tick, 50, TimeUnit.MILLISECONDS)
- Scheduler.scheduleOnce( () => countDownLatch.countDown(), 50, TimeUnit.MILLISECONDS)
+ Scheduler.scheduleOnce(() ⇒ countDownLatch.countDown(), 50, TimeUnit.MILLISECONDS)
// after 1 second the wait should fail
assert(countDownLatch.await(1, TimeUnit.SECONDS) == false)
@@ -56,40 +57,43 @@ class SchedulerSpec extends JUnitSuite {
/**
* ticket #372
*/
- @Test def schedulerShouldntCreateActors = withCleanEndState {
+ @Test
+ def schedulerShouldntCreateActors = withCleanEndState {
object Ping
val ticks = new CountDownLatch(1000)
val actor = actorOf(new Actor {
- def receive = { case Ping => ticks.countDown }
+ def receive = { case Ping ⇒ ticks.countDown }
}).start
val numActors = Actor.registry.local.actors.length
- (1 to 1000).foreach( _ => Scheduler.scheduleOnce(actor,Ping,1,TimeUnit.MILLISECONDS) )
- assert(ticks.await(10,TimeUnit.SECONDS))
+ (1 to 1000).foreach(_ ⇒ Scheduler.scheduleOnce(actor, Ping, 1, TimeUnit.MILLISECONDS))
+ assert(ticks.await(10, TimeUnit.SECONDS))
assert(Actor.registry.local.actors.length === numActors)
}
/**
* ticket #372
*/
- @Test def schedulerShouldBeCancellable = withCleanEndState {
+ @Test
+ def schedulerShouldBeCancellable = withCleanEndState {
object Ping
val ticks = new CountDownLatch(1)
val actor = actorOf(new Actor {
- def receive = { case Ping => ticks.countDown() }
+ def receive = { case Ping ⇒ ticks.countDown() }
}).start()
- (1 to 10).foreach { i =>
- val future = Scheduler.scheduleOnce(actor,Ping,1,TimeUnit.SECONDS)
+ (1 to 10).foreach { i ⇒
+ val future = Scheduler.scheduleOnce(actor, Ping, 1, TimeUnit.SECONDS)
future.cancel(true)
}
- assert(ticks.await(3,TimeUnit.SECONDS) == false) //No counting down should've been made
+ assert(ticks.await(3, TimeUnit.SECONDS) == false) //No counting down should've been made
}
/**
* ticket #307
*/
- @Test def actorRestartShouldPickUpScheduleAgain = withCleanEndState {
+ @Test
+ def actorRestartShouldPickUpScheduleAgain = withCleanEndState {
object Ping
object Crash
@@ -101,8 +105,8 @@ class SchedulerSpec extends JUnitSuite {
self.lifeCycle = Permanent
def receive = {
- case Ping => pingLatch.countDown()
- case Crash => throw new Exception("CRASH")
+ case Ping ⇒ pingLatch.countDown()
+ case Crash ⇒ throw new Exception("CRASH")
}
override def postRestart(reason: Throwable) = restartLatch.open
@@ -114,7 +118,7 @@ class SchedulerSpec extends JUnitSuite {
Supervise(
actor,
Permanent)
- :: Nil)).start
+ :: Nil)).start
Scheduler.schedule(actor, Ping, 500, 500, TimeUnit.MILLISECONDS)
// appx 2 pings before crash
diff --git a/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala
index 51b805f69e..18a800e408 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala
@@ -4,7 +4,7 @@ import org.scalatest.WordSpec
import org.scalatest.matchers.MustMatchers
import akka.testing._
-import akka.testing.Testing.{sleepFor, testMillis}
+import akka.testing.Testing.{ sleepFor, testMillis }
import akka.util.duration._
import akka.actor.Actor
@@ -13,7 +13,6 @@ import akka.routing._
import java.util.concurrent.atomic.AtomicInteger
-
class RoutingSpec extends WordSpec with MustMatchers {
import Routing._
@@ -26,32 +25,32 @@ class RoutingSpec extends WordSpec with MustMatchers {
val t1 = actorOf(new Actor {
def receive = {
- case Test1 => self.reply(3)
- case Test2 => self.reply(7)
+ case Test1 ⇒ self.reply(3)
+ case Test2 ⇒ self.reply(7)
}
}).start()
- val t2 = actorOf( new Actor() {
+ val t2 = actorOf(new Actor() {
def receive = {
- case Test3 => self.reply(11)
+ case Test3 ⇒ self.reply(11)
}
}).start()
val d = dispatcherActor {
- case Test1 | Test2 => t1
- case Test3 => t2
+ case Test1 | Test2 ⇒ t1
+ case Test3 ⇒ t2
}.start()
val result = for {
- a <- (d !! (Test1, testMillis(5 seconds))).as[Int]
- b <- (d !! (Test2, testMillis(5 seconds))).as[Int]
- c <- (d !! (Test3, testMillis(5 seconds))).as[Int]
+ a ← (d !! (Test1, testMillis(5 seconds))).as[Int]
+ b ← (d !! (Test2, testMillis(5 seconds))).as[Int]
+ c ← (d !! (Test3, testMillis(5 seconds))).as[Int]
} yield a + b + c
- result.isDefined must be (true)
- result.get must be (21)
+ result.isDefined must be(true)
+ result.get must be(21)
- for(a <- List(t1, t2, d)) a.stop()
+ for (a ← List(t1, t2, d)) a.stop()
}
"have messages logged" in {
@@ -59,10 +58,10 @@ class RoutingSpec extends WordSpec with MustMatchers {
val latch = TestLatch(2)
val actor = actorOf(new Actor {
- def receive = { case _ => }
+ def receive = { case _ ⇒ }
}).start()
- val logger = loggerActor(actor, x => { msgs.add(x); latch.countDown() }).start()
+ val logger = loggerActor(actor, x ⇒ { msgs.add(x); latch.countDown() }).start()
val foo: Any = "foo"
val bar: Any = "bar"
@@ -72,7 +71,7 @@ class RoutingSpec extends WordSpec with MustMatchers {
latch.await
- msgs must ( have size (2) and contain (foo) and contain (bar) )
+ msgs must (have size (2) and contain(foo) and contain(bar))
actor.stop()
logger.stop()
@@ -85,7 +84,7 @@ class RoutingSpec extends WordSpec with MustMatchers {
val t1 = actorOf(new Actor {
def receive = {
- case x =>
+ case x ⇒
sleepFor(50 millis) // slow actor
t1Count.incrementAndGet
latch.countDown()
@@ -94,7 +93,7 @@ class RoutingSpec extends WordSpec with MustMatchers {
val t2 = actorOf(new Actor {
def receive = {
- case x =>
+ case x ⇒
t2Count.incrementAndGet
latch.countDown()
}
@@ -102,17 +101,16 @@ class RoutingSpec extends WordSpec with MustMatchers {
val d = loadBalancerActor(new SmallestMailboxFirstIterator(t1 :: t2 :: Nil))
- for (i <- 1 to 500) d ! i
+ for (i ← 1 to 500) d ! i
latch.await(10 seconds)
// because t1 is much slower and thus has a bigger mailbox all the time
t1Count.get must be < (t2Count.get)
- for(a <- List(t1, t2, d)) a.stop()
+ for (a ← List(t1, t2, d)) a.stop()
}
-
"listen" in {
val fooLatch = TestLatch(2)
val barLatch = TestLatch(2)
@@ -120,16 +118,16 @@ class RoutingSpec extends WordSpec with MustMatchers {
val broadcast = actorOf(new Actor with Listeners {
def receive = listenerManagement orElse {
- case "foo" => gossip("bar")
+ case "foo" ⇒ gossip("bar")
}
}).start()
def newListener = actorOf(new Actor {
def receive = {
- case "bar" =>
+ case "bar" ⇒
barCount.incrementAndGet
barLatch.countDown()
- case "foo" =>
+ case "foo" ⇒
fooLatch.countDown()
}
}).start()
@@ -148,22 +146,22 @@ class RoutingSpec extends WordSpec with MustMatchers {
broadcast ! "foo"
barLatch.await
- barCount.get must be (2)
+ barCount.get must be(2)
fooLatch.await
- for(a <- List(broadcast, a1 ,a2 ,a3)) a.stop()
+ for (a ← List(broadcast, a1, a2, a3)) a.stop()
}
"be defined at" in {
import akka.actor.ActorRef
val Yes = "yes"
- val No = "no"
+ val No = "no"
- def testActor() = actorOf( new Actor() {
+ def testActor() = actorOf(new Actor() {
def receive = {
- case Yes => "yes"
+ case Yes ⇒ "yes"
}
}).start()
@@ -175,16 +173,16 @@ class RoutingSpec extends WordSpec with MustMatchers {
val d1 = loadBalancerActor(new SmallestMailboxFirstIterator(t1 :: t2 :: Nil))
val d2 = loadBalancerActor(new CyclicIterator[ActorRef](t3 :: t4 :: Nil))
- t1.isDefinedAt(Yes) must be (true)
- t1.isDefinedAt(No) must be (false)
- t2.isDefinedAt(Yes) must be (true)
- t2.isDefinedAt(No) must be (false)
- d1.isDefinedAt(Yes) must be (true)
- d1.isDefinedAt(No) must be (false)
- d2.isDefinedAt(Yes) must be (true)
- d2.isDefinedAt(No) must be (false)
+ t1.isDefinedAt(Yes) must be(true)
+ t1.isDefinedAt(No) must be(false)
+ t2.isDefinedAt(Yes) must be(true)
+ t2.isDefinedAt(No) must be(false)
+ d1.isDefinedAt(Yes) must be(true)
+ d1.isDefinedAt(No) must be(false)
+ d2.isDefinedAt(Yes) must be(true)
+ d2.isDefinedAt(No) must be(false)
- for(a <- List(t1, t2, d1, d2)) a.stop()
+ for (a ← List(t1, t2, d1, d2)) a.stop()
}
}
@@ -195,13 +193,10 @@ class RoutingSpec extends WordSpec with MustMatchers {
val count = new AtomicInteger(0)
val pool = actorOf(
- new Actor with DefaultActorPool
- with FixedCapacityStrategy
- with SmallestMailboxSelector
- {
+ new Actor with DefaultActorPool with FixedCapacityStrategy with SmallestMailboxSelector {
def factory = actorOf(new Actor {
def receive = {
- case _ =>
+ case _ ⇒
count.incrementAndGet
latch.countDown()
self reply_? "success"
@@ -218,7 +213,7 @@ class RoutingSpec extends WordSpec with MustMatchers {
val successes = TestLatch(2)
val successCounter = Some(actorOf(new Actor {
def receive = {
- case "success" => successes.countDown()
+ case "success" ⇒ successes.countDown()
}
}).start())
@@ -229,22 +224,16 @@ class RoutingSpec extends WordSpec with MustMatchers {
latch.await
successes.await
- count.get must be (2)
+ count.get must be(2)
- (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be (2)
+ (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be(2)
pool.stop()
}
-
"pass ticket #705" in {
val pool = actorOf(
- new Actor with DefaultActorPool
- with BoundedCapacityStrategy
- with MailboxPressureCapacitor
- with SmallestMailboxSelector
- with BasicFilter
- {
+ new Actor with DefaultActorPool with BoundedCapacityStrategy with MailboxPressureCapacitor with SmallestMailboxSelector with BasicFilter {
def lowerBound = 2
def upperBound = 20
def rampupRate = 0.1
@@ -257,7 +246,7 @@ class RoutingSpec extends WordSpec with MustMatchers {
def pressureThreshold = 1
def factory = actorOf(new Actor {
def receive = {
- case req: String => {
+ case req: String ⇒ {
sleepFor(10 millis)
self.reply_?("Response")
}
@@ -266,8 +255,8 @@ class RoutingSpec extends WordSpec with MustMatchers {
}).start()
try {
- (for (count <- 1 to 500) yield pool.!!) foreach {
- _.await.resultOrException.get must be ("Response")
+ (for (count ← 1 to 500) yield pool.!!) foreach {
+ _.await.resultOrException.get must be("Response")
}
} finally {
pool.stop()
@@ -282,15 +271,10 @@ class RoutingSpec extends WordSpec with MustMatchers {
val count = new AtomicInteger(0)
val pool = actorOf(
- new Actor with DefaultActorPool
- with BoundedCapacityStrategy
- with ActiveFuturesPressureCapacitor
- with SmallestMailboxSelector
- with BasicNoBackoffFilter
- {
+ new Actor with DefaultActorPool with BoundedCapacityStrategy with ActiveFuturesPressureCapacitor with SmallestMailboxSelector with BasicNoBackoffFilter {
def factory = actorOf(new Actor {
def receive = {
- case n: Int =>
+ case n: Int ⇒
sleepFor(n millis)
count.incrementAndGet
latch.countDown()
@@ -310,13 +294,13 @@ class RoutingSpec extends WordSpec with MustMatchers {
pool ! 1
- (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be (2)
+ (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be(2)
var loops = 0
def loop(t: Int) = {
latch = TestLatch(loops)
count.set(0)
- for (m <- 0 until loops) {
+ for (m ← 0 until loops) {
pool !!! t
sleepFor(50 millis)
}
@@ -328,18 +312,18 @@ class RoutingSpec extends WordSpec with MustMatchers {
loop(500)
latch.await
- count.get must be (loops)
+ count.get must be(loops)
- (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be (2)
+ (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be(2)
// a whole bunch should max it out
loops = 10
loop(500)
latch.await
- count.get must be (loops)
+ count.get must be(loops)
- (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be (4)
+ (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be(4)
pool.stop()
}
@@ -352,15 +336,10 @@ class RoutingSpec extends WordSpec with MustMatchers {
val count = new AtomicInteger(0)
val pool = actorOf(
- new Actor with DefaultActorPool
- with BoundedCapacityStrategy
- with MailboxPressureCapacitor
- with SmallestMailboxSelector
- with BasicNoBackoffFilter
- {
+ new Actor with DefaultActorPool with BoundedCapacityStrategy with MailboxPressureCapacitor with SmallestMailboxSelector with BasicNoBackoffFilter {
def factory = actorOf(new Actor {
def receive = {
- case n: Int =>
+ case n: Int ⇒
sleepFor(n millis)
count.incrementAndGet
latch.countDown()
@@ -381,7 +360,7 @@ class RoutingSpec extends WordSpec with MustMatchers {
def loop(t: Int) = {
latch = TestLatch(loops)
count.set(0)
- for (m <- 0 until loops) {
+ for (m ← 0 until loops) {
pool ! t
}
}
@@ -390,16 +369,16 @@ class RoutingSpec extends WordSpec with MustMatchers {
loops = 3
loop(500)
latch.await
- count.get must be (loops)
+ count.get must be(loops)
- (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be (2)
+ (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be(2)
// send a bunch over the theshold and observe an increment
loops = 15
loop(500)
latch.await(10 seconds)
- count.get must be (loops)
+ count.get must be(loops)
(pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be >= (3)
@@ -411,15 +390,11 @@ class RoutingSpec extends WordSpec with MustMatchers {
val delegates = new java.util.concurrent.ConcurrentHashMap[String, String]
val pool1 = actorOf(
- new Actor with DefaultActorPool
- with FixedCapacityStrategy
- with RoundRobinSelector
- with BasicNoBackoffFilter
- {
+ new Actor with DefaultActorPool with FixedCapacityStrategy with RoundRobinSelector with BasicNoBackoffFilter {
def factory = actorOf(new Actor {
def receive = {
- case _ =>
- delegates put(self.uuid.toString, "")
+ case _ ⇒
+ delegates put (self.uuid.toString, "")
latch1.countDown()
}
})
@@ -436,7 +411,7 @@ class RoutingSpec extends WordSpec with MustMatchers {
pool1 ! "b"
latch1.await
- delegates.size must be (1)
+ delegates.size must be(1)
pool1.stop()
@@ -444,15 +419,11 @@ class RoutingSpec extends WordSpec with MustMatchers {
delegates.clear()
val pool2 = actorOf(
- new Actor with DefaultActorPool
- with FixedCapacityStrategy
- with RoundRobinSelector
- with BasicNoBackoffFilter
- {
+ new Actor with DefaultActorPool with FixedCapacityStrategy with RoundRobinSelector with BasicNoBackoffFilter {
def factory = actorOf(new Actor {
def receive = {
- case _ =>
- delegates put(self.uuid.toString, "")
+ case _ ⇒
+ delegates put (self.uuid.toString, "")
latch2.countDown()
}
})
@@ -469,7 +440,7 @@ class RoutingSpec extends WordSpec with MustMatchers {
pool2 ! "b"
latch2.await
- delegates.size must be (2)
+ delegates.size must be(2)
pool2.stop()
}
@@ -478,17 +449,10 @@ class RoutingSpec extends WordSpec with MustMatchers {
val latch = TestLatch(10)
val pool = actorOf(
- new Actor with DefaultActorPool
- with BoundedCapacityStrategy
- with MailboxPressureCapacitor
- with SmallestMailboxSelector
- with Filter
- with RunningMeanBackoff
- with BasicRampup
- {
+ new Actor with DefaultActorPool with BoundedCapacityStrategy with MailboxPressureCapacitor with SmallestMailboxSelector with Filter with RunningMeanBackoff with BasicRampup {
def factory = actorOf(new Actor {
def receive = {
- case n: Int =>
+ case n: Int ⇒
sleepFor(n millis)
latch.countDown()
}
@@ -508,7 +472,7 @@ class RoutingSpec extends WordSpec with MustMatchers {
// put some pressure on the pool
- for (m <- 0 to 10) pool ! 250
+ for (m ← 0 to 10) pool ! 250
sleepFor(5 millis)
@@ -518,7 +482,7 @@ class RoutingSpec extends WordSpec with MustMatchers {
// let it cool down
- for (m <- 0 to 3) {
+ for (m ← 0 to 3) {
pool ! 1
sleepFor(500 millis)
}
diff --git a/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala b/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala
index 993f92259d..7b2a829f59 100644
--- a/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala
@@ -22,13 +22,13 @@ class CallingThreadDispatcherModelSpec extends ActorModelSpec {
def flood(num: Int) {
val cachedMessage = CountDownNStop(new CountDownLatch(num))
val keeper = newTestActor.start()
- (1 to num) foreach {
- _ => newTestActor.start() ! cachedMessage
+ (1 to num) foreach { _ ⇒
+ newTestActor.start() ! cachedMessage
}
keeper.stop()
- assertCountDown(cachedMessage.latch,10000, "Should process " + num + " countdowns")
+ assertCountDown(cachedMessage.latch, 10000, "Should process " + num + " countdowns")
}
- for(run <- 1 to 3) {
+ for (run ← 1 to 3) {
flood(10000)
await(dispatcher.stops.get == run)(withinMs = 10000)
assertDispatcher(dispatcher)(starts = run, stops = run)
diff --git a/akka-actor-tests/src/test/scala/akka/ticket/Ticket001Spec.scala b/akka-actor-tests/src/test/scala/akka/ticket/Ticket001Spec.scala
index e1a862e03c..c22445e19d 100644
--- a/akka-actor-tests/src/test/scala/akka/ticket/Ticket001Spec.scala
+++ b/akka-actor-tests/src/test/scala/akka/ticket/Ticket001Spec.scala
@@ -7,7 +7,7 @@ class Ticket001Spec extends WordSpec with MustMatchers {
"An XXX" must {
"do YYY" in {
- 1 must be (1)
+ 1 must be(1)
}
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/ticket/Ticket703Spec.scala b/akka-actor-tests/src/test/scala/akka/ticket/Ticket703Spec.scala
index 3648d0ab45..ac5bea25aa 100644
--- a/akka-actor-tests/src/test/scala/akka/ticket/Ticket703Spec.scala
+++ b/akka-actor-tests/src/test/scala/akka/ticket/Ticket703Spec.scala
@@ -10,25 +10,25 @@ class Ticket703Spec extends WordSpec with MustMatchers {
"A !!! call to an actor pool" should {
"reuse the proper timeout" in {
- val actorPool = actorOf(
- new Actor with DefaultActorPool with BoundedCapacityStrategy with MailboxPressureCapacitor with SmallestMailboxSelector with BasicNoBackoffFilter {
- def lowerBound = 2
- def upperBound = 20
- def rampupRate = 0.1
- def partialFill = true
- def selectionCount = 1
- def instance = factory
- def receive = _route
- def pressureThreshold = 1
- def factory = actorOf(new Actor {
- def receive = {
- case req: String =>
- Thread.sleep(6000L)
- self.reply_?("Response")
- }
- })
+ val actorPool = actorOf(
+ new Actor with DefaultActorPool with BoundedCapacityStrategy with MailboxPressureCapacitor with SmallestMailboxSelector with BasicNoBackoffFilter {
+ def lowerBound = 2
+ def upperBound = 20
+ def rampupRate = 0.1
+ def partialFill = true
+ def selectionCount = 1
+ def instance = factory
+ def receive = _route
+ def pressureThreshold = 1
+ def factory = actorOf(new Actor {
+ def receive = {
+ case req: String ⇒
+ Thread.sleep(6000L)
+ self.reply_?("Response")
+ }
+ })
}).start()
- (actorPool.!!).await.result must be === Some("Response")
+ (actorPool.!!).await.result must be === Some("Response")
}
}
}
\ No newline at end of file
diff --git a/akka-actor-tests/src/test/scala/akka/util/DurationSpec.scala b/akka-actor-tests/src/test/scala/akka/util/DurationSpec.scala
index 4c76a1ba4f..2f2fd3312b 100644
--- a/akka-actor-tests/src/test/scala/akka/util/DurationSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/util/DurationSpec.scala
@@ -13,28 +13,28 @@ class DurationSpec extends WordSpec with MustMatchers {
val one = 1.second
val two = one + one
val three = 3 * one
- (0 * one) must be (zero)
- (2 * one) must be (two)
- (three - two) must be (one)
- (three / 3) must be (one)
- (two / one) must be (2)
- (one + zero) must be (one)
- (one / 1000000) must be (1.micro)
+ (0 * one) must be(zero)
+ (2 * one) must be(two)
+ (three - two) must be(one)
+ (three / 3) must be(one)
+ (two / one) must be(2)
+ (one + zero) must be(one)
+ (one / 1000000) must be(1.micro)
}
"respect correct treatment of infinities" in {
val one = 1.second
val inf = Duration.Inf
val minf = Duration.MinusInf
- (-inf) must be (minf)
+ (-inf) must be(minf)
intercept[IllegalArgumentException] { minf + inf }
intercept[IllegalArgumentException] { inf - inf }
intercept[IllegalArgumentException] { inf + minf }
intercept[IllegalArgumentException] { minf - minf }
- (inf + inf) must be (inf)
- (inf - minf) must be (inf)
- (minf - inf) must be (minf)
- (minf + minf) must be (minf)
+ (inf + inf) must be(inf)
+ (inf - minf) must be(inf)
+ (minf - inf) must be(minf)
+ (minf + minf) must be(minf)
}
}
diff --git a/akka-actor/src/main/scala/akka/AkkaException.scala b/akka-actor/src/main/scala/akka/AkkaException.scala
index a9edf69a0b..71da1fa417 100644
--- a/akka-actor/src/main/scala/akka/AkkaException.scala
+++ b/akka-actor/src/main/scala/akka/AkkaException.scala
@@ -5,7 +5,7 @@
package akka
import akka.actor.newUuid
-import java.net.{InetAddress, UnknownHostException}
+import java.net.{ InetAddress, UnknownHostException }
/**
* Akka base Exception. Each Exception gets:
@@ -25,8 +25,8 @@ class AkkaException(message: String = "", cause: Throwable = null) extends Runti
def stackTraceToString = {
val trace = getStackTrace
val sb = new StringBuffer
- for (i <- 0 until trace.length)
- sb.append("\tat %s\n" format trace(i))
+ for (i ← 0 until trace.length)
+ sb.append("\tat %s\n" format trace(i))
sb.toString
}
}
@@ -35,6 +35,6 @@ object AkkaException {
val hostname = try {
InetAddress.getLocalHost.getHostName
} catch {
- case e: UnknownHostException => "unknown"
+ case e: UnknownHostException ⇒ "unknown"
}
}
diff --git a/akka-actor/src/main/scala/akka/actor/Actor.scala b/akka-actor/src/main/scala/akka/actor/Actor.scala
index d48aecbc1b..7da3f0ea85 100644
--- a/akka-actor/src/main/scala/akka/actor/Actor.scala
+++ b/akka-actor/src/main/scala/akka/actor/Actor.scala
@@ -8,13 +8,13 @@ import DeploymentConfig._
import akka.dispatch._
import akka.config.Config
import Config._
-import akka.util.{ListenerManagement, ReflectiveAccess, Duration, Helpers}
+import akka.util.{ ListenerManagement, ReflectiveAccess, Duration, Helpers }
import ReflectiveAccess._
-import Helpers.{narrow, narrowSilently}
+import Helpers.{ narrow, narrowSilently }
import akka.remoteinterface.RemoteSupport
-import akka.japi.{Creator, Procedure}
+import akka.japi.{ Creator, Procedure }
import akka.AkkaException
-import akka.serialization.{Format, Serializer}
+import akka.serialization.{ Format, Serializer }
import akka.event.EventHandler
import scala.reflect.BeanProperty
@@ -31,17 +31,17 @@ sealed trait LifeCycleMessage extends Serializable
/**
* Marker trait to show which Messages are automatically handled by Akka
*/
-sealed trait AutoReceivedMessage { self: LifeCycleMessage => }
+sealed trait AutoReceivedMessage { self: LifeCycleMessage ⇒ }
-case class HotSwap(code: ActorRef => Actor.Receive, discardOld: Boolean = true) extends AutoReceivedMessage with LifeCycleMessage {
+case class HotSwap(code: ActorRef ⇒ Actor.Receive, discardOld: Boolean = true) extends AutoReceivedMessage with LifeCycleMessage {
/**
* Java API
*/
- def this(code: akka.japi.Function[ActorRef,Procedure[Any]], discardOld: Boolean) = {
- this( (self: ActorRef) => {
+ def this(code: akka.japi.Function[ActorRef, Procedure[Any]], discardOld: Boolean) = {
+ this((self: ActorRef) ⇒ {
val behavior = code(self)
- val result: Actor.Receive = { case msg => behavior(msg) }
+ val result: Actor.Receive = { case msg ⇒ behavior(msg) }
result
}, discardOld)
}
@@ -77,12 +77,12 @@ case class MaximumNumberOfRestartsWithinTimeRangeReached(
@BeanProperty val lastExceptionCausingRestart: Throwable) extends LifeCycleMessage
// Exceptions for Actors
-class ActorStartException private[akka](message: String, cause: Throwable = null) extends AkkaException(message, cause)
-class IllegalActorStateException private[akka](message: String, cause: Throwable = null) extends AkkaException(message, cause)
-class ActorKilledException private[akka](message: String, cause: Throwable = null) extends AkkaException(message, cause)
-class ActorInitializationException private[akka](message: String, cause: Throwable = null) extends AkkaException(message, cause)
-class ActorTimeoutException private[akka](message: String, cause: Throwable = null) extends AkkaException(message, cause)
-class InvalidMessageException private[akka](message: String, cause: Throwable = null) extends AkkaException(message, cause)
+class ActorStartException private[akka] (message: String, cause: Throwable = null) extends AkkaException(message, cause)
+class IllegalActorStateException private[akka] (message: String, cause: Throwable = null) extends AkkaException(message, cause)
+class ActorKilledException private[akka] (message: String, cause: Throwable = null) extends AkkaException(message, cause)
+class ActorInitializationException private[akka] (message: String, cause: Throwable = null) extends AkkaException(message, cause)
+class ActorTimeoutException private[akka] (message: String, cause: Throwable = null) extends AkkaException(message, cause)
+class InvalidMessageException private[akka] (message: String, cause: Throwable = null) extends AkkaException(message, cause)
/**
* This message is thrown by default when an Actors behavior doesn't match a message
@@ -108,8 +108,8 @@ object Actor extends ListenerManagement {
// Clear Thread.subclassAudits
val tf = classOf[java.lang.Thread].getDeclaredField("subclassAudits")
tf.setAccessible(true)
- val subclassAudits = tf.get(null).asInstanceOf[java.util.Map[_,_]]
- subclassAudits synchronized {subclassAudits.clear()}
+ val subclassAudits = tf.get(null).asInstanceOf[java.util.Map[_, _]]
+ subclassAudits synchronized { subclassAudits.clear() }
}
}
Runtime.getRuntime.addShutdownHook(new Thread(hook))
@@ -135,7 +135,7 @@ object Actor extends ListenerManagement {
*/
type Receive = PartialFunction[Any, Unit]
- private[actor] val actorRefInCreation = new ThreadLocal[Option[ActorRef]]{
+ private[actor] val actorRefInCreation = new ThreadLocal[Option[ActorRef]] {
override def initialValue = None
}
@@ -153,8 +153,8 @@ object Actor extends ListenerManagement {
* val actor = actorOf[MyActor].start()
*
*/
- def actorOf[T <: Actor : Manifest](address: String): ActorRef =
- actorOf(manifest[T].erasure.asInstanceOf[Class[_ <: Actor]], address)
+ def actorOf[T <: Actor: Manifest](address: String): ActorRef =
+ actorOf(manifest[T].erasure.asInstanceOf[Class[_ <: Actor]], address)
/**
* Creates an ActorRef out of the Actor with type T.
@@ -171,8 +171,8 @@ object Actor extends ListenerManagement {
* val actor = actorOf[MyActor].start
*
*/
- def actorOf[T <: Actor : Manifest]: ActorRef =
- actorOf(manifest[T].erasure.asInstanceOf[Class[_ <: Actor]], new UUID().toString)
+ def actorOf[T <: Actor: Manifest]: ActorRef =
+ actorOf(manifest[T].erasure.asInstanceOf[Class[_ <: Actor]], new UUID().toString)
/**
* Creates an ActorRef out of the Actor of the specified Class.
@@ -210,11 +210,11 @@ object Actor extends ListenerManagement {
Address.validate(address)
try {
Deployer.deploymentFor(address) match {
- case Deploy(_, router, _, Local) => newLocalActorRef(clazz, address) // FIXME handle 'router' in 'Local' actors
- case deploy => newClusterActorRef[T](clazz, address, deploy)
+ case Deploy(_, router, _, Local) ⇒ newLocalActorRef(clazz, address) // FIXME handle 'router' in 'Local' actors
+ case deploy ⇒ newClusterActorRef[T](clazz, address, deploy)
}
} catch {
- case e: DeploymentException =>
+ case e: DeploymentException ⇒
EventHandler.error(e, this, "Look up deployment for address [%s] falling back to local actor." format address)
newLocalActorRef(clazz, address) // if deployment fails, fall back to local actors
}
@@ -238,7 +238,7 @@ object Actor extends ListenerManagement {
* val actor = actorOf(new MyActor).start()
*
*/
- def actorOf[T <: Actor](factory: => T): ActorRef = actorOf(factory, new UUID().toString)
+ def actorOf[T <: Actor](factory: ⇒ T): ActorRef = actorOf(factory, new UUID().toString)
/**
* Creates an ActorRef out of the Actor. Allows you to pass in a factory function
@@ -258,16 +258,16 @@ object Actor extends ListenerManagement {
* val actor = actorOf(new MyActor).start
*
*/
- def actorOf[T <: Actor](creator: => T, address: String): ActorRef = {
+ def actorOf[T <: Actor](creator: ⇒ T, address: String): ActorRef = {
Address.validate(address)
- val factory = () => creator
+ val factory = () ⇒ creator
try {
Deployer.deploymentFor(address) match {
- case Deploy(_, router, _, Local) => new LocalActorRef(factory, address) // FIXME handle 'router' in 'Local' actors
- case deploy => newClusterActorRef[T](factory, address, deploy)
+ case Deploy(_, router, _, Local) ⇒ new LocalActorRef(factory, address) // FIXME handle 'router' in 'Local' actors
+ case deploy ⇒ newClusterActorRef[T](factory, address, deploy)
}
} catch {
- case e: DeploymentException =>
+ case e: DeploymentException ⇒
EventHandler.error(e, this, "Look up deployment for address [%s] falling back to local actor." format address)
new LocalActorRef(factory, address) // if deployment fails, fall back to local actors
}
@@ -294,14 +294,14 @@ object Actor extends ListenerManagement {
*/
def actorOf[T <: Actor](creator: Creator[T], address: String): ActorRef = {
Address.validate(address)
- val factory = () => creator.create
+ val factory = () ⇒ creator.create
try {
Deployer.deploymentFor(address) match {
- case Deploy(_, router, _, Local) => new LocalActorRef(factory, address) // FIXME handle 'router' in 'Local' actors
- case deploy => newClusterActorRef[T](factory, address, deploy)
+ case Deploy(_, router, _, Local) ⇒ new LocalActorRef(factory, address) // FIXME handle 'router' in 'Local' actors
+ case deploy ⇒ newClusterActorRef[T](factory, address, deploy)
}
} catch {
- case e: DeploymentException =>
+ case e: DeploymentException ⇒
EventHandler.error(e, this, "Look up deployment for address [%s] falling back to local actor." format address)
new LocalActorRef(factory, address) // if deployment fails, fall back to local actors
}
@@ -322,12 +322,12 @@ object Actor extends ListenerManagement {
* }
*
*/
- def spawn(body: => Unit)(implicit dispatcher: MessageDispatcher = Dispatchers.defaultGlobalDispatcher): Unit = {
+ def spawn(body: ⇒ Unit)(implicit dispatcher: MessageDispatcher = Dispatchers.defaultGlobalDispatcher): Unit = {
case object Spawn
actorOf(new Actor() {
self.dispatcher = dispatcher
def receive = {
- case Spawn => try { body } finally { self.stop() }
+ case Spawn ⇒ try { body } finally { self.stop() }
}
}).start() ! Spawn
}
@@ -347,54 +347,53 @@ object Actor extends ListenerManagement {
* (actor !!! "foo").as[Int] (Recommended)
*/
implicit def futureToAnyOptionAsTypedOption(anyFuture: Future[_]) = new AnyOptionAsTypedOption({
- try { anyFuture.await } catch { case t: FutureTimeoutException => }
+ try { anyFuture.await } catch { case t: FutureTimeoutException ⇒ }
anyFuture.resultOrException
})
private[akka] def newLocalActorRef(clazz: Class[_ <: Actor], address: String): ActorRef = {
- new LocalActorRef(() => {
+ new LocalActorRef(() ⇒ {
import ReflectiveAccess.{ createInstance, noParams, noArgs }
createInstance[Actor](clazz.asInstanceOf[Class[_]], noParams, noArgs) match {
- case Right(actor) => actor
- case Left(exception) =>
+ case Right(actor) ⇒ actor
+ case Left(exception) ⇒
val cause = exception match {
- case i: InvocationTargetException => i.getTargetException
- case _ => exception
+ case i: InvocationTargetException ⇒ i.getTargetException
+ case _ ⇒ exception
}
throw new ActorInitializationException(
"Could not instantiate Actor of " + clazz +
- "\nMake sure Actor is NOT defined inside a class/trait," +
- "\nif so put it outside the class/trait, f.e. in a companion object," +
- "\nOR try to change: 'actorOf[MyActor]' to 'actorOf(new MyActor)'.", cause)
- }
+ "\nMake sure Actor is NOT defined inside a class/trait," +
+ "\nif so put it outside the class/trait, f.e. in a companion object," +
+ "\nOR try to change: 'actorOf[MyActor]' to 'actorOf(new MyActor)'.", cause)
+ }
}, address)
}
- private def newClusterActorRef[T <: Actor](factory: () => T, address: String, deploy: Deploy): ActorRef = {
+ private def newClusterActorRef[T <: Actor](factory: () ⇒ T, address: String, deploy: Deploy): ActorRef = {
newClusterActorRef(factory().getClass.asInstanceOf[Class[T]], address, deploy)
}
-
private def newClusterActorRef[T <: Actor](clazz: Class[T], address: String, deploy: Deploy): ActorRef = {
deploy match {
- case Deploy(_, router, serializerClassName, Clustered(home, replication: Replication, state: State)) =>
+ case Deploy(_, router, serializerClassName, Clustered(home, replication: Replication, state: State)) ⇒
ClusterModule.ensureEnabled()
if (Actor.remote.isRunning) throw new IllegalStateException("Remote server is not running")
val hostname = home match {
- case Host(hostname) => hostname
- case IP(address) => address
- case Node(nodeName) => Config.hostname
+ case Host(hostname) ⇒ hostname
+ case IP(address) ⇒ address
+ case Node(nodeName) ⇒ Config.hostname
}
val replicas = replication match {
- case Replicate(replicas) => replicas
- case AutoReplicate => -1
- case AutoReplicate() => -1
- case NoReplicas => 0
- case NoReplicas() => 0
+ case Replicate(replicas) ⇒ replicas
+ case AutoReplicate ⇒ -1
+ case AutoReplicate() ⇒ -1
+ case NoReplicas ⇒ 0
+ case NoReplicas() ⇒ 0
}
import ClusterModule.node
@@ -405,18 +404,18 @@ object Actor extends ListenerManagement {
def serializerErrorDueTo(reason: String) =
throw new akka.config.ConfigurationException(
"Could not create Serializer object [" + serializerClassName +
- "] for serialization of actor [" + address +
- "] since " + reason)
+ "] for serialization of actor [" + address +
+ "] since " + reason)
//todo: serializer is not used.
val serializer: Serializer = {
if (serializerClassName == "N/A") serializerErrorDueTo("no class name defined in configuration")
val clazz: Class[_] = ReflectiveAccess.getClassFor(serializerClassName) match {
- case Right(clazz) => clazz
- case Left(exception) =>
+ case Right(clazz) ⇒ clazz
+ case Left(exception) ⇒
val cause = exception match {
- case i: InvocationTargetException => i.getTargetException
- case _ => exception
+ case i: InvocationTargetException ⇒ i.getTargetException
+ case _ ⇒ exception
}
serializerErrorDueTo(cause.toString)
}
@@ -433,18 +432,18 @@ object Actor extends ListenerManagement {
node.use(address)
} else {
val routerType = router match {
- case Direct => RouterType.Direct
- case Direct() => RouterType.Direct
- case RoundRobin => RouterType.RoundRobin
- case RoundRobin() => RouterType.RoundRobin
- case Random => RouterType.Random
- case Random() => RouterType.Random
- case LeastCPU => RouterType.LeastCPU
- case LeastCPU() => RouterType.LeastCPU
- case LeastRAM => RouterType.LeastRAM
- case LeastRAM() => RouterType.LeastRAM
- case LeastMessages => RouterType.LeastMessages
- case LeastMessages() => RouterType.LeastMessages
+ case Direct ⇒ RouterType.Direct
+ case Direct() ⇒ RouterType.Direct
+ case RoundRobin ⇒ RouterType.RoundRobin
+ case RoundRobin() ⇒ RouterType.RoundRobin
+ case Random ⇒ RouterType.Random
+ case Random() ⇒ RouterType.Random
+ case LeastCPU ⇒ RouterType.LeastCPU
+ case LeastCPU() ⇒ RouterType.LeastCPU
+ case LeastRAM ⇒ RouterType.LeastRAM
+ case LeastRAM() ⇒ RouterType.LeastRAM
+ case LeastMessages ⇒ RouterType.LeastMessages
+ case LeastMessages() ⇒ RouterType.LeastMessages
}
node.ref(address, routerType)
}
@@ -461,10 +460,10 @@ object Actor extends ListenerManagement {
*/
RemoteActorRef(address, Actor.TIMEOUT, None, ActorType.ScalaActor)
- case invalid => throw new IllegalActorStateException(
+ case invalid ⇒ throw new IllegalActorStateException(
"Could not create actor [" + clazz.getName +
- "] with address [" + address +
- "], not bound to a valid deployment scheme [" + invalid + "]")
+ "] with address [" + address +
+ "], not bound to a valid deployment scheme [" + invalid + "]")
}
}
}
@@ -528,20 +527,21 @@ trait Actor {
* Mainly for internal use, functions as the implicit sender references when invoking
* the 'forward' function.
*/
- @transient implicit val someSelf: Some[ActorRef] = {
+ @transient
+ implicit val someSelf: Some[ActorRef] = {
val optRef = Actor.actorRefInCreation.get
if (optRef.isEmpty) throw new ActorInitializationException(
"ActorRef for instance of actor [" + getClass.getName + "] is not in scope." +
- "\n\tYou can not create an instance of an actor explicitly using 'new MyActor'." +
- "\n\tYou have to use one of the factory methods in the 'Actor' object to create a new actor." +
- "\n\tEither use:" +
- "\n\t\t'val actor = Actor.actorOf[MyActor]', or" +
- "\n\t\t'val actor = Actor.actorOf(new MyActor(..))'")
- Actor.actorRefInCreation.set(None)
- optRef.asInstanceOf[Some[ActorRef]]
+ "\n\tYou can not create an instance of an actor explicitly using 'new MyActor'." +
+ "\n\tYou have to use one of the factory methods in the 'Actor' object to create a new actor." +
+ "\n\tEither use:" +
+ "\n\t\t'val actor = Actor.actorOf[MyActor]', or" +
+ "\n\t\t'val actor = Actor.actorOf(new MyActor(..))'")
+ Actor.actorRefInCreation.set(None)
+ optRef.asInstanceOf[Some[ActorRef]]
}
- /*
+ /*
* Option[ActorRef] representation of the 'self' ActorRef reference.
*
* Mainly for internal use, functions as the implicit sender references when invoking
@@ -576,7 +576,8 @@ trait Actor {
* self.stop(..)
*
*/
- @transient val self: ScalaActorRef = someSelf.get
+ @transient
+ val self: ScalaActorRef = someSelf.get
/**
* User overridable callback/setting.
@@ -645,12 +646,12 @@ trait Actor {
def isDefinedAt(message: Any): Boolean = {
val behaviorStack = self.hotswap
message match { //Same logic as apply(msg) but without the unhandled catch-all
- case l: AutoReceivedMessage => true
+ case l: AutoReceivedMessage ⇒ true
case msg if behaviorStack.nonEmpty &&
- behaviorStack.head.isDefinedAt(msg) => true
+ behaviorStack.head.isDefinedAt(msg) ⇒ true
case msg if behaviorStack.isEmpty &&
- processingBehavior.isDefinedAt(msg) => true
- case _ => false
+ processingBehavior.isDefinedAt(msg) ⇒ true
+ case _ ⇒ false
}
}
@@ -681,26 +682,26 @@ trait Actor {
throw new InvalidMessageException("Message from [" + self.sender + "] to [" + self.toString + "] is null")
val behaviorStack = self.hotswap
msg match {
- case l: AutoReceivedMessage => autoReceiveMessage(l)
+ case l: AutoReceivedMessage ⇒ autoReceiveMessage(l)
case msg if behaviorStack.nonEmpty &&
- behaviorStack.head.isDefinedAt(msg) => behaviorStack.head.apply(msg)
+ behaviorStack.head.isDefinedAt(msg) ⇒ behaviorStack.head.apply(msg)
case msg if behaviorStack.isEmpty &&
- processingBehavior.isDefinedAt(msg) => processingBehavior.apply(msg)
- case unknown => unhandled(unknown) //This is the only line that differs from processingbehavior
+ processingBehavior.isDefinedAt(msg) ⇒ processingBehavior.apply(msg)
+ case unknown ⇒ unhandled(unknown) //This is the only line that differs from processingbehavior
}
}
private final def autoReceiveMessage(msg: AutoReceivedMessage) {
msg match {
- case HotSwap(code, discardOld) => become(code(self), discardOld)
- case RevertHotSwap => unbecome()
- case Exit(dead, reason) => self.handleTrapExit(dead, reason)
- case Link(child) => self.link(child)
- case Unlink(child) => self.unlink(child)
- case UnlinkAndStop(child) => self.unlink(child); child.stop()
- case Restart(reason) => throw reason
- case Kill => throw new ActorKilledException("Kill")
- case PoisonPill =>
+ case HotSwap(code, discardOld) ⇒ become(code(self), discardOld)
+ case RevertHotSwap ⇒ unbecome()
+ case Exit(dead, reason) ⇒ self.handleTrapExit(dead, reason)
+ case Link(child) ⇒ self.link(child)
+ case Unlink(child) ⇒ self.unlink(child)
+ case UnlinkAndStop(child) ⇒ self.unlink(child); child.stop()
+ case Restart(reason) ⇒ throw reason
+ case Kill ⇒ throw new ActorKilledException("Kill")
+ case PoisonPill ⇒
val f = self.senderFuture()
self.stop()
if (f.isDefined) f.get.completeWithException(new ActorKilledException("PoisonPill"))
diff --git a/akka-actor/src/main/scala/akka/actor/ActorRef.scala b/akka-actor/src/main/scala/akka/actor/ActorRef.scala
index bdd781ec38..132e8bd804 100644
--- a/akka-actor/src/main/scala/akka/actor/ActorRef.scala
+++ b/akka-actor/src/main/scala/akka/actor/ActorRef.scala
@@ -14,7 +14,7 @@ import ReflectiveAccess._
import java.net.InetSocketAddress
import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.{ ScheduledFuture, ConcurrentHashMap, TimeUnit }
-import java.util.{ Map => JMap }
+import java.util.{ Map ⇒ JMap }
import scala.reflect.BeanProperty
import scala.collection.immutable.Stack
@@ -85,7 +85,7 @@ abstract class Channel[T] {
*
* @author Jonas Bonér
*/
-trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scalaRef: ScalaActorRef =>
+trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scalaRef: ScalaActorRef ⇒
// Only mutable for RemoteServer in order to maintain identity across nodes
@volatile
protected[akka] var _uuid = newUuid
@@ -140,7 +140,6 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal
def setFaultHandler(handler: FaultHandlingStrategy)
def getFaultHandler: FaultHandlingStrategy
-
/**
* Akka Java API.
* A lifeCycle defines whether the actor will be stopped on error (Temporary) or if it can be restarted (Permanent)
@@ -171,7 +170,7 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal
* The default is also that all actors that are created and spawned from within this actor
* is sharing the same dispatcher as its creator.
*/
- def setDispatcher(dispatcher: MessageDispatcher) {this.dispatcher = dispatcher}
+ def setDispatcher(dispatcher: MessageDispatcher) { this.dispatcher = dispatcher }
def getDispatcher: MessageDispatcher = dispatcher
/**
@@ -220,8 +219,8 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal
* Is the actor running?
*/
def isRunning: Boolean = _status match {
- case ActorRefInternals.BEING_RESTARTED | ActorRefInternals.RUNNING => true
- case _ => false
+ case ActorRefInternals.BEING_RESTARTED | ActorRefInternals.RUNNING ⇒ true
+ case _ ⇒ false
}
/**
@@ -256,7 +255,7 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal
*
*
*/
- def sendOneWay(message: AnyRef):Unit = {
+ def sendOneWay(message: AnyRef): Unit = {
sendOneWay(message, null)
}
@@ -306,9 +305,9 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal
def sendRequestReply(message: AnyRef, timeout: Long, sender: ActorRef): AnyRef = {
!!(message, timeout)(Option(sender)).getOrElse(throw new ActorTimeoutException(
"Message [" + message +
- "]\n\tfrom [" + (if (sender ne null) sender.address else "nowhere") +
- "]\n\twith timeout [" + timeout +
- "]\n\ttimed out."))
+ "]\n\tfrom [" + (if (sender ne null) sender.address else "nowhere") +
+ "]\n\twith timeout [" + timeout +
+ "]\n\ttimed out."))
.asInstanceOf[AnyRef]
}
@@ -317,16 +316,14 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal
* @see sendRequestReplyFuture(message: AnyRef, sender: ActorRef): Future[_]
* Uses the Actors default timeout (setTimeout()) and omits the sender
*/
- def sendRequestReplyFuture[T <: AnyRef](message: AnyRef): Future[T]
- = sendRequestReplyFuture(message, timeout, null).asInstanceOf[Future[T]]
+ def sendRequestReplyFuture[T <: AnyRef](message: AnyRef): Future[T] = sendRequestReplyFuture(message, timeout, null).asInstanceOf[Future[T]]
/**
* Akka Java API.
* @see sendRequestReplyFuture(message: AnyRef, sender: ActorRef): Future[_]
* Uses the Actors default timeout (setTimeout())
*/
- def sendRequestReplyFuture[T <: AnyRef](message: AnyRef, sender: ActorRef): Future[T]
- = sendRequestReplyFuture(message, timeout, sender).asInstanceOf[Future[T]]
+ def sendRequestReplyFuture[T <: AnyRef](message: AnyRef, sender: ActorRef): Future[T] = sendRequestReplyFuture(message, timeout, sender).asInstanceOf[Future[T]]
/**
* Akka Java API.
@@ -339,8 +336,7 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal
* If you are sending messages using sendRequestReplyFuture then you have to use getContext().reply(..)
* to send a reply message to the original sender. If not then the sender will block until the timeout expires.
*/
- def sendRequestReplyFuture[T <: AnyRef](message: AnyRef, timeout: Long, sender: ActorRef): Future[T]
- = !!!(message, timeout)(Option(sender)).asInstanceOf[Future[T]]
+ def sendRequestReplyFuture[T <: AnyRef](message: AnyRef, timeout: Long, sender: ActorRef): Future[T] = !!!(message, timeout)(Option(sender)).asInstanceOf[Future[T]]
/**
* Akka Java API.
@@ -507,7 +503,7 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal
override def equals(that: Any): Boolean = {
that.isInstanceOf[ActorRef] &&
- that.asInstanceOf[ActorRef].uuid == uuid
+ that.asInstanceOf[ActorRef].uuid == uuid
}
override def toString = "Actor[" + address + ":" + uuid + "]"
@@ -518,7 +514,7 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal
*
* @author Jonas Bonér
*/
-class LocalActorRef private[akka] (private[this] val actorFactory: () => Actor, val address: String)
+class LocalActorRef private[akka] (private[this] val actorFactory: () ⇒ Actor, val address: String)
extends ActorRef with ScalaActorRef {
protected[akka] val guard = new ReentrantGuard
@@ -551,7 +547,7 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () => Actor,
__lifeCycle: LifeCycle,
__supervisor: Option[ActorRef],
__hotswap: Stack[PartialFunction[Any, Unit]],
- __factory: () => Actor) = {
+ __factory: () ⇒ Actor) = {
this(__factory, __address)
_uuid = __uuid
timeout = __timeout
@@ -559,7 +555,7 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () => Actor,
lifeCycle = __lifeCycle
_supervisor = __supervisor
hotswap = __hotswap
- setActorSelfFields(actor,this)
+ setActorSelfFields(actor, this)
start()
}
@@ -723,15 +719,16 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () => Actor,
actor(messageHandle.message)
currentMessage = null // reset current message after successful invocation
} catch {
- case e: InterruptedException =>
+ case e: InterruptedException ⇒
currentMessage = null // received message while actor is shutting down, ignore
- case e =>
+ case e ⇒
handleExceptionInDispatch(e, messageHandle.message)
- } finally {
+ }
+ finally {
checkReceiveTimeout // Reschedule receive timeout
}
} catch {
- case e =>
+ case e ⇒
EventHandler.error(e, this, messageHandle.message.toString)
throw e
}
@@ -741,34 +738,34 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () => Actor,
protected[akka] def handleTrapExit(dead: ActorRef, reason: Throwable) {
faultHandler match {
- case AllForOneStrategy(trapExit,maxRetries, within) if trapExit.exists(_.isAssignableFrom(reason.getClass)) =>
+ case AllForOneStrategy(trapExit, maxRetries, within) if trapExit.exists(_.isAssignableFrom(reason.getClass)) ⇒
restartLinkedActors(reason, maxRetries, within)
- case OneForOneStrategy(trapExit,maxRetries, within) if trapExit.exists(_.isAssignableFrom(reason.getClass)) =>
+ case OneForOneStrategy(trapExit, maxRetries, within) if trapExit.exists(_.isAssignableFrom(reason.getClass)) ⇒
dead.restart(reason, maxRetries, within)
- case _ =>
+ case _ ⇒
if (_supervisor.isDefined) notifySupervisorWithMessage(Exit(this, reason))
- else dead.stop()
+ else dead.stop()
}
}
private def requestRestartPermission(maxNrOfRetries: Option[Int], withinTimeRange: Option[Int]): Boolean = {
- val denied = if (maxNrOfRetries.isEmpty && withinTimeRange.isEmpty) { //Immortal
+ val denied = if (maxNrOfRetries.isEmpty && withinTimeRange.isEmpty) { //Immortal
false
} else if (withinTimeRange.isEmpty) { // restrict number of restarts
val retries = maxNrOfRetriesCount + 1
maxNrOfRetriesCount = retries //Increment number of retries
retries > maxNrOfRetries.get
- } else { // cannot restart more than N within M timerange
+ } else { // cannot restart more than N within M timerange
val retries = maxNrOfRetriesCount + 1
val windowStart = restartTimeWindowStartNanos
- val now = System.nanoTime
+ val now = System.nanoTime
//We are within the time window if it isn't the first restart, or if the window hasn't closed
- val insideWindow = if (windowStart == 0) false
- else (now - windowStart) <= TimeUnit.MILLISECONDS.toNanos(withinTimeRange.get)
+ val insideWindow = if (windowStart == 0) false
+ else (now - windowStart) <= TimeUnit.MILLISECONDS.toNanos(withinTimeRange.get)
if (windowStart == 0 || !insideWindow) //(Re-)set the start of the window
restartTimeWindowStartNanos = now
@@ -786,25 +783,25 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () => Actor,
}
protected[akka] def restart(reason: Throwable, maxNrOfRetries: Option[Int], withinTimeRange: Option[Int]) {
- def performRestart() {
+ def performRestart() {
val failedActor = actorInstance.get
failedActor match {
- case p: Proxyable =>
+ case p: Proxyable ⇒
failedActor.preRestart(reason)
failedActor.postRestart(reason)
- case _ =>
+ case _ ⇒
failedActor.preRestart(reason)
val freshActor = newActor
setActorSelfFields(failedActor, null) // Only null out the references if we could instantiate the new actor
- actorInstance.set(freshActor) // Assign it here so if preStart fails, we can null out the sef-refs next call
+ actorInstance.set(freshActor) // Assign it here so if preStart fails, we can null out the sef-refs next call
freshActor.preStart()
freshActor.postRestart(reason)
}
}
def tooManyRestarts() {
- _supervisor.foreach { sup =>
+ _supervisor.foreach { sup ⇒
// can supervisor handle the notification?
val notification = MaximumNumberOfRestartsWithinTimeRangeReached(this, maxNrOfRetries, withinTimeRange, reason)
if (sup.isDefinedAt(notification)) notifySupervisorWithMessage(notification)
@@ -812,31 +809,33 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () => Actor,
stop()
}
- @tailrec def attemptRestart() {
- val success = if (requestRestartPermission(maxNrOfRetries,withinTimeRange)) {
+ @tailrec
+ def attemptRestart() {
+ val success = if (requestRestartPermission(maxNrOfRetries, withinTimeRange)) {
guard.withGuard[Boolean] {
_status = ActorRefInternals.BEING_RESTARTED
lifeCycle match {
- case Temporary =>
- shutDownTemporaryActor(this)
- true
+ case Temporary ⇒
+ shutDownTemporaryActor(this)
+ true
- case _ => // either permanent or none where default is permanent
+ case _ ⇒ // either permanent or none where default is permanent
val success = try {
performRestart()
true
} catch {
- case e =>
+ case e ⇒
EventHandler.error(e, this, "Exception in restart of Actor [%s]".format(toString))
false // an error or exception here should trigger a retry
- } finally {
+ }
+ finally {
currentMessage = null
}
if (success) {
_status = ActorRefInternals.RUNNING
dispatcher.resume(this)
- restartLinkedActors(reason,maxNrOfRetries,withinTimeRange)
+ restartLinkedActors(reason, maxNrOfRetries, withinTimeRange)
}
success
}
@@ -859,8 +858,8 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () => Actor,
val actorRef = i.next
actorRef.lifeCycle match {
// either permanent or none where default is permanent
- case Temporary => shutDownTemporaryActor(actorRef)
- case _ => actorRef.restart(reason, maxNrOfRetries, withinTimeRange)
+ case Temporary ⇒ shutDownTemporaryActor(actorRef)
+ case _ ⇒ actorRef.restart(reason, maxNrOfRetries, withinTimeRange)
}
}
}
@@ -899,15 +898,15 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () => Actor,
if (supervisor.isDefined) notifySupervisorWithMessage(Exit(this, reason))
else {
lifeCycle match {
- case Temporary => shutDownTemporaryActor(this)
- case _ => dispatcher.resume(this) //Resume processing for this actor
+ case Temporary ⇒ shutDownTemporaryActor(this)
+ case _ ⇒ dispatcher.resume(this) //Resume processing for this actor
}
}
}
private def notifySupervisorWithMessage(notification: LifeCycleMessage) {
// FIXME to fix supervisor restart of remote actor for oneway calls, inject a supervisor proxy that can send notification back to client
- _supervisor.foreach { sup =>
+ _supervisor.foreach { sup ⇒
if (sup.isShutdown) { // if supervisor is shut down, game over for all linked actors
//Scoped stop all linked actors, to avoid leaking the 'i' val
{
@@ -925,7 +924,8 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () => Actor,
private def setActorSelfFields(actor: Actor, value: ActorRef) {
- @tailrec def lookupAndSetSelfFields(clazz: Class[_],actor: Actor, value: ActorRef): Boolean = {
+ @tailrec
+ def lookupAndSetSelfFields(clazz: Class[_], actor: Actor, value: ActorRef): Boolean = {
val success = try {
val selfField = clazz.getDeclaredField("self")
val someSelfField = clazz.getDeclaredField("someSelf")
@@ -935,7 +935,7 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () => Actor,
someSelfField.set(actor, if (value ne null) Some(value) else null)
true
} catch {
- case e: NoSuchFieldException => false
+ case e: NoSuchFieldException ⇒ false
}
if (success) true
@@ -999,14 +999,14 @@ private[akka] case class RemoteActorRef private[akka] (
import DeploymentConfig._
val remoteAddress = Deployer.deploymentFor(address) match {
- case Deploy(_, _, _, Clustered(home, _, _)) =>
+ case Deploy(_, _, _, Clustered(home, _, _)) ⇒
val hostname = home match {
- case Host(hostname) => hostname
- case IP(address) => address
- case Node(nodeName) => Config.hostname
+ case Host(hostname) ⇒ hostname
+ case IP(address) ⇒ address
+ case Node(nodeName) ⇒ Config.hostname
}
new InetSocketAddress(hostname, Config.remoteServerPort)
- case _ => throw new IllegalStateException(
+ case _ ⇒ throw new IllegalStateException(
"Actor with Address [" + address + "] is not bound to a Clustered Deployment")
}
@@ -1108,7 +1108,7 @@ trait ActorRefShared {
* There are implicit conversions in ../actor/Implicits.scala
* from ActorRef -> ScalaActorRef and back
*/
-trait ScalaActorRef extends ActorRefShared { ref: ActorRef =>
+trait ScalaActorRef extends ActorRefShared { ref: ActorRef ⇒
/**
* Address for actor, must be a unique one.
@@ -1202,7 +1202,7 @@ trait ScalaActorRef extends ActorRefShared { ref: ActorRef =>
try {
future.await
} catch {
- case e: FutureTimeoutException =>
+ case e: FutureTimeoutException ⇒
if (isMessageJoinPoint) {
EventHandler.error(e, this, e.getMessage)
throw e
diff --git a/akka-actor/src/main/scala/akka/actor/ActorRegistry.scala b/akka-actor/src/main/scala/akka/actor/ActorRegistry.scala
index 92f0667af6..032ba917f7 100644
--- a/akka-actor/src/main/scala/akka/actor/ActorRegistry.scala
+++ b/akka-actor/src/main/scala/akka/actor/ActorRegistry.scala
@@ -8,11 +8,11 @@ import scala.collection.mutable.ListBuffer
import scala.reflect.Manifest
import annotation.tailrec
-import java.util.concurrent.{ConcurrentSkipListSet, ConcurrentHashMap}
-import java.util.{Set => JSet}
+import java.util.concurrent.{ ConcurrentSkipListSet, ConcurrentHashMap }
+import java.util.{ Set ⇒ JSet }
import akka.util.ReflectiveAccess._
-import akka.util.{ReflectiveAccess, ReadWriteGuard, ListenerManagement}
+import akka.util.{ ReflectiveAccess, ReadWriteGuard, ListenerManagement }
import akka.serialization._
/**
@@ -33,9 +33,9 @@ case class ActorUnregistered(address: String, actor: ActorRef) extends ActorRegi
private[actor] final class ActorRegistry private[actor] () extends ListenerManagement {
//private val isClusterEnabled = ReflectiveAccess.isClusterEnabled
- private val actorsByAddress = new ConcurrentHashMap[String, ActorRef]
- private val actorsByUuid = new ConcurrentHashMap[String, ActorRef]
- private val guard = new ReadWriteGuard
+ private val actorsByAddress = new ConcurrentHashMap[String, ActorRef]
+ private val actorsByUuid = new ConcurrentHashMap[String, ActorRef]
+ private val guard = new ReadWriteGuard
val local = new LocalActorRegistry(actorsByAddress, actorsByUuid)
@@ -44,8 +44,8 @@ private[actor] final class ActorRegistry private[actor] () extends ListenerManag
*/
def actorFor(address: String): Option[ActorRef] = {
if (actorsByAddress.containsKey(address)) Some(actorsByAddress.get(address))
-// else if (isClusterEnabled) ClusterModule.node.use(address) // FIXME uncomment and fix
- else None
+ // else if (isClusterEnabled) ClusterModule.node.use(address) // FIXME uncomment and fix
+ else None
}
/**
@@ -150,7 +150,7 @@ class LocalActorRegistry(
*/
def actorFor(address: String): Option[ActorRef] = {
if (actorsByAddress.containsKey(address)) Some(actorsByAddress.get(address))
- else None
+ else None
}
/**
@@ -159,7 +159,7 @@ class LocalActorRegistry(
private[akka] def actorFor(uuid: Uuid): Option[ActorRef] = {
val uuidAsString = uuid.toString
if (actorsByUuid.containsKey(uuidAsString)) Some(actorsByUuid.get(uuidAsString))
- else None
+ else None
}
/**
@@ -181,12 +181,12 @@ class LocalActorRegistry(
/**
* Returns all actors in the system.
*/
- def actors: Array[ActorRef] = filter(_ => true)
+ def actors: Array[ActorRef] = filter(_ ⇒ true)
/**
* Invokes a function for all actors.
*/
- def foreach(f: (ActorRef) => Unit) = {
+ def foreach(f: (ActorRef) ⇒ Unit) = {
val elements = actorsByAddress.elements
while (elements.hasMoreElements) f(elements.nextElement)
}
@@ -195,7 +195,7 @@ class LocalActorRegistry(
* Invokes the function on all known actors until it returns Some
* Returns None if the function never returns Some
*/
- def find[T](f: PartialFunction[ActorRef, T]) : Option[T] = {
+ def find[T](f: PartialFunction[ActorRef, T]): Option[T] = {
val elements = actorsByAddress.elements
while (elements.hasMoreElements) {
val element = elements.nextElement
@@ -207,8 +207,8 @@ class LocalActorRegistry(
/**
* Finds all actors that satisfy a predicate.
*/
- def filter(p: ActorRef => Boolean): Array[ActorRef] = {
- val all = new ListBuffer[ActorRef]
+ def filter(p: ActorRef ⇒ Boolean): Array[ActorRef] = {
+ val all = new ListBuffer[ActorRef]
val elements = actorsByAddress.elements
while (elements.hasMoreElements) {
val actorId = elements.nextElement
@@ -222,12 +222,12 @@ class LocalActorRegistry(
/**
* Returns all typed actors in the system.
*/
- def typedActors: Array[AnyRef] = filterTypedActors(_ => true)
+ def typedActors: Array[AnyRef] = filterTypedActors(_ ⇒ true)
/**
* Invokes a function for all typed actors.
*/
- def foreachTypedActor(f: (AnyRef) => Unit) = {
+ def foreachTypedActor(f: (AnyRef) ⇒ Unit) = {
TypedActorModule.ensureEnabled
val elements = actorsByAddress.elements
while (elements.hasMoreElements) {
@@ -240,7 +240,7 @@ class LocalActorRegistry(
* Invokes the function on all known typed actors until it returns Some
* Returns None if the function never returns Some
*/
- def findTypedActor[T](f: PartialFunction[AnyRef,T]) : Option[T] = {
+ def findTypedActor[T](f: PartialFunction[AnyRef, T]): Option[T] = {
TypedActorModule.ensureEnabled
val elements = actorsByAddress.elements
while (elements.hasMoreElements) {
@@ -253,7 +253,7 @@ class LocalActorRegistry(
/**
* Finds all typed actors that satisfy a predicate.
*/
- def filterTypedActors(p: AnyRef => Boolean): Array[AnyRef] = {
+ def filterTypedActors(p: AnyRef ⇒ Boolean): Array[AnyRef] = {
TypedActorModule.ensureEnabled
val all = new ListBuffer[AnyRef]
val elements = actorsByAddress.elements
@@ -281,7 +281,7 @@ class LocalActorRegistry(
*
* @author Viktor Klang
*/
-class Index[K <: AnyRef,V <: AnyRef : Manifest] {
+class Index[K <: AnyRef, V <: AnyRef: Manifest] {
private val Naught = Array[V]() //Nil for Arrays
private val container = new ConcurrentHashMap[K, JSet[V]]
private val emptySet = new ConcurrentSkipListSet[V]
@@ -292,7 +292,8 @@ class Index[K <: AnyRef,V <: AnyRef : Manifest] {
*/
def put(key: K, value: V): Boolean = {
//Tailrecursive spin-locking put
- @tailrec def spinPut(k: K, v: V): Boolean = {
+ @tailrec
+ def spinPut(k: K, v: V): Boolean = {
var retry = false
var added = false
val set = container get k
@@ -310,7 +311,7 @@ class Index[K <: AnyRef,V <: AnyRef : Manifest] {
newSet add v
// Parry for two simultaneous putIfAbsent(id,newSet)
- val oldSet = container.putIfAbsent(k,newSet)
+ val oldSet = container.putIfAbsent(k, newSet)
if (oldSet ne null) {
oldSet.synchronized {
if (oldSet.isEmpty) retry = true //IF the set is empty then it has been removed, so signal retry
@@ -342,7 +343,7 @@ class Index[K <: AnyRef,V <: AnyRef : Manifest] {
* @return Some(value) for the first matching value where the supplied function returns true for the given key,
* if no matches it returns None
*/
- def findValue(key: K)(f: (V) => Boolean): Option[V] = {
+ def findValue(key: K)(f: (V) ⇒ Boolean): Option[V] = {
import scala.collection.JavaConversions._
val set = container get key
if (set ne null) set.iterator.find(f)
@@ -352,10 +353,10 @@ class Index[K <: AnyRef,V <: AnyRef : Manifest] {
/**
* Applies the supplied function to all keys and their values
*/
- def foreach(fun: (K,V) => Unit) {
+ def foreach(fun: (K, V) ⇒ Unit) {
import scala.collection.JavaConversions._
- container.entrySet foreach {
- (e) => e.getValue.foreach(fun(e.getKey,_))
+ container.entrySet foreach { (e) ⇒
+ e.getValue.foreach(fun(e.getKey, _))
}
}
@@ -369,8 +370,8 @@ class Index[K <: AnyRef,V <: AnyRef : Manifest] {
if (set ne null) {
set.synchronized {
if (set.remove(value)) { //If we can remove the value
- if (set.isEmpty) //and the set becomes empty
- container.remove(key,emptySet) //We try to remove the key if it's mapped to an empty set
+ if (set.isEmpty) //and the set becomes empty
+ container.remove(key, emptySet) //We try to remove the key if it's mapped to an empty set
true //Remove succeeded
} else false //Remove failed
@@ -386,5 +387,5 @@ class Index[K <: AnyRef,V <: AnyRef : Manifest] {
/**
* Removes all keys and all values
*/
- def clear = foreach { case (k, v) => remove(k, v) }
+ def clear = foreach { case (k, v) ⇒ remove(k, v) }
}
diff --git a/akka-actor/src/main/scala/akka/actor/BootableActorLoaderService.scala b/akka-actor/src/main/scala/akka/actor/BootableActorLoaderService.scala
index 73fa2e768e..de1bffb7d2 100644
--- a/akka-actor/src/main/scala/akka/actor/BootableActorLoaderService.scala
+++ b/akka-actor/src/main/scala/akka/actor/BootableActorLoaderService.scala
@@ -5,10 +5,10 @@
package akka.actor
import java.io.File
-import java.net.{URL, URLClassLoader}
+import java.net.{ URL, URLClassLoader }
import java.util.jar.JarFile
-import akka.util.{Bootable}
+import akka.util.{ Bootable }
import akka.config.Config._
/**
@@ -19,7 +19,7 @@ trait BootableActorLoaderService extends Bootable {
val BOOT_CLASSES = config.getList("akka.boot")
lazy val applicationLoader: Option[ClassLoader] = createApplicationClassLoader
- protected def createApplicationClassLoader : Option[ClassLoader] = Some({
+ protected def createApplicationClassLoader: Option[ClassLoader] = Some({
if (HOME.isDefined) {
val DEPLOY = HOME.get + "/deploy"
val DEPLOY_DIR = new File(DEPLOY)
@@ -29,7 +29,7 @@ trait BootableActorLoaderService extends Bootable {
val filesToDeploy = DEPLOY_DIR.listFiles.toArray.toList
.asInstanceOf[List[File]].filter(_.getName.endsWith(".jar"))
var dependencyJars: List[URL] = Nil
- filesToDeploy.map { file =>
+ filesToDeploy.map { file ⇒
val jarFile = new JarFile(file)
val en = jarFile.entries
while (en.hasMoreElements) {
@@ -41,14 +41,14 @@ trait BootableActorLoaderService extends Bootable {
val toDeploy = filesToDeploy.map(_.toURI.toURL)
val allJars = toDeploy ::: dependencyJars
- new URLClassLoader(allJars.toArray,Thread.currentThread.getContextClassLoader)
+ new URLClassLoader(allJars.toArray, Thread.currentThread.getContextClassLoader)
} else Thread.currentThread.getContextClassLoader
})
abstract override def onLoad = {
super.onLoad
- for (loader <- applicationLoader; clazz <- BOOT_CLASSES) {
+ for (loader ← applicationLoader; clazz ← BOOT_CLASSES) {
loader.loadClass(clazz).newInstance
}
}
diff --git a/akka-actor/src/main/scala/akka/actor/Deployer.scala b/akka-actor/src/main/scala/akka/actor/Deployer.scala
index 6ecb2ac913..cb35f62a9a 100644
--- a/akka-actor/src/main/scala/akka/actor/Deployer.scala
+++ b/akka-actor/src/main/scala/akka/actor/Deployer.scala
@@ -10,7 +10,7 @@ import java.util.concurrent.ConcurrentHashMap
import akka.event.EventHandler
import akka.actor.DeploymentConfig._
-import akka.config.{ConfigurationException, Config}
+import akka.config.{ ConfigurationException, Config }
import akka.util.ReflectiveAccess
import akka.AkkaException
@@ -147,8 +147,8 @@ object Deployer {
}
def isLocal(deployment: Deploy): Boolean = deployment match {
- case Deploy(_, _, _, Local) => true
- case _ => false
+ case Deploy(_, _, _, Local) ⇒ true
+ case _ ⇒ false
}
def isClustered(deployment: Deploy): Boolean = isLocal(deployment)
@@ -162,8 +162,8 @@ object Deployer {
*/
private[akka] def deploymentFor(address: String): Deploy = {
lookupDeploymentFor(address) match {
- case Some(deployment) => deployment
- case None => thrownNoDeploymentBoundException(address)
+ case Some(deployment) ⇒ deployment
+ case None ⇒ thrownNoDeploymentBoundException(address)
}
}
@@ -175,11 +175,11 @@ object Deployer {
try {
lookupInConfig(address)
} catch {
- case e: ConfigurationException =>
+ case e: ConfigurationException ⇒
EventHandler.error(e, this, e.getMessage)
throw e
}
- newDeployment foreach { d =>
+ newDeployment foreach { d ⇒
if (d eq null) {
val e = new IllegalStateException("Deployment for address [" + address + "] is null")
EventHandler.error(e, this, e.getMessage)
@@ -193,18 +193,18 @@ object Deployer {
private[akka] def deploymentsInConfig: List[Deploy] = {
for {
- address <- addressesInConfig
- deployment <- lookupInConfig(address)
+ address ← addressesInConfig
+ deployment ← lookupInConfig(address)
} yield deployment
}
private[akka] def addressesInConfig: List[String] = {
val deploymentPath = "akka.actor.deployment"
Config.config.getSection(deploymentPath) match {
- case None => Nil
- case Some(addressConfig) =>
+ case None ⇒ Nil
+ case Some(addressConfig) ⇒
addressConfig.map.keySet
- .map(path => path.substring(0, path.indexOf(".")))
+ .map(path ⇒ path.substring(0, path.indexOf(".")))
.toSet.toList // toSet to force uniqueness
}
}
@@ -219,25 +219,25 @@ object Deployer {
// --------------------------------
val addressPath = "akka.actor.deployment." + address
Config.config.getSection(addressPath) match {
- case None => Some(Deploy(address, Direct, "N/A", Local))
- case Some(addressConfig) =>
+ case None ⇒ Some(Deploy(address, Direct, "N/A", Local))
+ case Some(addressConfig) ⇒
// --------------------------------
// akka.actor.deployment..router
// --------------------------------
val router = addressConfig.getString("router", "direct") match {
- case "direct" => Direct
- case "round-robin" => RoundRobin
- case "random" => Random
- case "least-cpu" => LeastCPU
- case "least-ram" => LeastRAM
- case "least-messages" => LeastMessages
- case customRouterClassName =>
+ case "direct" ⇒ Direct
+ case "round-robin" ⇒ RoundRobin
+ case "random" ⇒ Random
+ case "least-cpu" ⇒ LeastCPU
+ case "least-ram" ⇒ LeastRAM
+ case "least-messages" ⇒ LeastMessages
+ case customRouterClassName ⇒
val customRouter = try {
Class.forName(customRouterClassName).newInstance.asInstanceOf[AnyRef]
} catch {
- case e => throw new ConfigurationException(
- "Config option [" + addressPath + ".router] needs to be one of " +
+ case e ⇒ throw new ConfigurationException(
+ "Config option [" + addressPath + ".router] needs to be one of " +
"[\"direct\", \"round-robin\", \"random\", \"least-cpu\", \"least-ram\", \"least-messages\" or FQN of router class]")
}
CustomRouter(customRouter)
@@ -252,33 +252,33 @@ object Deployer {
// akka.actor.deployment..clustered
// --------------------------------
addressConfig.getSection("clustered") match {
- case None =>
+ case None ⇒
Some(Deploy(address, router, "N/A", Local)) // deploy locally
- case Some(clusteredConfig) =>
+ case Some(clusteredConfig) ⇒
// --------------------------------
// akka.actor.deployment..clustered.home
// --------------------------------
val home = clusteredConfig.getString("home", "") match {
- case "" => Host("localhost")
- case home =>
+ case "" ⇒ Host("localhost")
+ case home ⇒
def raiseHomeConfigError() = throw new ConfigurationException(
- "Config option [" + addressPath +
+ "Config option [" + addressPath +
".clustered.home] needs to be on format 'host:', 'ip:'' or 'node:', was [" +
home + "]")
if (!(home.startsWith("host:") || home.startsWith("node:") || home.startsWith("ip:"))) raiseHomeConfigError()
val tokenizer = new java.util.StringTokenizer(home, ":")
- val protocol = tokenizer.nextElement
- val address = tokenizer.nextElement.asInstanceOf[String]
+ val protocol = tokenizer.nextElement
+ val address = tokenizer.nextElement.asInstanceOf[String]
protocol match {
- case "host" => Host(address)
- case "node" => Node(address)
- case "ip" => IP(address)
- case _ => raiseHomeConfigError()
+ case "host" ⇒ Host(address)
+ case "node" ⇒ Node(address)
+ case "ip" ⇒ IP(address)
+ case _ ⇒ raiseHomeConfigError()
}
}
@@ -286,17 +286,17 @@ object Deployer {
// akka.actor.deployment..clustered.replicas
// --------------------------------
val replicas = clusteredConfig.getAny("replicas", "1") match {
- case "auto" => AutoReplicate
- case "1" => NoReplicas
- case nrOfReplicas: String =>
+ case "auto" ⇒ AutoReplicate
+ case "1" ⇒ NoReplicas
+ case nrOfReplicas: String ⇒
try {
Replicate(nrOfReplicas.toInt)
} catch {
- case e: NumberFormatException =>
+ case e: NumberFormatException ⇒
throw new ConfigurationException(
"Config option [" + addressPath +
- ".clustered.replicas] needs to be either [\"auto\"] or [1-N] - was [" +
- nrOfReplicas + "]")
+ ".clustered.replicas] needs to be either [\"auto\"] or [1-N] - was [" +
+ nrOfReplicas + "]")
}
}
@@ -315,8 +315,8 @@ object Deployer {
private def throwDeploymentBoundException(deployment: Deploy): Nothing = {
val e = new DeploymentAlreadyBoundException(
"Address [" + deployment.address +
- "] already bound to [" + deployment +
- "]. You have to invoke 'undeploy(deployment) first.")
+ "] already bound to [" + deployment +
+ "]. You have to invoke 'undeploy(deployment) first.")
EventHandler.error(e, this, e.getMessage)
throw e
}
@@ -386,6 +386,6 @@ object Address {
}
}
-class DeploymentException private[akka](message: String) extends AkkaException(message)
-class DeploymentAlreadyBoundException private[akka](message: String) extends AkkaException(message)
-class NoDeploymentBoundException private[akka](message: String) extends AkkaException(message)
+class DeploymentException private[akka] (message: String) extends AkkaException(message)
+class DeploymentAlreadyBoundException private[akka] (message: String) extends AkkaException(message)
+class NoDeploymentBoundException private[akka] (message: String) extends AkkaException(message)
diff --git a/akka-actor/src/main/scala/akka/actor/FSM.scala b/akka-actor/src/main/scala/akka/actor/FSM.scala
index f4fff52035..60e2b10c67 100644
--- a/akka-actor/src/main/scala/akka/actor/FSM.scala
+++ b/akka-actor/src/main/scala/akka/actor/FSM.scala
@@ -48,7 +48,7 @@ object FSM {
* reminder what the new state is.
*/
object -> {
- def unapply[S](in : (S, S)) = Some(in)
+ def unapply[S](in: (S, S)) = Some(in)
}
/*
@@ -139,7 +139,7 @@ object FSM {
*
*/
trait FSM[S, D] extends ListenerManagement {
- this: Actor =>
+ this: Actor ⇒
import FSM._
@@ -147,9 +147,11 @@ trait FSM[S, D] extends ListenerManagement {
type Timeout = Option[Duration]
type TransitionHandler = PartialFunction[(S, S), Unit]
- /******************************************
+ /**
+ * ****************************************
* DSL
- ******************************************/
+ * ****************************************
+ */
/**
* Insert a new StateFunction at the end of the processing chain for the
@@ -261,7 +263,7 @@ trait FSM[S, D] extends ListenerManagement {
* Set state timeout explicitly. This method can safely be used from within a
* state handler.
*/
- protected final def setStateTimeout(state : S, timeout : Timeout) {
+ protected final def setStateTimeout(state: S, timeout: Timeout) {
stateTimeouts(state) = timeout
}
@@ -298,16 +300,16 @@ trait FSM[S, D] extends ListenerManagement {
* Convenience wrapper for using a total function instead of a partial
* function literal. To be used with onTransition.
*/
- implicit protected final def total2pf(transitionHandler: (S, S) => Unit) =
+ implicit protected final def total2pf(transitionHandler: (S, S) ⇒ Unit) =
new PartialFunction[(S, S), Unit] {
- def isDefinedAt(in : (S, S)) = true
- def apply(in : (S, S)) { transitionHandler(in._1, in._2) }
+ def isDefinedAt(in: (S, S)) = true
+ def apply(in: (S, S)) { transitionHandler(in._1, in._2) }
}
/**
* Set handler which is called upon termination of this FSM actor.
*/
- protected final def onTermination(terminationHandler: PartialFunction[StopEvent[S,D], Unit]) = {
+ protected final def onTermination(terminationHandler: PartialFunction[StopEvent[S, D], Unit]) = {
terminateEvent = terminationHandler
}
@@ -326,9 +328,11 @@ trait FSM[S, D] extends ListenerManagement {
makeTransition(currentState)
}
- /******************************************************************
+ /**
+ * ****************************************************************
* PRIVATE IMPLEMENTATION DETAILS
- ******************************************************************/
+ * ****************************************************************
+ */
/*
* FSM State data and current timeout handling
@@ -362,7 +366,7 @@ trait FSM[S, D] extends ListenerManagement {
* unhandled event handler
*/
private val handleEventDefault: StateFunction = {
- case Event(value, stateData) =>
+ case Event(value, stateData) ⇒
stay
}
private var handleEvent: StateFunction = handleEventDefault
@@ -370,50 +374,52 @@ trait FSM[S, D] extends ListenerManagement {
/*
* termination handling
*/
- private var terminateEvent: PartialFunction[StopEvent[S,D], Unit] = {
- case StopEvent(Failure(cause), _, _) =>
- case StopEvent(reason, _, _) =>
+ private var terminateEvent: PartialFunction[StopEvent[S, D], Unit] = {
+ case StopEvent(Failure(cause), _, _) ⇒
+ case StopEvent(reason, _, _) ⇒
}
/*
* transition handling
*/
private var transitionEvent: List[TransitionHandler] = Nil
- private def handleTransition(prev : S, next : S) {
+ private def handleTransition(prev: S, next: S) {
val tuple = (prev, next)
- for (te <- transitionEvent) { if (te.isDefinedAt(tuple)) te(tuple) }
+ for (te ← transitionEvent) { if (te.isDefinedAt(tuple)) te(tuple) }
}
// ListenerManagement shall not start() or stop() listener actors
override protected val manageLifeCycleOfListeners = false
- /*********************************************
+ /**
+ * *******************************************
* Main actor receive() method
- *********************************************/
+ * *******************************************
+ */
override final protected def receive: Receive = {
- case TimeoutMarker(gen) =>
+ case TimeoutMarker(gen) ⇒
if (generation == gen) {
processEvent(StateTimeout)
}
- case t@Timer(name, msg, repeat) =>
+ case t@Timer(name, msg, repeat) ⇒
if (timerActive_?(name)) {
processEvent(msg)
if (!repeat) {
timers -= name
}
}
- case SubscribeTransitionCallBack(actorRef) =>
+ case SubscribeTransitionCallBack(actorRef) ⇒
addListener(actorRef)
// send current state back as reference point
try {
actorRef ! CurrentState(self, currentState.stateName)
} catch {
- case e : ActorInitializationException =>
+ case e: ActorInitializationException ⇒
EventHandler.warning(this, "trying to register not running listener")
}
- case UnsubscribeTransitionCallBack(actorRef) =>
+ case UnsubscribeTransitionCallBack(actorRef) ⇒
removeListener(actorRef)
- case value => {
+ case value ⇒ {
if (timeoutFuture.isDefined) {
timeoutFuture.get.cancel(true)
timeoutFuture = None
@@ -427,14 +433,14 @@ trait FSM[S, D] extends ListenerManagement {
val event = Event(value, currentState.stateData)
val stateFunc = stateFunctions(currentState.stateName)
val nextState = if (stateFunc isDefinedAt event) {
- stateFunc(event)
- } else {
- // handleEventDefault ensures that this is always defined
- handleEvent(event)
- }
+ stateFunc(event)
+ } else {
+ // handleEventDefault ensures that this is always defined
+ handleEvent(event)
+ }
nextState.stopReason match {
- case Some(reason) => terminate(reason)
- case None => makeTransition(nextState)
+ case Some(reason) ⇒ terminate(reason)
+ case None ⇒ makeTransition(nextState)
}
}
@@ -468,7 +474,7 @@ trait FSM[S, D] extends ListenerManagement {
case class Event[D](event: Any, stateData: D)
object Ev {
- def unapply[D](e : Event[D]) : Option[Any] = Some(e.event)
+ def unapply[D](e: Event[D]): Option[Any] = Some(e.event)
}
case class State(stateName: S, stateData: D, timeout: Timeout = None) {
@@ -489,8 +495,8 @@ trait FSM[S, D] extends ListenerManagement {
*/
def replying(replyValue: Any): State = {
self.sender match {
- case Some(sender) => sender ! replyValue
- case None =>
+ case Some(sender) ⇒ sender ! replyValue
+ case None ⇒
}
this
}
diff --git a/akka-actor/src/main/scala/akka/actor/Scheduler.scala b/akka-actor/src/main/scala/akka/actor/Scheduler.scala
index 1c1da8e7a2..785445f9c4 100644
--- a/akka-actor/src/main/scala/akka/actor/Scheduler.scala
+++ b/akka-actor/src/main/scala/akka/actor/Scheduler.scala
@@ -27,7 +27,8 @@ object Scheduler {
case class SchedulerException(msg: String, e: Throwable) extends RuntimeException(msg, e)
- @volatile private var service = Executors.newSingleThreadScheduledExecutor(SchedulerThreadFactory)
+ @volatile
+ private var service = Executors.newSingleThreadScheduledExecutor(SchedulerThreadFactory)
/**
* Schedules to send the specified message to the receiver after initialDelay and then repeated after delay
@@ -38,7 +39,7 @@ object Scheduler {
new Runnable { def run = receiver ! message },
initialDelay, delay, timeUnit).asInstanceOf[ScheduledFuture[AnyRef]]
} catch {
- case e: Exception =>
+ case e: Exception ⇒
val error = SchedulerException(message + " could not be scheduled on " + receiver, e)
EventHandler.error(error, this, "%s @ %s".format(receiver, message))
throw error
@@ -49,7 +50,7 @@ object Scheduler {
* Schedules to run specified function to the receiver after initialDelay and then repeated after delay,
* avoid blocking operations since this is executed in the schedulers thread
*/
- def schedule(f: () => Unit, initialDelay: Long, delay: Long, timeUnit: TimeUnit): ScheduledFuture[AnyRef] =
+ def schedule(f: () ⇒ Unit, initialDelay: Long, delay: Long, timeUnit: TimeUnit): ScheduledFuture[AnyRef] =
schedule(new Runnable { def run = f() }, initialDelay, delay, timeUnit)
/**
@@ -60,7 +61,7 @@ object Scheduler {
try {
service.scheduleAtFixedRate(runnable, initialDelay, delay, timeUnit).asInstanceOf[ScheduledFuture[AnyRef]]
} catch {
- case e: Exception =>
+ case e: Exception ⇒
val error = SchedulerException("Failed to schedule a Runnable", e)
EventHandler.error(error, this, error.getMessage)
throw error
@@ -76,8 +77,8 @@ object Scheduler {
new Runnable { def run = receiver ! message },
delay, timeUnit).asInstanceOf[ScheduledFuture[AnyRef]]
} catch {
- case e: Exception =>
- val error = SchedulerException( message + " could not be scheduleOnce'd on " + receiver, e)
+ case e: Exception ⇒
+ val error = SchedulerException(message + " could not be scheduleOnce'd on " + receiver, e)
EventHandler.error(e, this, receiver + " @ " + message)
throw error
}
@@ -87,7 +88,7 @@ object Scheduler {
* Schedules a function to be run after delay,
* avoid blocking operations since the runnable is executed in the schedulers thread
*/
- def scheduleOnce(f: () => Unit, delay: Long, timeUnit: TimeUnit): ScheduledFuture[AnyRef] =
+ def scheduleOnce(f: () ⇒ Unit, delay: Long, timeUnit: TimeUnit): ScheduledFuture[AnyRef] =
scheduleOnce(new Runnable { def run = f() }, delay, timeUnit)
/**
@@ -96,9 +97,9 @@ object Scheduler {
*/
def scheduleOnce(runnable: Runnable, delay: Long, timeUnit: TimeUnit): ScheduledFuture[AnyRef] = {
try {
- service.schedule(runnable,delay, timeUnit).asInstanceOf[ScheduledFuture[AnyRef]]
+ service.schedule(runnable, delay, timeUnit).asInstanceOf[ScheduledFuture[AnyRef]]
} catch {
- case e: Exception =>
+ case e: Exception ⇒
val error = SchedulerException("Failed to scheduleOnce a Runnable", e)
EventHandler.error(e, this, error.getMessage)
throw error
diff --git a/akka-actor/src/main/scala/akka/actor/Supervisor.scala b/akka-actor/src/main/scala/akka/actor/Supervisor.scala
index 86dd283c52..9d32fdfd78 100644
--- a/akka-actor/src/main/scala/akka/actor/Supervisor.scala
+++ b/akka-actor/src/main/scala/akka/actor/Supervisor.scala
@@ -9,11 +9,11 @@ import akka.util._
import ReflectiveAccess._
import Actor._
-import java.util.concurrent.{CopyOnWriteArrayList, ConcurrentHashMap}
+import java.util.concurrent.{ CopyOnWriteArrayList, ConcurrentHashMap }
import java.net.InetSocketAddress
import akka.config.Supervision._
-class SupervisorException private[akka](message: String, cause: Throwable = null) extends AkkaException(message, cause)
+class SupervisorException private[akka] (message: String, cause: Throwable = null) extends AkkaException(message, cause)
/**
* Factory object for creating supervisors declarative. It creates instances of the 'Supervisor' class.
@@ -98,13 +98,13 @@ case class SupervisorFactory(val config: SupervisorConfig) {
*
* @author Jonas Bonér
*/
-sealed class Supervisor(handler: FaultHandlingStrategy, maxRestartsHandler: (ActorRef, MaximumNumberOfRestartsWithinTimeRangeReached) => Unit) {
+sealed class Supervisor(handler: FaultHandlingStrategy, maxRestartsHandler: (ActorRef, MaximumNumberOfRestartsWithinTimeRangeReached) ⇒ Unit) {
import Supervisor._
private val _childActors = new ConcurrentHashMap[String, List[ActorRef]]
private val _childSupervisors = new CopyOnWriteArrayList[Supervisor]
- private[akka] val supervisor = actorOf(new SupervisorActor(handler,maxRestartsHandler)).start()
+ private[akka] val supervisor = actorOf(new SupervisorActor(handler, maxRestartsHandler)).start()
def uuid = supervisor.uuid
@@ -125,11 +125,11 @@ sealed class Supervisor(handler: FaultHandlingStrategy, maxRestartsHandler: (Act
_childActors.values.toArray.toList.asInstanceOf[List[Supervisor]]
def configure(config: SupervisorConfig): Unit = config match {
- case SupervisorConfig(_, servers, _) =>
+ case SupervisorConfig(_, servers, _) ⇒
- servers.map(server =>
+ servers.map(server ⇒
server match {
- case Supervise(actorRef, lifeCycle, registerAsRemoteService) =>
+ case Supervise(actorRef, lifeCycle, registerAsRemoteService) ⇒
actorRef.start()
val className = actorRef.actor.getClass.getName
val currentActors = {
@@ -142,7 +142,7 @@ sealed class Supervisor(handler: FaultHandlingStrategy, maxRestartsHandler: (Act
supervisor.link(actorRef)
if (registerAsRemoteService)
Actor.remote.register(actorRef)
- case supervisorConfig @ SupervisorConfig(_, _,_) => // recursive supervisor configuration
+ case supervisorConfig@SupervisorConfig(_, _, _) ⇒ // recursive supervisor configuration
val childSupervisor = Supervisor(supervisorConfig)
supervisor.link(childSupervisor.supervisor)
_childSupervisors.add(childSupervisor)
@@ -155,13 +155,12 @@ sealed class Supervisor(handler: FaultHandlingStrategy, maxRestartsHandler: (Act
*
* @author Jonas Bonér
*/
-final class SupervisorActor private[akka] (handler: FaultHandlingStrategy, maxRestartsHandler: (ActorRef,MaximumNumberOfRestartsWithinTimeRangeReached) => Unit) extends Actor {
+final class SupervisorActor private[akka] (handler: FaultHandlingStrategy, maxRestartsHandler: (ActorRef, MaximumNumberOfRestartsWithinTimeRangeReached) ⇒ Unit) extends Actor {
self.faultHandler = handler
-
override def postStop(): Unit = {
val i = self.linkedActors.values.iterator
- while(i.hasNext) {
+ while (i.hasNext) {
val ref = i.next
ref.stop()
self.unlink(ref)
@@ -169,8 +168,8 @@ final class SupervisorActor private[akka] (handler: FaultHandlingStrategy, maxRe
}
def receive = {
- case max@MaximumNumberOfRestartsWithinTimeRangeReached(_,_,_,_) => maxRestartsHandler(self, max)
- case unknown => throw new SupervisorException(
+ case max@MaximumNumberOfRestartsWithinTimeRangeReached(_, _, _, _) ⇒ maxRestartsHandler(self, max)
+ case unknown ⇒ throw new SupervisorException(
"SupervisorActor can not respond to messages.\n\tUnknown message [" + unknown + "]")
}
}
diff --git a/akka-actor/src/main/scala/akka/actor/UntypedActor.scala b/akka-actor/src/main/scala/akka/actor/UntypedActor.scala
index 41585dc602..d561ce6221 100644
--- a/akka-actor/src/main/scala/akka/actor/UntypedActor.scala
+++ b/akka-actor/src/main/scala/akka/actor/UntypedActor.scala
@@ -4,7 +4,7 @@
package akka.actor
-import akka.japi.{Creator, Procedure}
+import akka.japi.{ Creator, Procedure }
/**
* Subclass this abstract class to create a MDB-style untyped actor.
@@ -70,18 +70,18 @@ abstract class UntypedActor extends Actor {
/**
* Returns the 'self' reference with the API.
*/
- def context(): ActorRef = self
+ def context(): ActorRef = self
/**
* Java API for become
*/
- def become(behavior: Procedure[Any]):Unit = become(behavior,false)
+ def become(behavior: Procedure[Any]): Unit = become(behavior, false)
/*
* Java API for become with optional discardOld
*/
def become(behavior: Procedure[Any], discardOld: Boolean): Unit =
- super.become({ case msg => behavior.apply(msg) }, discardOld)
+ super.become({ case msg ⇒ behavior.apply(msg) }, discardOld)
/**
* User overridable callback.
@@ -122,7 +122,7 @@ abstract class UntypedActor extends Actor {
}
final protected def receive = {
- case msg => onReceive(msg)
+ case msg ⇒ onReceive(msg)
}
}
diff --git a/akka-actor/src/main/scala/akka/cluster/NodeAddress.scala b/akka-actor/src/main/scala/akka/cluster/NodeAddress.scala
index 3bdef4c9dc..66e22b2349 100644
--- a/akka-actor/src/main/scala/akka/cluster/NodeAddress.scala
+++ b/akka-actor/src/main/scala/akka/cluster/NodeAddress.scala
@@ -12,33 +12,33 @@ import akka.config.Config
* @author Jonas Bonér
*/
class NodeAddress(
- val clusterName: String,
- val nodeName: String,
- val hostname: String,
- val port: Int) {
- if ((hostname eq null) || hostname == "") throw new NullPointerException("Host name must not be null or empty string")
- if ((nodeName eq null) || nodeName == "") throw new NullPointerException("Node name must not be null or empty string")
+ val clusterName: String,
+ val nodeName: String,
+ val hostname: String,
+ val port: Int) {
+ if ((hostname eq null) || hostname == "") throw new NullPointerException("Host name must not be null or empty string")
+ if ((nodeName eq null) || nodeName == "") throw new NullPointerException("Node name must not be null or empty string")
if ((clusterName eq null) || clusterName == "") throw new NullPointerException("Cluster name must not be null or empty string")
- if (port < 1) throw new NullPointerException("Port can not be negative")
+ if (port < 1) throw new NullPointerException("Port can not be negative")
- override def toString = "%s:%s:%s:%s".format(clusterName, nodeName, hostname, port)
+ override def toString = "%s:%s:%s:%s".format(clusterName, nodeName, hostname, port)
- override def hashCode = 0 + clusterName.## + nodeName.## + hostname.## + port.##
+ override def hashCode = 0 + clusterName.## + nodeName.## + hostname.## + port.##
- override def equals(other: Any) = NodeAddress.unapply(this) == NodeAddress.unapply(other)
+ override def equals(other: Any) = NodeAddress.unapply(this) == NodeAddress.unapply(other)
}
object NodeAddress {
def apply(
- clusterName: String = ClusterModule.name,
- nodeName: String = Config.nodename,
- hostname: String = Config.hostname,
- port: Int = Config.remoteServerPort): NodeAddress =
+ clusterName: String = ClusterModule.name,
+ nodeName: String = Config.nodename,
+ hostname: String = Config.hostname,
+ port: Int = Config.remoteServerPort): NodeAddress =
new NodeAddress(clusterName, nodeName, hostname, port)
def unapply(other: Any) = other match {
- case address: NodeAddress => Some((address.clusterName, address.nodeName, address.hostname, address.port))
- case _ => None
+ case address: NodeAddress ⇒ Some((address.clusterName, address.nodeName, address.hostname, address.port))
+ case _ ⇒ None
}
}
diff --git a/akka-actor/src/main/scala/akka/config/Config.scala b/akka-actor/src/main/scala/akka/config/Config.scala
index 8c1d5b20a8..5e8a75d423 100644
--- a/akka-actor/src/main/scala/akka/config/Config.scala
+++ b/akka-actor/src/main/scala/akka/config/Config.scala
@@ -23,13 +23,13 @@ object Config {
val HOME = {
val envHome = System.getenv("AKKA_HOME") match {
- case null | "" | "." => None
- case value => Some(value)
+ case null | "" | "." ⇒ None
+ case value ⇒ Some(value)
}
val systemHome = System.getProperty("akka.home") match {
- case null | "" => None
- case value => Some(value)
+ case null | "" ⇒ None
+ case value ⇒ Some(value)
}
envHome orElse systemHome
@@ -38,13 +38,13 @@ object Config {
val config: Configuration = {
val confName = {
val envConf = System.getenv("AKKA_MODE") match {
- case null | "" => None
- case value => Some(value)
+ case null | "" ⇒ None
+ case value ⇒ Some(value)
}
val systemConf = System.getProperty("akka.mode") match {
- case null | "" => None
- case value => Some(value)
+ case null | "" ⇒ None
+ case value ⇒ Some(value)
}
(envConf orElse systemConf).map("akka." + _ + ".conf").getOrElse("akka.conf")
@@ -53,15 +53,15 @@ object Config {
val (newInstance, source) =
if (System.getProperty("akka.config", "") != "") {
val configFile = System.getProperty("akka.config", "")
- (() => Configuration.fromFile(configFile), "Loading config from -Dakka.config=" + configFile)
+ (() ⇒ Configuration.fromFile(configFile), "Loading config from -Dakka.config=" + configFile)
} else if (getClass.getClassLoader.getResource(confName) ne null) {
- (() => Configuration.fromResource(confName, getClass.getClassLoader), "Loading config [" + confName + "] from the application classpath.")
+ (() ⇒ Configuration.fromResource(confName, getClass.getClassLoader), "Loading config [" + confName + "] from the application classpath.")
} else if (HOME.isDefined) {
val configFile = HOME.get + "/config/" + confName
- (() => Configuration.fromFile(configFile), "AKKA_HOME is defined as [" + HOME.get + "], loading config from [" + configFile + "].")
+ (() ⇒ Configuration.fromFile(configFile), "AKKA_HOME is defined as [" + HOME.get + "], loading config from [" + configFile + "].")
} else {
- (() => Configuration.fromString("akka {}"), // default empty config
- "\nCan't load '" + confName + "'." +
+ (() ⇒ Configuration.fromString("akka {}"), // default empty config
+ "\nCan't load '" + confName + "'." +
"\nOne of the three ways of locating the '" + confName + "' file needs to be defined:" +
"\n\t1. Define the '-Dakka.config=...' system property option." +
"\n\t2. Put the '" + confName + "' file on the classpath." +
@@ -78,12 +78,12 @@ object Config {
throw new ConfigurationException(
"Akka JAR version [" + VERSION + "] is different than the provided config version [" + configVersion + "]")
- if(Configuration.outputConfigSources)
+ if (Configuration.outputConfigSources)
System.out.println(source)
i
} catch {
- case e =>
+ case e ⇒
System.err.println("Couldn't parse config, fatal error.")
System.err.println("Config source: " + source)
e.printStackTrace(System.err)
@@ -97,18 +97,18 @@ object Config {
val TIME_UNIT = config.getString("akka.time-unit", "seconds")
lazy val nodename = System.getProperty("akka.cluster.nodename") match {
- case null | "" => new UUID().toString
- case value => value
+ case null | "" ⇒ new UUID().toString
+ case value ⇒ value
}
lazy val hostname = System.getProperty("akka.cluster.hostname") match {
- case null | "" => InetAddress.getLocalHost.getHostName
- case value => value
+ case null | "" ⇒ InetAddress.getLocalHost.getHostName
+ case value ⇒ value
}
val remoteServerPort = System.getProperty("akka.cluster.remote-server-port") match {
- case null | "" => config.getInt("akka.cluster.remote-server-port", 2552)
- case value => value.toInt
+ case null | "" ⇒ config.getInt("akka.cluster.remote-server-port", 2552)
+ case value ⇒ value.toInt
}
val startTime = System.currentTimeMillis
diff --git a/akka-actor/src/main/scala/akka/config/ConfigParser.scala b/akka-actor/src/main/scala/akka/config/ConfigParser.scala
index 6190beb826..6138143db3 100644
--- a/akka-actor/src/main/scala/akka/config/ConfigParser.scala
+++ b/akka-actor/src/main/scala/akka/config/ConfigParser.scala
@@ -11,7 +11,6 @@ package akka.config
import scala.collection.mutable
import scala.util.parsing.combinator._
-
class ConfigParser(var prefix: String = "", map: mutable.Map[String, Any] = mutable.Map.empty[String, Any], importer: Importer) extends RegexParsers {
val sections = mutable.Stack[String]()
@@ -34,7 +33,7 @@ class ConfigParser(var prefix: String = "", map: mutable.Map[String, Any] = muta
def value: Parser[Any] = number | string | list | boolean
def number = numberToken
- def string = stringToken ^^ { s => s.substring(1, s.length - 1) }
+ def string = stringToken ^^ { s ⇒ s.substring(1, s.length - 1) }
def list = "[" ~> repsep(string | numberToken, opt(",")) <~ (opt(",") ~ "]")
def boolean = booleanToken
@@ -43,20 +42,20 @@ class ConfigParser(var prefix: String = "", map: mutable.Map[String, Any] = muta
def root = rep(includeFile | assignment | sectionOpen | sectionClose)
def includeFile = "include" ~> string ^^ {
- case filename: String =>
+ case filename: String ⇒
new ConfigParser(prefix, map, importer) parse importer.importFile(filename)
}
def assignment = identToken ~ assignToken ~ value ^^ {
- case k ~ a ~ v => map(prefix + k) = v
+ case k ~ a ~ v ⇒ map(prefix + k) = v
}
- def sectionOpen = sectionToken <~ "{" ^^ { name =>
+ def sectionOpen = sectionToken <~ "{" ^^ { name ⇒
sections push name
createPrefix
}
- def sectionClose = "}" ^^ { _ =>
+ def sectionClose = "}" ^^ { _ ⇒
if (sections.isEmpty) {
failure("dangling close tag")
} else {
@@ -67,9 +66,9 @@ class ConfigParser(var prefix: String = "", map: mutable.Map[String, Any] = muta
def parse(in: String): Map[String, Any] = {
parseAll(root, in) match {
- case Success(result, _) => map.toMap
- case x @ Failure(msg, _) => throw new ConfigurationException(x.toString)
- case x @ Error(msg, _) => throw new ConfigurationException(x.toString)
+ case Success(result, _) ⇒ map.toMap
+ case x@Failure(msg, _) ⇒ throw new ConfigurationException(x.toString)
+ case x@Error(msg, _) ⇒ throw new ConfigurationException(x.toString)
}
}
}
diff --git a/akka-actor/src/main/scala/akka/config/Configuration.scala b/akka-actor/src/main/scala/akka/config/Configuration.scala
index 7794a3eb3d..a799a973bd 100644
--- a/akka-actor/src/main/scala/akka/config/Configuration.scala
+++ b/akka-actor/src/main/scala/akka/config/Configuration.scala
@@ -11,7 +11,7 @@ package akka.config
import java.io.File
object Configuration {
- val DefaultPath = new File(".").getCanonicalPath
+ val DefaultPath = new File(".").getCanonicalPath
val DefaultImporter = new FilesystemImporter(DefaultPath)
val outputConfigSources = System.getProperty("akka.output.config.source") ne null
@@ -76,7 +76,7 @@ class Configuration(val map: Map[String, Any]) {
try {
Some(map(key))
} catch {
- case _ => None
+ case _ ⇒ None
}
}
@@ -87,7 +87,7 @@ class Configuration(val map: Map[String, Any]) {
try {
map(key).asInstanceOf[Seq[Any]]
} catch {
- case _ => Seq.empty[Any]
+ case _ ⇒ Seq.empty[Any]
}
}
@@ -100,7 +100,7 @@ class Configuration(val map: Map[String, Any]) {
try {
map(key).asInstanceOf[Seq[String]]
} catch {
- case _ => Seq.empty[String]
+ case _ ⇒ Seq.empty[String]
}
}
@@ -108,7 +108,7 @@ class Configuration(val map: Map[String, Any]) {
try {
Some(map(key).toString.toInt)
} catch {
- case _ => None
+ case _ ⇒ None
}
}
@@ -119,7 +119,7 @@ class Configuration(val map: Map[String, Any]) {
try {
Some(map(key).toString.toLong)
} catch {
- case _ => None
+ case _ ⇒ None
}
}
@@ -130,7 +130,7 @@ class Configuration(val map: Map[String, Any]) {
try {
Some(map(key).toString.toFloat)
} catch {
- case _ => None
+ case _ ⇒ None
}
}
@@ -141,7 +141,7 @@ class Configuration(val map: Map[String, Any]) {
try {
Some(map(key).toString.toDouble)
} catch {
- case _ => None
+ case _ ⇒ None
}
}
@@ -149,7 +149,7 @@ class Configuration(val map: Map[String, Any]) {
getDouble(key).getOrElse(outputIfDesiredAndReturnInput(key, defaultValue))
def getBoolean(key: String): Option[Boolean] = {
- getString(key) flatMap { s =>
+ getString(key) flatMap { s ⇒
val isTrue = trueValues.contains(s)
if (!isTrue && !falseValues.contains(s)) None
else Some(isTrue)
@@ -165,8 +165,8 @@ class Configuration(val map: Map[String, Any]) {
getBoolean(key, defaultValue)
def apply(key: String): String = getString(key) match {
- case None => throw new ConfigurationException("undefined config: " + key)
- case Some(v) => v
+ case None ⇒ throw new ConfigurationException("undefined config: " + key)
+ case Some(v) ⇒ v
}
def apply(key: String, defaultValue: String) = getString(key, defaultValue)
@@ -176,7 +176,7 @@ class Configuration(val map: Map[String, Any]) {
def getSection(name: String): Option[Configuration] = {
val l = name.length + 1
- val m = map.collect { case (k, v) if k.startsWith(name) => (k.substring(l), v) }
+ val m = map.collect { case (k, v) if k.startsWith(name) ⇒ (k.substring(l), v) }
if (m.isEmpty) None
else Some(new Configuration(m))
}
diff --git a/akka-actor/src/main/scala/akka/config/Configurator.scala b/akka-actor/src/main/scala/akka/config/Configurator.scala
index e209ee21fb..2818339b0f 100644
--- a/akka-actor/src/main/scala/akka/config/Configurator.scala
+++ b/akka-actor/src/main/scala/akka/config/Configurator.scala
@@ -4,7 +4,7 @@
package akka.config
-import akka.config.Supervision. {SuperviseTypedActor, FaultHandlingStrategy}
+import akka.config.Supervision.{ SuperviseTypedActor, FaultHandlingStrategy }
private[akka] trait TypedActorConfiguratorBase {
def getExternalDependency[T](clazz: Class[T]): T
diff --git a/akka-actor/src/main/scala/akka/config/Importer.scala b/akka-actor/src/main/scala/akka/config/Importer.scala
index 1bec00208a..c5ec6cb9b2 100644
--- a/akka-actor/src/main/scala/akka/config/Importer.scala
+++ b/akka-actor/src/main/scala/akka/config/Importer.scala
@@ -8,8 +8,7 @@
package akka.config
-import java.io.{BufferedReader, File, FileInputStream, InputStream, InputStreamReader}
-
+import java.io.{ BufferedReader, File, FileInputStream, InputStream, InputStreamReader }
/**
* An interface for finding config files and reading them into strings for
@@ -36,12 +35,11 @@ trait Importer {
in.close()
sb.toString
} catch {
- case x => throw new ConfigurationException(x.toString)
+ case x ⇒ throw new ConfigurationException(x.toString)
}
}
}
-
/**
* An Importer that looks for imported config files in the filesystem.
* This is the default importer.
@@ -54,7 +52,6 @@ class FilesystemImporter(val baseDir: String) extends Importer {
}
}
-
/**
* An Importer that looks for imported config files in the java resources
* of the system class loader (usually the jar used to launch this app).
diff --git a/akka-actor/src/main/scala/akka/config/SupervisionConfig.scala b/akka-actor/src/main/scala/akka/config/SupervisionConfig.scala
index e695f0301e..b06c01b119 100644
--- a/akka-actor/src/main/scala/akka/config/SupervisionConfig.scala
+++ b/akka-actor/src/main/scala/akka/config/SupervisionConfig.scala
@@ -5,8 +5,8 @@
package akka.config
import akka.dispatch.MessageDispatcher
-import akka.actor.{MaximumNumberOfRestartsWithinTimeRangeReached, ActorRef}
-import akka.japi.{Procedure2, Procedure}
+import akka.actor.{ MaximumNumberOfRestartsWithinTimeRangeReached, ActorRef }
+import akka.japi.{ Procedure2, Procedure }
case class RemoteAddress(val hostname: String, val port: Int)
@@ -22,10 +22,10 @@ object Supervision {
sealed abstract class LifeCycle extends ConfigElement
sealed abstract class FaultHandlingStrategy(val trapExit: List[Class[_ <: Throwable]]) extends ConfigElement
- case class SupervisorConfig(restartStrategy: FaultHandlingStrategy, worker: List[Server], maxRestartsHandler: (ActorRef,MaximumNumberOfRestartsWithinTimeRangeReached)=> Unit = {(aRef,max)=>()}) extends Server {
+ case class SupervisorConfig(restartStrategy: FaultHandlingStrategy, worker: List[Server], maxRestartsHandler: (ActorRef, MaximumNumberOfRestartsWithinTimeRangeReached) ⇒ Unit = { (aRef, max) ⇒ () }) extends Server {
//Java API
- def this(restartStrategy: FaultHandlingStrategy, worker: Array[Server]) = this(restartStrategy,worker.toList)
- def this(restartStrategy: FaultHandlingStrategy, worker: Array[Server], restartHandler:Procedure2[ActorRef,MaximumNumberOfRestartsWithinTimeRangeReached]) = this(restartStrategy,worker.toList, {(aRef,max)=>restartHandler.apply(aRef,max)})
+ def this(restartStrategy: FaultHandlingStrategy, worker: Array[Server]) = this(restartStrategy, worker.toList)
+ def this(restartStrategy: FaultHandlingStrategy, worker: Array[Server], restartHandler: Procedure2[ActorRef, MaximumNumberOfRestartsWithinTimeRangeReached]) = this(restartStrategy, worker.toList, { (aRef, max) ⇒ restartHandler.apply(aRef, max) })
}
class Supervise(val actorRef: ActorRef, val lifeCycle: LifeCycle, val registerAsRemoteService: Boolean = false) extends Server {
@@ -104,19 +104,19 @@ object Supervision {
case object UndefinedLifeCycle extends LifeCycle
//Java API (& Scala if you fancy)
- def permanent(): LifeCycle = Permanent
- def temporary(): LifeCycle = Temporary
+ def permanent(): LifeCycle = Permanent
+ def temporary(): LifeCycle = Temporary
def undefinedLifeCycle(): LifeCycle = UndefinedLifeCycle
//Java API
def noFaultHandlingStrategy = NoFaultHandlingStrategy
case class SuperviseTypedActor(_intf: Class[_],
- val target: Class[_],
- val lifeCycle: LifeCycle,
- val timeout: Long,
- _dispatcher: MessageDispatcher // optional
- ) extends Server {
+ val target: Class[_],
+ val lifeCycle: LifeCycle,
+ val timeout: Long,
+ _dispatcher: MessageDispatcher // optional
+ ) extends Server {
val intf: Option[Class[_]] = Option(_intf)
val dispatcher: Option[MessageDispatcher] = Option(_dispatcher)
diff --git a/akka-actor/src/main/scala/akka/dataflow/DataFlow.scala b/akka-actor/src/main/scala/akka/dataflow/DataFlow.scala
index 13438132e6..44cef7e13d 100644
--- a/akka-actor/src/main/scala/akka/dataflow/DataFlow.scala
+++ b/akka-actor/src/main/scala/akka/dataflow/DataFlow.scala
@@ -5,10 +5,10 @@
package akka.dataflow
import java.util.concurrent.atomic.AtomicReference
-import java.util.concurrent.{ConcurrentLinkedQueue, LinkedBlockingQueue}
+import java.util.concurrent.{ ConcurrentLinkedQueue, LinkedBlockingQueue }
import akka.event.EventHandler
-import akka.actor.{Actor, ActorRef}
+import akka.actor.{ Actor, ActorRef }
import akka.actor.Actor._
import akka.dispatch.CompletableFuture
import akka.AkkaException
@@ -28,7 +28,7 @@ object DataFlow {
/**
* Executes the supplied thunk in another thread.
*/
- def thread(body: => Unit): Unit = spawn(body)
+ def thread(body: ⇒ Unit): Unit = spawn(body)
/**
* JavaAPI.
@@ -39,21 +39,21 @@ object DataFlow {
/**
* Executes the supplied function in another thread.
*/
- def thread[A <: AnyRef, R <: AnyRef](body: A => R) =
+ def thread[A <: AnyRef, R <: AnyRef](body: A ⇒ R) =
actorOf(new ReactiveEventBasedThread(body)).start()
/**
* JavaAPI.
* Executes the supplied Function in another thread.
*/
- def thread[A <: AnyRef, R <: AnyRef](body: Function[A,R]) =
+ def thread[A <: AnyRef, R <: AnyRef](body: Function[A, R]) =
actorOf(new ReactiveEventBasedThread(body.apply)).start()
- private class ReactiveEventBasedThread[A <: AnyRef, T <: AnyRef](body: A => T)
+ private class ReactiveEventBasedThread[A <: AnyRef, T <: AnyRef](body: A ⇒ T)
extends Actor {
def receive = {
- case Exit => self.stop()
- case message => self.reply(body(message.asInstanceOf[A]))
+ case Exit ⇒ self.stop()
+ case message ⇒ self.reply(body(message.asInstanceOf[A]))
}
}
@@ -78,13 +78,13 @@ object DataFlow {
private class In[T <: Any](dataFlow: DataFlowVariable[T]) extends Actor {
self.timeout = timeoutMs
def receive = {
- case s@Set(v) =>
+ case s@Set(v) ⇒
if (dataFlow.value.compareAndSet(None, Some(v.asInstanceOf[T]))) {
- while(dataFlow.blockedReaders.peek ne null)
- dataFlow.blockedReaders.poll ! s
+ while (dataFlow.blockedReaders.peek ne null)
+ dataFlow.blockedReaders.poll ! s
} else throw new DataFlowVariableException(
"Attempt to change data flow variable (from [" + dataFlow.value.get + "] to [" + v + "])")
- case Exit => self.stop()
+ case Exit ⇒ self.stop()
}
}
@@ -92,12 +92,12 @@ object DataFlow {
self.timeout = timeoutMs
private var readerFuture: Option[CompletableFuture[Any]] = None
def receive = {
- case Get => dataFlow.value.get match {
- case Some(value) => self reply value
- case None => readerFuture = self.senderFuture
+ case Get ⇒ dataFlow.value.get match {
+ case Some(value) ⇒ self reply value
+ case None ⇒ readerFuture = self.senderFuture
}
- case Set(v:T) => readerFuture.map(_ completeWithResult v)
- case Exit => self.stop()
+ case Set(v: T) ⇒ readerFuture.map(_ completeWithResult v)
+ case Exit ⇒ self.stop()
}
}
@@ -109,7 +109,7 @@ object DataFlow {
def <<(ref: DataFlowVariable[T]) {
if (this.value.get.isEmpty) in ! Set(ref())
else throw new DataFlowVariableException(
- "Attempt to change data flow variable (from [" + this.value.get + "] to [" + ref() + "])")
+ "Attempt to change data flow variable (from [" + this.value.get + "] to [" + ref() + "])")
}
/**
@@ -124,7 +124,7 @@ object DataFlow {
def <<(value: T) {
if (this.value.get.isEmpty) in ! Set(value)
else throw new DataFlowVariableException(
- "Attempt to change data flow variable (from [" + this.value.get + "] to [" + value + "])")
+ "Attempt to change data flow variable (from [" + this.value.get + "] to [" + value + "])")
}
/**
@@ -149,14 +149,14 @@ object DataFlow {
blockedReaders offer out
(out !! Get).as[T]
} catch {
- case e: Exception =>
+ case e: Exception ⇒
EventHandler.error(e, this, e.getMessage)
out ! Exit
throw e
}
result.getOrElse(throw new DataFlowVariableException(
- "Timed out (after " + timeoutMs + " milliseconds) while waiting for result"))
+ "Timed out (after " + timeoutMs + " milliseconds) while waiting for result"))
}
}
diff --git a/akka-actor/src/main/scala/akka/dispatch/Dispatchers.scala b/akka-actor/src/main/scala/akka/dispatch/Dispatchers.scala
index eee5d53c51..07daf658d3 100644
--- a/akka-actor/src/main/scala/akka/dispatch/Dispatchers.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/Dispatchers.scala
@@ -4,10 +4,10 @@
package akka.dispatch
-import akka.actor.{Actor, ActorRef}
+import akka.actor.{ Actor, ActorRef }
import akka.actor.newUuid
import akka.config.Config._
-import akka.util.{Duration,ReflectiveAccess}
+import akka.util.{ Duration, ReflectiveAccess }
import akka.config.Configuration
@@ -46,15 +46,15 @@ import java.util.concurrent.TimeUnit
* @author Jonas Bonér
*/
object Dispatchers {
- val THROUGHPUT = config.getInt("akka.actor.throughput", 5)
- val DEFAULT_SHUTDOWN_TIMEOUT = config.getLong("akka.actor.dispatcher-shutdown-timeout").
- map(time => Duration(time, TIME_UNIT)).
- getOrElse(Duration(1000,TimeUnit.MILLISECONDS))
- val MAILBOX_CAPACITY = config.getInt("akka.actor.default-dispatcher.mailbox-capacity", -1)
- val MAILBOX_PUSH_TIME_OUT = Duration(config.getInt("akka.actor.default-dispatcher.mailbox-push-timeout-time", 10), TIME_UNIT)
- val THROUGHPUT_DEADLINE_TIME = Duration(config.getInt("akka.actor.throughput-deadline-time",-1), TIME_UNIT)
+ val THROUGHPUT = config.getInt("akka.actor.throughput", 5)
+ val DEFAULT_SHUTDOWN_TIMEOUT = config.getLong("akka.actor.dispatcher-shutdown-timeout").
+ map(time ⇒ Duration(time, TIME_UNIT)).
+ getOrElse(Duration(1000, TimeUnit.MILLISECONDS))
+ val MAILBOX_CAPACITY = config.getInt("akka.actor.default-dispatcher.mailbox-capacity", -1)
+ val MAILBOX_PUSH_TIME_OUT = Duration(config.getInt("akka.actor.default-dispatcher.mailbox-push-timeout-time", 10), TIME_UNIT)
+ val THROUGHPUT_DEADLINE_TIME = Duration(config.getInt("akka.actor.throughput-deadline-time", -1), TIME_UNIT)
val THROUGHPUT_DEADLINE_TIME_MILLIS = THROUGHPUT_DEADLINE_TIME.toMillis.toInt
- val MAILBOX_TYPE: MailboxType = if (MAILBOX_CAPACITY < 1) UnboundedMailbox() else BoundedMailbox()
+ val MAILBOX_TYPE: MailboxType = if (MAILBOX_CAPACITY < 1) UnboundedMailbox() else BoundedMailbox()
lazy val defaultGlobalDispatcher = {
config.getSection("akka.actor.default-dispatcher").flatMap(from).getOrElse(globalExecutorBasedEventDrivenDispatcher)
@@ -94,7 +94,7 @@ object Dispatchers {
* Has a fluent builder interface for configuring its semantics.
*/
def newExecutorBasedEventDrivenDispatcher(name: String) =
- ThreadPoolConfigDispatcherBuilder(config => new ExecutorBasedEventDrivenDispatcher(name,config),ThreadPoolConfig())
+ ThreadPoolConfigDispatcherBuilder(config ⇒ new ExecutorBasedEventDrivenDispatcher(name, config), ThreadPoolConfig())
/**
* Creates a executor-based event-driven dispatcher serving multiple (millions) of actors through a thread pool.
@@ -102,9 +102,8 @@ object Dispatchers {
* Has a fluent builder interface for configuring its semantics.
*/
def newExecutorBasedEventDrivenDispatcher(name: String, throughput: Int, mailboxType: MailboxType) =
- ThreadPoolConfigDispatcherBuilder(config =>
- new ExecutorBasedEventDrivenDispatcher(name, throughput, THROUGHPUT_DEADLINE_TIME_MILLIS, mailboxType, config),ThreadPoolConfig())
-
+ ThreadPoolConfigDispatcherBuilder(config ⇒
+ new ExecutorBasedEventDrivenDispatcher(name, throughput, THROUGHPUT_DEADLINE_TIME_MILLIS, mailboxType, config), ThreadPoolConfig())
/**
* Creates a executor-based event-driven dispatcher serving multiple (millions) of actors through a thread pool.
@@ -112,16 +111,16 @@ object Dispatchers {
* Has a fluent builder interface for configuring its semantics.
*/
def newExecutorBasedEventDrivenDispatcher(name: String, throughput: Int, throughputDeadlineMs: Int, mailboxType: MailboxType) =
- ThreadPoolConfigDispatcherBuilder(config =>
- new ExecutorBasedEventDrivenDispatcher(name, throughput, throughputDeadlineMs, mailboxType, config),ThreadPoolConfig())
+ ThreadPoolConfigDispatcherBuilder(config ⇒
+ new ExecutorBasedEventDrivenDispatcher(name, throughput, throughputDeadlineMs, mailboxType, config), ThreadPoolConfig())
- /**
+ /**
* Creates a executor-based event-driven dispatcher, with work-stealing, serving multiple (millions) of actors through a thread pool.
*
* Has a fluent builder interface for configuring its semantics.
*/
def newExecutorBasedEventDrivenWorkStealingDispatcher(name: String) =
- ThreadPoolConfigDispatcherBuilder(config => new ExecutorBasedEventDrivenWorkStealingDispatcher(name,config),ThreadPoolConfig())
+ ThreadPoolConfigDispatcherBuilder(config ⇒ new ExecutorBasedEventDrivenWorkStealingDispatcher(name, config), ThreadPoolConfig())
/**
* Creates a executor-based event-driven dispatcher, with work-stealing, serving multiple (millions) of actors through a thread pool.
@@ -129,8 +128,8 @@ object Dispatchers {
* Has a fluent builder interface for configuring its semantics.
*/
def newExecutorBasedEventDrivenWorkStealingDispatcher(name: String, throughput: Int) =
- ThreadPoolConfigDispatcherBuilder(config =>
- new ExecutorBasedEventDrivenWorkStealingDispatcher(name, throughput, THROUGHPUT_DEADLINE_TIME_MILLIS, MAILBOX_TYPE, config),ThreadPoolConfig())
+ ThreadPoolConfigDispatcherBuilder(config ⇒
+ new ExecutorBasedEventDrivenWorkStealingDispatcher(name, throughput, THROUGHPUT_DEADLINE_TIME_MILLIS, MAILBOX_TYPE, config), ThreadPoolConfig())
/**
* Creates a executor-based event-driven dispatcher, with work-stealing, serving multiple (millions) of actors through a thread pool.
@@ -138,9 +137,8 @@ object Dispatchers {
* Has a fluent builder interface for configuring its semantics.
*/
def newExecutorBasedEventDrivenWorkStealingDispatcher(name: String, throughput: Int, mailboxType: MailboxType) =
- ThreadPoolConfigDispatcherBuilder(config =>
- new ExecutorBasedEventDrivenWorkStealingDispatcher(name, throughput, THROUGHPUT_DEADLINE_TIME_MILLIS, mailboxType, config),ThreadPoolConfig())
-
+ ThreadPoolConfigDispatcherBuilder(config ⇒
+ new ExecutorBasedEventDrivenWorkStealingDispatcher(name, throughput, THROUGHPUT_DEADLINE_TIME_MILLIS, mailboxType, config), ThreadPoolConfig())
/**
* Creates a executor-based event-driven dispatcher, with work-stealing, serving multiple (millions) of actors through a thread pool.
@@ -148,13 +146,13 @@ object Dispatchers {
* Has a fluent builder interface for configuring its semantics.
*/
def newExecutorBasedEventDrivenWorkStealingDispatcher(name: String, throughput: Int, throughputDeadlineMs: Int, mailboxType: MailboxType) =
- ThreadPoolConfigDispatcherBuilder(config =>
- new ExecutorBasedEventDrivenWorkStealingDispatcher(name, throughput, throughputDeadlineMs, mailboxType, config),ThreadPoolConfig())
+ ThreadPoolConfigDispatcherBuilder(config ⇒
+ new ExecutorBasedEventDrivenWorkStealingDispatcher(name, throughput, throughputDeadlineMs, mailboxType, config), ThreadPoolConfig())
/**
* Utility function that tries to load the specified dispatcher config from the akka.conf
* or else use the supplied default dispatcher
*/
- def fromConfig(key: String, default: => MessageDispatcher = defaultGlobalDispatcher): MessageDispatcher =
+ def fromConfig(key: String, default: ⇒ MessageDispatcher = defaultGlobalDispatcher): MessageDispatcher =
config getSection key flatMap from getOrElse default
/*
@@ -181,24 +179,24 @@ object Dispatchers {
* IllegalArgumentException if it cannot
*/
def from(cfg: Configuration): Option[MessageDispatcher] = {
- cfg.getString("type") map {
- case "ExecutorBasedEventDriven" => new ExecutorBasedEventDrivenDispatcherConfigurator()
- case "ExecutorBasedEventDrivenWorkStealing" => new ExecutorBasedEventDrivenWorkStealingDispatcherConfigurator()
- case "GlobalExecutorBasedEventDriven" => GlobalExecutorBasedEventDrivenDispatcherConfigurator
- case fqn =>
- ReflectiveAccess.getClassFor[MessageDispatcherConfigurator](fqn) match {
- case r: Right[_, Class[MessageDispatcherConfigurator]] =>
- ReflectiveAccess.createInstance[MessageDispatcherConfigurator](r.b, Array[Class[_]](), Array[AnyRef]()) match {
- case r: Right[Exception, MessageDispatcherConfigurator] => r.b
- case l: Left[Exception, MessageDispatcherConfigurator] =>
- throw new IllegalArgumentException("Cannot instantiate MessageDispatcherConfigurator type [%s], make sure it has a default no-args constructor" format fqn, l.a)
- }
- case l: Left[Exception, _] =>
- throw new IllegalArgumentException("Unknown MessageDispatcherConfigurator type [%s]" format fqn, l.a)
- }
- } map {
- _ configure cfg
- }
+ cfg.getString("type") map {
+ case "ExecutorBasedEventDriven" ⇒ new ExecutorBasedEventDrivenDispatcherConfigurator()
+ case "ExecutorBasedEventDrivenWorkStealing" ⇒ new ExecutorBasedEventDrivenWorkStealingDispatcherConfigurator()
+ case "GlobalExecutorBasedEventDriven" ⇒ GlobalExecutorBasedEventDrivenDispatcherConfigurator
+ case fqn ⇒
+ ReflectiveAccess.getClassFor[MessageDispatcherConfigurator](fqn) match {
+ case r: Right[_, Class[MessageDispatcherConfigurator]] ⇒
+ ReflectiveAccess.createInstance[MessageDispatcherConfigurator](r.b, Array[Class[_]](), Array[AnyRef]()) match {
+ case r: Right[Exception, MessageDispatcherConfigurator] ⇒ r.b
+ case l: Left[Exception, MessageDispatcherConfigurator] ⇒
+ throw new IllegalArgumentException("Cannot instantiate MessageDispatcherConfigurator type [%s], make sure it has a default no-args constructor" format fqn, l.a)
+ }
+ case l: Left[Exception, _] ⇒
+ throw new IllegalArgumentException("Unknown MessageDispatcherConfigurator type [%s]" format fqn, l.a)
+ }
+ } map {
+ _ configure cfg
+ }
}
}
@@ -208,7 +206,7 @@ object GlobalExecutorBasedEventDrivenDispatcherConfigurator extends MessageDispa
class ExecutorBasedEventDrivenDispatcherConfigurator extends MessageDispatcherConfigurator {
def configure(config: Configuration): MessageDispatcher = {
- configureThreadPool(config, threadPoolConfig => new ExecutorBasedEventDrivenDispatcher(
+ configureThreadPool(config, threadPoolConfig ⇒ new ExecutorBasedEventDrivenDispatcher(
config.getString("name", newUuid.toString),
config.getInt("throughput", Dispatchers.THROUGHPUT),
config.getInt("throughput-deadline-time", Dispatchers.THROUGHPUT_DEADLINE_TIME_MILLIS),
@@ -219,7 +217,7 @@ class ExecutorBasedEventDrivenDispatcherConfigurator extends MessageDispatcherCo
class ExecutorBasedEventDrivenWorkStealingDispatcherConfigurator extends MessageDispatcherConfigurator {
def configure(config: Configuration): MessageDispatcher = {
- configureThreadPool(config, threadPoolConfig => new ExecutorBasedEventDrivenWorkStealingDispatcher(
+ configureThreadPool(config, threadPoolConfig ⇒ new ExecutorBasedEventDrivenWorkStealingDispatcher(
config.getString("name", newUuid.toString),
config.getInt("throughput", Dispatchers.THROUGHPUT),
config.getInt("throughput-deadline-time", Dispatchers.THROUGHPUT_DEADLINE_TIME_MILLIS),
diff --git a/akka-actor/src/main/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcher.scala b/akka-actor/src/main/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcher.scala
index bc03607fdc..3c985e6409 100644
--- a/akka-actor/src/main/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcher.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcher.scala
@@ -5,10 +5,10 @@
package akka.dispatch
import akka.event.EventHandler
-import akka.actor.{ActorRef}
+import akka.actor.{ ActorRef }
import java.util.concurrent.atomic.AtomicReference
-import java.util.concurrent.{ TimeUnit, ExecutorService, RejectedExecutionException, ConcurrentLinkedQueue}
+import java.util.concurrent.{ TimeUnit, ExecutorService, RejectedExecutionException, ConcurrentLinkedQueue }
/**
* Default settings are:
@@ -72,7 +72,7 @@ class ExecutorBasedEventDrivenDispatcher(
extends MessageDispatcher {
def this(_name: String, throughput: Int, throughputDeadlineTime: Int, mailboxType: MailboxType) =
- this(_name, throughput, throughputDeadlineTime, mailboxType,ThreadPoolConfig()) // Needed for Java API usage
+ this(_name, throughput, throughputDeadlineTime, mailboxType, ThreadPoolConfig()) // Needed for Java API usage
def this(_name: String, throughput: Int, mailboxType: MailboxType) =
this(_name, throughput, Dispatchers.THROUGHPUT_DEADLINE_TIME_MILLIS, mailboxType) // Needed for Java API usage
@@ -100,7 +100,7 @@ class ExecutorBasedEventDrivenDispatcher(
private[akka] def executeFuture(invocation: FutureInvocation[_]): Unit = if (active.isOn) {
try executorService.get() execute invocation
catch {
- case e: RejectedExecutionException =>
+ case e: RejectedExecutionException ⇒
EventHandler.warning(this, e.toString)
throw e
}
@@ -114,15 +114,19 @@ class ExecutorBasedEventDrivenDispatcher(
override def mailboxSize(actorRef: ActorRef) = getMailbox(actorRef).size
def createMailbox(actorRef: ActorRef): AnyRef = mailboxType match {
- case b: UnboundedMailbox =>
+ case b: UnboundedMailbox ⇒
new ConcurrentLinkedQueue[MessageInvocation] with MessageQueue with ExecutableMailbox {
- @inline final def dispatcher = ExecutorBasedEventDrivenDispatcher.this
- @inline final def enqueue(m: MessageInvocation) = this.add(m)
- @inline final def dequeue(): MessageInvocation = this.poll()
+ @inline
+ final def dispatcher = ExecutorBasedEventDrivenDispatcher.this
+ @inline
+ final def enqueue(m: MessageInvocation) = this.add(m)
+ @inline
+ final def dequeue(): MessageInvocation = this.poll()
}
- case b: BoundedMailbox =>
+ case b: BoundedMailbox ⇒
new DefaultBoundedMessageQueue(b.capacity, b.pushTimeOut) with ExecutableMailbox {
- @inline final def dispatcher = ExecutorBasedEventDrivenDispatcher.this
+ @inline
+ final def dispatcher = ExecutorBasedEventDrivenDispatcher.this
}
}
@@ -141,7 +145,7 @@ class ExecutorBasedEventDrivenDispatcher(
try {
executorService.get() execute mbox
} catch {
- case e: RejectedExecutionException =>
+ case e: RejectedExecutionException ⇒
EventHandler.warning(this, e.toString)
mbox.dispatcherLock.unlock()
throw e
@@ -171,7 +175,7 @@ class ExecutorBasedEventDrivenDispatcher(
/**
* This is the behavior of an ExecutorBasedEventDrivenDispatchers mailbox.
*/
-trait ExecutableMailbox extends Runnable { self: MessageQueue =>
+trait ExecutableMailbox extends Runnable { self: MessageQueue ⇒
def dispatcher: ExecutorBasedEventDrivenDispatcher
@@ -179,8 +183,9 @@ trait ExecutableMailbox extends Runnable { self: MessageQueue =>
try {
processMailbox()
} catch {
- case ie: InterruptedException =>
- } finally {
+ case ie: InterruptedException ⇒
+ }
+ finally {
dispatcherLock.unlock()
}
if (!self.isEmpty)
@@ -201,8 +206,8 @@ trait ExecutableMailbox extends Runnable { self: MessageQueue =>
else { //But otherwise, if we are throttled, we need to do some book-keeping
var processedMessages = 0
val isDeadlineEnabled = dispatcher.throughputDeadlineTime > 0
- val deadlineNs = if (isDeadlineEnabled) System.nanoTime + TimeUnit.MILLISECONDS.toNanos(dispatcher.throughputDeadlineTime)
- else 0
+ val deadlineNs = if (isDeadlineEnabled) System.nanoTime + TimeUnit.MILLISECONDS.toNanos(dispatcher.throughputDeadlineTime)
+ else 0
do {
nextMessage.invoke
nextMessage =
@@ -225,7 +230,7 @@ object PriorityGenerator {
/**
* Creates a PriorityGenerator that uses the supplied function as priority generator
*/
- def apply(priorityFunction: Any => Int): PriorityGenerator = new PriorityGenerator {
+ def apply(priorityFunction: Any ⇒ Int): PriorityGenerator = new PriorityGenerator {
def gen(message: Any): Int = priorityFunction(message)
}
}
@@ -248,16 +253,15 @@ abstract class PriorityGenerator extends java.util.Comparator[MessageInvocation]
* The dispatcher will process the messages with the _lowest_ priority first.
*/
class PriorityExecutorBasedEventDrivenDispatcher(
- name: String,
- val comparator: java.util.Comparator[MessageInvocation],
- throughput: Int = Dispatchers.THROUGHPUT,
- throughputDeadlineTime: Int = Dispatchers.THROUGHPUT_DEADLINE_TIME_MILLIS,
- mailboxType: MailboxType = Dispatchers.MAILBOX_TYPE,
- config: ThreadPoolConfig = ThreadPoolConfig()
- ) extends ExecutorBasedEventDrivenDispatcher(name, throughput, throughputDeadlineTime, mailboxType, config) with PriorityMailbox {
+ name: String,
+ val comparator: java.util.Comparator[MessageInvocation],
+ throughput: Int = Dispatchers.THROUGHPUT,
+ throughputDeadlineTime: Int = Dispatchers.THROUGHPUT_DEADLINE_TIME_MILLIS,
+ mailboxType: MailboxType = Dispatchers.MAILBOX_TYPE,
+ config: ThreadPoolConfig = ThreadPoolConfig()) extends ExecutorBasedEventDrivenDispatcher(name, throughput, throughputDeadlineTime, mailboxType, config) with PriorityMailbox {
def this(name: String, comparator: java.util.Comparator[MessageInvocation], throughput: Int, throughputDeadlineTime: Int, mailboxType: MailboxType) =
- this(name, comparator, throughput, throughputDeadlineTime, mailboxType,ThreadPoolConfig()) // Needed for Java API usage
+ this(name, comparator, throughput, throughputDeadlineTime, mailboxType, ThreadPoolConfig()) // Needed for Java API usage
def this(name: String, comparator: java.util.Comparator[MessageInvocation], throughput: Int, mailboxType: MailboxType) =
this(name, comparator, throughput, Dispatchers.THROUGHPUT_DEADLINE_TIME_MILLIS, mailboxType) // Needed for Java API usage
@@ -272,7 +276,6 @@ class PriorityExecutorBasedEventDrivenDispatcher(
this(name, comparator, Dispatchers.THROUGHPUT, Dispatchers.THROUGHPUT_DEADLINE_TIME_MILLIS, Dispatchers.MAILBOX_TYPE) // Needed for Java API usage
}
-
/**
* Can be used to give an ExecutorBasedEventDrivenDispatcher's actors priority-enabled mailboxes
*
@@ -281,18 +284,20 @@ class PriorityExecutorBasedEventDrivenDispatcher(
* val comparator = ...comparator that determines mailbox priority ordering...
* }
*/
-trait PriorityMailbox { self: ExecutorBasedEventDrivenDispatcher =>
+trait PriorityMailbox { self: ExecutorBasedEventDrivenDispatcher ⇒
def comparator: java.util.Comparator[MessageInvocation]
override def createMailbox(actorRef: ActorRef): AnyRef = self.mailboxType match {
- case b: UnboundedMailbox =>
+ case b: UnboundedMailbox ⇒
new UnboundedPriorityMessageQueue(comparator) with ExecutableMailbox {
- @inline final def dispatcher = self
+ @inline
+ final def dispatcher = self
}
- case b: BoundedMailbox =>
+ case b: BoundedMailbox ⇒
new BoundedPriorityMessageQueue(b.capacity, b.pushTimeOut, comparator) with ExecutableMailbox {
- @inline final def dispatcher = self
+ @inline
+ final def dispatcher = self
}
}
}
diff --git a/akka-actor/src/main/scala/akka/dispatch/ExecutorBasedEventDrivenWorkStealingDispatcher.scala b/akka-actor/src/main/scala/akka/dispatch/ExecutorBasedEventDrivenWorkStealingDispatcher.scala
index 637aea8e60..eaf4472901 100644
--- a/akka-actor/src/main/scala/akka/dispatch/ExecutorBasedEventDrivenWorkStealingDispatcher.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/ExecutorBasedEventDrivenWorkStealingDispatcher.scala
@@ -4,7 +4,7 @@
package akka.dispatch
-import akka.actor.{ActorRef, Actor, IllegalActorStateException}
+import akka.actor.{ ActorRef, Actor, IllegalActorStateException }
import util.DynamicVariable
@@ -33,7 +33,7 @@ class ExecutorBasedEventDrivenWorkStealingDispatcher(
extends ExecutorBasedEventDrivenDispatcher(_name, throughput, throughputDeadlineTime, mailboxType, config) {
def this(_name: String, throughput: Int, throughputDeadlineTime: Int, mailboxType: MailboxType) =
- this(_name, throughput, throughputDeadlineTime, mailboxType,ThreadPoolConfig()) // Needed for Java API usage
+ this(_name, throughput, throughputDeadlineTime, mailboxType, ThreadPoolConfig()) // Needed for Java API usage
def this(_name: String, throughput: Int, mailboxType: MailboxType) =
this(_name, throughput, Dispatchers.THROUGHPUT_DEADLINE_TIME_MILLIS, mailboxType) // Needed for Java API usage
@@ -50,15 +50,17 @@ class ExecutorBasedEventDrivenWorkStealingDispatcher(
def this(_name: String, mailboxType: MailboxType) =
this(_name, Dispatchers.THROUGHPUT, Dispatchers.THROUGHPUT_DEADLINE_TIME_MILLIS, mailboxType) // Needed for Java API usage
- @volatile private var actorType: Option[Class[_]] = None
- @volatile private var members = Vector[ActorRef]()
+ @volatile
+ private var actorType: Option[Class[_]] = None
+ @volatile
+ private var members = Vector[ActorRef]()
private val donationInProgress = new DynamicVariable(false)
private[akka] override def register(actorRef: ActorRef) = {
//Verify actor type conformity
actorType match {
- case None => actorType = Some(actorRef.actor.getClass)
- case Some(aType) =>
+ case None ⇒ actorType = Some(actorRef.actor.getClass)
+ case Some(aType) ⇒
if (aType != actorRef.actor.getClass)
throw new IllegalActorStateException(String.format(
"Can't register actor %s in a work stealing dispatcher which already knows actors of type %s",
@@ -87,11 +89,11 @@ class ExecutorBasedEventDrivenWorkStealingDispatcher(
override private[akka] def reRegisterForExecution(mbox: MessageQueue with ExecutableMailbox): Unit = {
try {
donationInProgress.value = true
- while(donateFrom(mbox)) {} //When we reregister, first donate messages to another actor
+ while (donateFrom(mbox)) {} //When we reregister, first donate messages to another actor
} finally { donationInProgress.value = false }
if (!mbox.isEmpty) //If we still have messages left to process, reschedule for execution
- super.reRegisterForExecution(mbox)
+ super.reRegisterForExecution(mbox)
}
/**
@@ -104,8 +106,8 @@ class ExecutorBasedEventDrivenWorkStealingDispatcher(
// the dispatcher is being shut down...
// Starts at is seeded by current time
doFindDonorRecipient(donorMbox, actors, (System.currentTimeMillis % actors.size).asInstanceOf[Int]) match {
- case null => false
- case recipient => donate(donorMbox.dequeue, recipient)
+ case null ⇒ false
+ case recipient ⇒ donate(donorMbox.dequeue, recipient)
}
}
@@ -116,8 +118,8 @@ class ExecutorBasedEventDrivenWorkStealingDispatcher(
donationInProgress.value = true
val actors = members // copy to prevent concurrent modifications having any impact
doFindDonorRecipient(donorMbox, actors, System.identityHashCode(message) % actors.size) match {
- case null => false
- case recipient => donate(message, recipient)
+ case null ⇒ false
+ case recipient ⇒ donate(message, recipient)
}
} finally { donationInProgress.value = false }
@@ -143,7 +145,7 @@ class ExecutorBasedEventDrivenWorkStealingDispatcher(
var i = 0
var recipient: ActorRef = null
- while((i < prSz) && (recipient eq null)) {
+ while ((i < prSz) && (recipient eq null)) {
val actor = potentialRecipients((i + startIndex) % prSz) //Wrap-around, one full lap
val mbox = getMailbox(actor)
diff --git a/akka-actor/src/main/scala/akka/dispatch/Future.scala b/akka-actor/src/main/scala/akka/dispatch/Future.scala
index 2614767e94..3ffdc0e1a6 100644
--- a/akka-actor/src/main/scala/akka/dispatch/Future.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/Future.scala
@@ -6,18 +6,18 @@ package akka.dispatch
import akka.AkkaException
import akka.event.EventHandler
-import akka.actor.{Actor, Channel}
+import akka.actor.{ Actor, Channel }
import akka.util.Duration
-import akka.japi.{ Procedure, Function => JFunc }
+import akka.japi.{ Procedure, Function ⇒ JFunc }
import scala.util.continuations._
import java.util.concurrent.locks.ReentrantLock
-import java.util.concurrent. {ConcurrentLinkedQueue, TimeUnit, Callable}
-import java.util.concurrent.TimeUnit.{NANOSECONDS => NANOS, MILLISECONDS => MILLIS}
-import java.util.concurrent.atomic. {AtomicBoolean}
-import java.lang.{Iterable => JIterable}
-import java.util.{LinkedList => JLinkedList}
+import java.util.concurrent.{ ConcurrentLinkedQueue, TimeUnit, Callable }
+import java.util.concurrent.TimeUnit.{ NANOSECONDS ⇒ NANOS, MILLISECONDS ⇒ MILLIS }
+import java.util.concurrent.atomic.{ AtomicBoolean }
+import java.lang.{ Iterable ⇒ JIterable }
+import java.util.{ LinkedList ⇒ JLinkedList }
import scala.annotation.tailrec
import scala.collection.generic.CanBuildFrom
@@ -58,8 +58,8 @@ object Futures {
def firstCompletedOf[T](futures: Iterable[Future[T]], timeout: Long = Long.MaxValue): Future[T] = {
val futureResult = new DefaultCompletableFuture[T](timeout)
- val completeFirst: Future[T] => Unit = _.value.foreach(futureResult complete _)
- for(f <- futures) f onComplete completeFirst
+ val completeFirst: Future[T] ⇒ Unit = _.value.foreach(futureResult complete _)
+ for (f ← futures) f onComplete completeFirst
futureResult
}
@@ -69,7 +69,7 @@ object Futures {
* Returns a Future to the result of the first future in the list that is completed
*/
def firstCompletedOf[T <: AnyRef](futures: java.lang.Iterable[Future[T]], timeout: Long): Future[T] =
- firstCompletedOf(scala.collection.JavaConversions.iterableAsScalaIterable(futures),timeout)
+ firstCompletedOf(scala.collection.JavaConversions.iterableAsScalaIterable(futures), timeout)
/**
* A non-blocking fold over the specified futures.
@@ -81,30 +81,31 @@ object Futures {
* val result = Futures.fold(0)(futures)(_ + _).await.result
*
*/
- def fold[T,R](zero: R, timeout: Long = Actor.TIMEOUT)(futures: Iterable[Future[T]])(foldFun: (R, T) => R): Future[R] = {
- if(futures.isEmpty) {
+ def fold[T, R](zero: R, timeout: Long = Actor.TIMEOUT)(futures: Iterable[Future[T]])(foldFun: (R, T) ⇒ R): Future[R] = {
+ if (futures.isEmpty) {
new AlreadyCompletedFuture[R](Right(zero))
} else {
val result = new DefaultCompletableFuture[R](timeout)
val results = new ConcurrentLinkedQueue[T]()
val allDone = futures.size
- val aggregate: Future[T] => Unit = f => if (!result.isCompleted) { //TODO: This is an optimization, is it premature?
+ val aggregate: Future[T] ⇒ Unit = f ⇒ if (!result.isCompleted) { //TODO: This is an optimization, is it premature?
f.value.get match {
- case r: Right[Throwable, T] =>
+ case r: Right[Throwable, T] ⇒
results add r.b
if (results.size == allDone) { //Only one thread can get here
try {
result completeWithResult scala.collection.JavaConversions.collectionAsScalaIterable(results).foldLeft(zero)(foldFun)
} catch {
- case e: Exception =>
+ case e: Exception ⇒
EventHandler.error(e, this, e.getMessage)
result completeWithException e
- } finally {
+ }
+ finally {
results.clear
}
}
- case l: Left[Throwable, T] =>
+ case l: Left[Throwable, T] ⇒
result completeWithException l.a
results.clear
}
@@ -123,7 +124,7 @@ object Futures {
* or the result of the fold.
*/
def fold[T <: AnyRef, R <: AnyRef](zero: R, timeout: Long, futures: java.lang.Iterable[Future[T]], fun: akka.japi.Function2[R, T, R]): Future[R] =
- fold(zero, timeout)(scala.collection.JavaConversions.iterableAsScalaIterable(futures))( fun.apply _ )
+ fold(zero, timeout)(scala.collection.JavaConversions.iterableAsScalaIterable(futures))(fun.apply _)
/**
* Initiates a fold over the supplied futures where the fold-zero is the result value of the Future that's completed first
@@ -132,23 +133,23 @@ object Futures {
* val result = Futures.reduce(futures)(_ + _).await.result
*
*/
- def reduce[T, R >: T](futures: Iterable[Future[T]], timeout: Long = Actor.TIMEOUT)(op: (R,T) => T): Future[R] = {
+ def reduce[T, R >: T](futures: Iterable[Future[T]], timeout: Long = Actor.TIMEOUT)(op: (R, T) ⇒ T): Future[R] = {
if (futures.isEmpty)
new AlreadyCompletedFuture[R](Left(new UnsupportedOperationException("empty reduce left")))
else {
val result = new DefaultCompletableFuture[R](timeout)
val seedFound = new AtomicBoolean(false)
- val seedFold: Future[T] => Unit = f => {
+ val seedFold: Future[T] ⇒ Unit = f ⇒ {
if (seedFound.compareAndSet(false, true)) { //Only the first completed should trigger the fold
f.value.get match {
- case r: Right[Throwable, T] =>
+ case r: Right[Throwable, T] ⇒
result.completeWith(fold(r.b, timeout)(futures.filterNot(_ eq f))(op))
- case l: Left[Throwable, T] =>
+ case l: Left[Throwable, T] ⇒
result.completeWithException(l.a)
}
}
}
- for(f <- futures) f onComplete seedFold //Attach the listener to the Futures
+ for (f ← futures) f onComplete seedFold //Attach the listener to the Futures
result
}
}
@@ -166,8 +167,8 @@ object Futures {
* Useful for reducing many Futures into a single Future.
*/
def sequence[A](in: JIterable[Future[A]], timeout: Long): Future[JIterable[A]] =
- scala.collection.JavaConversions.iterableAsScalaIterable(in).foldLeft(Future(new JLinkedList[A]()))((fr, fa) =>
- for (r <- fr; a <- fa) yield {
+ scala.collection.JavaConversions.iterableAsScalaIterable(in).foldLeft(Future(new JLinkedList[A]()))((fr, fa) ⇒
+ for (r ← fr; a ← fa) yield {
r add a
r
})
@@ -185,10 +186,10 @@ object Futures {
* This is useful for performing a parallel map. For example, to apply a function to all items of a list
* in parallel.
*/
- def traverse[A, B](in: JIterable[A], timeout: Long, fn: JFunc[A,Future[B]]): Future[JIterable[B]] =
- scala.collection.JavaConversions.iterableAsScalaIterable(in).foldLeft(Future(new JLinkedList[B]())){(fr, a) =>
+ def traverse[A, B](in: JIterable[A], timeout: Long, fn: JFunc[A, Future[B]]): Future[JIterable[B]] =
+ scala.collection.JavaConversions.iterableAsScalaIterable(in).foldLeft(Future(new JLinkedList[B]())) { (fr, a) ⇒
val fb = fn(a)
- for (r <- fr; b <- fb) yield {
+ for (r ← fr; b ← fb) yield {
r add b
r
}
@@ -200,13 +201,13 @@ object Futures {
* This is useful for performing a parallel map. For example, to apply a function to all items of a list
* in parallel.
*
- def traverse[A, B, M[_] <: Traversable[_]](in: M[A], timeout: Long = Actor.TIMEOUT)(fn: A => Future[B])(implicit cbf: CanBuildFrom[M[A], B, M[B]]): Future[M[B]] =
- in.foldLeft(new DefaultCompletableFuture[Builder[B, M[B]]](timeout).completeWithResult(cbf(in)): Future[Builder[B, M[B]]]) { (fr, a) =>
- val fb = fn(a.asInstanceOf[A])
- for (r <- fr; b <-fb) yield (r += b)
- }.map(_.result)
- */
- def traverse[A, B](in: JIterable[A], fn: JFunc[A,Future[B]]): Future[JIterable[B]] = traverse(in, Actor.TIMEOUT, fn)
+ * def traverse[A, B, M[_] <: Traversable[_]](in: M[A], timeout: Long = Actor.TIMEOUT)(fn: A => Future[B])(implicit cbf: CanBuildFrom[M[A], B, M[B]]): Future[M[B]] =
+ * in.foldLeft(new DefaultCompletableFuture[Builder[B, M[B]]](timeout).completeWithResult(cbf(in)): Future[Builder[B, M[B]]]) { (fr, a) =>
+ * val fb = fn(a.asInstanceOf[A])
+ * for (r <- fr; b <-fb) yield (r += b)
+ * }.map(_.result)
+ */
+ def traverse[A, B](in: JIterable[A], fn: JFunc[A, Future[B]]): Future[JIterable[B]] = traverse(in, Actor.TIMEOUT, fn)
}
object Future {
@@ -215,8 +216,8 @@ object Future {
* This method constructs and returns a Future that will eventually hold the result of the execution of the supplied body
* The execution is performed by the specified Dispatcher.
*/
- def apply[T](body: => T, timeout: Long = Actor.TIMEOUT)(implicit dispatcher: MessageDispatcher): Future[T] =
- dispatcher.dispatchFuture(() => body, timeout)
+ def apply[T](body: ⇒ T, timeout: Long = Actor.TIMEOUT)(implicit dispatcher: MessageDispatcher): Future[T] =
+ dispatcher.dispatchFuture(() ⇒ body, timeout)
/**
* Construct a completable channel
@@ -229,7 +230,7 @@ object Future {
/**
* Create an empty Future with default timeout
*/
- def empty[T](timeout : Long = Actor.TIMEOUT) = new DefaultCompletableFuture[T](timeout)
+ def empty[T](timeout: Long = Actor.TIMEOUT) = new DefaultCompletableFuture[T](timeout)
import scala.collection.mutable.Builder
import scala.collection.generic.CanBuildFrom
@@ -239,7 +240,7 @@ object Future {
* Useful for reducing many Futures into a single Future.
*/
def sequence[A, M[_] <: Traversable[_]](in: M[Future[A]], timeout: Long = Actor.TIMEOUT)(implicit cbf: CanBuildFrom[M[Future[A]], A, M[A]]): Future[M[A]] =
- in.foldLeft(new DefaultCompletableFuture[Builder[A, M[A]]](timeout).completeWithResult(cbf(in)): Future[Builder[A, M[A]]])((fr, fa) => for (r <- fr; a <- fa.asInstanceOf[Future[A]]) yield (r += a)).map(_.result)
+ in.foldLeft(new DefaultCompletableFuture[Builder[A, M[A]]](timeout).completeWithResult(cbf(in)): Future[Builder[A, M[A]]])((fr, fa) ⇒ for (r ← fr; a ← fa.asInstanceOf[Future[A]]) yield (r += a)).map(_.result)
/**
* Transforms a Traversable[A] into a Future[Traversable[B]] using the provided Function A => Future[B].
@@ -249,10 +250,10 @@ object Future {
* val myFutureList = Futures.traverse(myList)(x => Future(myFunc(x)))
*
*/
- def traverse[A, B, M[_] <: Traversable[_]](in: M[A], timeout: Long = Actor.TIMEOUT)(fn: A => Future[B])(implicit cbf: CanBuildFrom[M[A], B, M[B]]): Future[M[B]] =
- in.foldLeft(new DefaultCompletableFuture[Builder[B, M[B]]](timeout).completeWithResult(cbf(in)): Future[Builder[B, M[B]]]) { (fr, a) =>
+ def traverse[A, B, M[_] <: Traversable[_]](in: M[A], timeout: Long = Actor.TIMEOUT)(fn: A ⇒ Future[B])(implicit cbf: CanBuildFrom[M[A], B, M[B]]): Future[M[B]] =
+ in.foldLeft(new DefaultCompletableFuture[Builder[B, M[B]]](timeout).completeWithResult(cbf(in)): Future[Builder[B, M[B]]]) { (fr, a) ⇒
val fb = fn(a.asInstanceOf[A])
- for (r <- fr; b <-fb) yield (r += b)
+ for (r ← fr; b ← fb) yield (r += b)
}.map(_.result)
/**
@@ -271,16 +272,16 @@ object Future {
*
* The Delimited Continuations compiler plugin must be enabled in order to use this method.
*/
- def flow[A](body: => A @cps[Future[Any]], timeout: Long = Actor.TIMEOUT): Future[A] = {
+ def flow[A](body: ⇒ A @cps[Future[Any]], timeout: Long = Actor.TIMEOUT): Future[A] = {
val future = Promise[A](timeout)
- (reset(future.asInstanceOf[CompletableFuture[Any]].completeWithResult(body)): Future[Any]) onComplete { f =>
+ (reset(future.asInstanceOf[CompletableFuture[Any]].completeWithResult(body)): Future[Any]) onComplete { f ⇒
val opte = f.exception
if (opte.isDefined) future completeWithException (opte.get)
}
future
}
- private[akka] val callbacksPendingExecution = new ThreadLocal[Option[Stack[() => Unit]]]() {
+ private[akka] val callbacksPendingExecution = new ThreadLocal[Option[Stack[() ⇒ Unit]]]() {
override def initialValue = None
}
}
@@ -297,7 +298,7 @@ sealed trait Future[+T] {
* execution will fail. The normal result of getting a Future from an ActorRef using !!! will return
* an untyped Future.
*/
- def apply[A >: T](): A @cps[Future[Any]] = shift(this flatMap (_: A => Future[Any]))
+ def apply[A >: T](): A @cps[Future[Any]] = shift(this flatMap (_: A ⇒ Future[Any]))
/**
* Blocks awaiting completion of this Future, then returns the resulting value,
@@ -314,7 +315,7 @@ sealed trait Future[+T] {
* timeout has expired. In the case of the timeout expiring a
* FutureTimeoutException will be thrown.
*/
- def await : Future[T]
+ def await: Future[T]
/**
* Blocks the current thread until the Future has been completed or the
@@ -322,7 +323,7 @@ sealed trait Future[+T] {
* supplied at the constructuion of this Future.
* In the case of the timeout expiring a FutureTimeoutException will be thrown.
*/
- def await(atMost: Duration) : Future[T]
+ def await(atMost: Duration): Future[T]
/**
* Blocks the current thread until the Future has been completed. Use
@@ -330,7 +331,7 @@ sealed trait Future[+T] {
* indefinitely if the Future is never completed.
*/
@deprecated("Will be removed after 1.1, it's dangerous and can cause deadlocks, agony and insanity.", "1.1")
- def awaitBlocking : Future[T]
+ def awaitBlocking: Future[T]
/**
* Tests whether this Future has been completed.
@@ -381,7 +382,7 @@ sealed trait Future[+T] {
* Future. If the Future has already been completed, this will apply
* immediately.
*/
- def onComplete(func: Future[T] => Unit): Future[T]
+ def onComplete(func: Future[T] ⇒ Unit): Future[T]
/**
* When the future is completed with a valid result, apply the provided
@@ -393,7 +394,7 @@ sealed trait Future[+T] {
* }.await.result
*
*/
- final def receive(pf: PartialFunction[Any, Unit]): Future[T] = onComplete { f =>
+ final def receive(pf: PartialFunction[Any, Unit]): Future[T] = onComplete { f ⇒
val optr = f.result
if (optr.isDefined) {
val r = optr.get
@@ -417,7 +418,7 @@ sealed trait Future[+T] {
*/
final def collect[A](pf: PartialFunction[Any, A]): Future[A] = {
val fa = new DefaultCompletableFuture[A](timeoutInNanos, NANOS)
- onComplete { ft =>
+ onComplete { ft ⇒
val v = ft.value.get
fa complete {
if (v.isLeft) v.asInstanceOf[Either[Throwable, A]]
@@ -427,7 +428,7 @@ sealed trait Future[+T] {
if (pf isDefinedAt r) Right(pf(r))
else Left(new MatchError(r))
} catch {
- case e: Exception =>
+ case e: Exception ⇒
EventHandler.error(e, this, e.getMessage)
Left(e)
}
@@ -450,7 +451,7 @@ sealed trait Future[+T] {
*/
final def failure[A >: T](pf: PartialFunction[Throwable, A]): Future[A] = {
val fa = new DefaultCompletableFuture[A](timeoutInNanos, NANOS)
- onComplete { ft =>
+ onComplete { ft ⇒
val opte = ft.exception
fa complete {
if (opte.isDefined) {
@@ -459,7 +460,7 @@ sealed trait Future[+T] {
if (pf isDefinedAt e) Right(pf(e))
else Left(e)
} catch {
- case x: Exception => Left(x)
+ case x: Exception ⇒ Left(x)
}
} else ft.value.get
}
@@ -480,9 +481,9 @@ sealed trait Future[+T] {
* } yield b + "-" + c
*
*/
- final def map[A](f: T => A): Future[A] = {
+ final def map[A](f: T ⇒ A): Future[A] = {
val fa = new DefaultCompletableFuture[A](timeoutInNanos, NANOS)
- onComplete { ft =>
+ onComplete { ft ⇒
val optv = ft.value
if (optv.isDefined) {
val v = optv.get
@@ -492,7 +493,7 @@ sealed trait Future[+T] {
fa complete (try {
Right(f(v.right.get))
} catch {
- case e: Exception =>
+ case e: Exception ⇒
EventHandler.error(e, this, e.getMessage)
Left(e)
})
@@ -516,9 +517,9 @@ sealed trait Future[+T] {
* } yield b + "-" + c
*
*/
- final def flatMap[A](f: T => Future[A]): Future[A] = {
+ final def flatMap[A](f: T ⇒ Future[A]): Future[A] = {
val fa = new DefaultCompletableFuture[A](timeoutInNanos, NANOS)
- onComplete { ft =>
+ onComplete { ft ⇒
val optv = ft.value
if (optv.isDefined) {
val v = optv.get
@@ -528,7 +529,7 @@ sealed trait Future[+T] {
try {
fa.completeWith(f(v.right.get))
} catch {
- case e: Exception =>
+ case e: Exception ⇒
EventHandler.error(e, this, e.getMessage)
fa completeWithException e
}
@@ -538,15 +539,15 @@ sealed trait Future[+T] {
fa
}
- final def foreach(f: T => Unit): Unit = onComplete { ft =>
+ final def foreach(f: T ⇒ Unit): Unit = onComplete { ft ⇒
val optr = ft.result
if (optr.isDefined)
f(optr.get)
}
- final def filter(p: Any => Boolean): Future[Any] = {
+ final def filter(p: Any ⇒ Boolean): Future[Any] = {
val f = new DefaultCompletableFuture[T](timeoutInNanos, NANOS)
- onComplete { ft =>
+ onComplete { ft ⇒
val optv = ft.value
if (optv.isDefined) {
val v = optv.get
@@ -558,7 +559,7 @@ sealed trait Future[+T] {
if (p(r)) Right(r)
else Left(new MatchError(r))
} catch {
- case e: Exception =>
+ case e: Exception ⇒
EventHandler.error(e, this, e.getMessage)
Left(e)
})
@@ -583,13 +584,13 @@ sealed trait Future[+T] {
/* Java API */
final def onComplete[A >: T](proc: Procedure[Future[A]]): Future[T] = onComplete(proc(_))
- final def map[A >: T, B](f: JFunc[A,B]): Future[B] = map(f(_))
+ final def map[A >: T, B](f: JFunc[A, B]): Future[B] = map(f(_))
- final def flatMap[A >: T, B](f: JFunc[A,Future[B]]): Future[B] = flatMap(f(_))
+ final def flatMap[A >: T, B](f: JFunc[A, Future[B]]): Future[B] = flatMap(f(_))
final def foreach[A >: T](proc: Procedure[A]): Unit = foreach(proc(_))
- final def filter(p: JFunc[Any,Boolean]): Future[Any] = filter(p(_))
+ final def filter(p: JFunc[Any, Boolean]): Future[Any] = filter(p(_))
}
@@ -629,19 +630,19 @@ trait CompletableFuture[T] extends Future[T] {
* @return this.
*/
final def completeWith(other: Future[T]): Future[T] = {
- other onComplete { f => complete(f.value.get) }
+ other onComplete { f ⇒ complete(f.value.get) }
this
}
- final def << (value: T): Future[T] @cps[Future[Any]] = shift { cont: (Future[T] => Future[Any]) => cont(complete(Right(value))) }
+ final def <<(value: T): Future[T] @cps[Future[Any]] = shift { cont: (Future[T] ⇒ Future[Any]) ⇒ cont(complete(Right(value))) }
- final def << (other: Future[T]): Future[T] @cps[Future[Any]] = shift { cont: (Future[T] => Future[Any]) =>
+ final def <<(other: Future[T]): Future[T] @cps[Future[Any]] = shift { cont: (Future[T] ⇒ Future[Any]) ⇒
val fr = new DefaultCompletableFuture[Any](Actor.TIMEOUT)
- this completeWith other onComplete { f =>
+ this completeWith other onComplete { f ⇒
try {
fr completeWith cont(f)
} catch {
- case e: Exception =>
+ case e: Exception ⇒
EventHandler.error(e, this, e.getMessage)
fr completeWithException e
}
@@ -665,7 +666,7 @@ class DefaultCompletableFuture[T](timeout: Long, timeunit: TimeUnit) extends Com
private val _lock = new ReentrantLock
private val _signal = _lock.newCondition
private var _value: Option[Either[Throwable, T]] = None
- private var _listeners: List[Future[T] => Unit] = Nil
+ private var _listeners: List[Future[T] ⇒ Unit] = Nil
/**
* Must be called inside _lock.lock<->_lock.unlock
@@ -677,7 +678,7 @@ class DefaultCompletableFuture[T](timeout: Long, timeunit: TimeUnit) extends Com
val remainingNanos = try {
_signal.awaitNanos(waitTimeNanos)
} catch {
- case e: InterruptedException =>
+ case e: InterruptedException ⇒
waitTimeNanos - (currentTimeInNanos - start)
}
awaitUnsafe(remainingNanos)
@@ -736,7 +737,8 @@ class DefaultCompletableFuture[T](timeout: Long, timeunit: TimeUnit) extends Com
}
if (notifyTheseListeners.nonEmpty) { // Steps to ensure we don't run into a stack-overflow situation
- @tailrec def runCallbacks(rest: List[Future[T] => Unit], callbacks: Stack[() => Unit]) {
+ @tailrec
+ def runCallbacks(rest: List[Future[T] ⇒ Unit], callbacks: Stack[() ⇒ Unit]) {
if (rest.nonEmpty) {
notifyCompleted(rest.head)
while (callbacks.nonEmpty) { callbacks.pop().apply() }
@@ -746,13 +748,13 @@ class DefaultCompletableFuture[T](timeout: Long, timeunit: TimeUnit) extends Com
val pending = Future.callbacksPendingExecution.get
if (pending.isDefined) { //Instead of nesting the calls to the callbacks (leading to stack overflow)
- pending.get.push(() => { // Linearize/aggregate callbacks at top level and then execute
+ pending.get.push(() ⇒ { // Linearize/aggregate callbacks at top level and then execute
val doNotify = notifyCompleted _ //Hoist closure to avoid garbage
notifyTheseListeners foreach doNotify
})
} else {
try {
- val callbacks = Stack[() => Unit]() // Allocate new aggregator for pending callbacks
+ val callbacks = Stack[() ⇒ Unit]() // Allocate new aggregator for pending callbacks
Future.callbacksPendingExecution.set(Some(callbacks)) // Specify the callback aggregator
runCallbacks(notifyTheseListeners, callbacks) // Execute callbacks, if they trigger new callbacks, they are aggregated
} finally { Future.callbacksPendingExecution.set(None) } // Ensure cleanup
@@ -762,11 +764,11 @@ class DefaultCompletableFuture[T](timeout: Long, timeunit: TimeUnit) extends Com
this
}
- def onComplete(func: Future[T] => Unit): CompletableFuture[T] = {
+ def onComplete(func: Future[T] ⇒ Unit): CompletableFuture[T] = {
_lock.lock
val notifyNow = try {
if (_value.isEmpty) {
- if(!isExpired) { //Only add the listener if the future isn't expired
+ if (!isExpired) { //Only add the listener if the future isn't expired
_listeners ::= func
false
} else false //Will never run the callback since the future is expired
@@ -780,16 +782,18 @@ class DefaultCompletableFuture[T](timeout: Long, timeunit: TimeUnit) extends Com
this
}
- private def notifyCompleted(func: Future[T] => Unit) {
+ private def notifyCompleted(func: Future[T] ⇒ Unit) {
try {
func(this)
} catch {
- case e => EventHandler notify EventHandler.Error(e, this)
+ case e ⇒ EventHandler notify EventHandler.Error(e, this)
}
}
- @inline private def currentTimeInNanos: Long = MILLIS.toNanos(System.currentTimeMillis)
- @inline private def timeLeft(): Long = timeoutInNanos - (currentTimeInNanos - _startTimeInNanos)
+ @inline
+ private def currentTimeInNanos: Long = MILLIS.toNanos(System.currentTimeMillis)
+ @inline
+ private def timeLeft(): Long = timeoutInNanos - (currentTimeInNanos - _startTimeInNanos)
}
/**
@@ -800,10 +804,10 @@ sealed class AlreadyCompletedFuture[T](suppliedValue: Either[Throwable, T]) exte
val value = Some(suppliedValue)
def complete(value: Either[Throwable, T]): CompletableFuture[T] = this
- def onComplete(func: Future[T] => Unit): Future[T] = { func(this); this }
+ def onComplete(func: Future[T] ⇒ Unit): Future[T] = { func(this); this }
def await(atMost: Duration): Future[T] = this
- def await : Future[T] = this
- def awaitBlocking : Future[T] = this
+ def await: Future[T] = this
+ def awaitBlocking: Future[T] = this
def isExpired: Boolean = true
def timeoutInNanos: Long = 0
}
diff --git a/akka-actor/src/main/scala/akka/dispatch/MailboxHandling.scala b/akka-actor/src/main/scala/akka/dispatch/MailboxHandling.scala
index 3b3032ad90..8a0579676e 100644
--- a/akka-actor/src/main/scala/akka/dispatch/MailboxHandling.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/MailboxHandling.scala
@@ -6,7 +6,7 @@ package akka.dispatch
import akka.AkkaException
-import java.util.{Comparator, PriorityQueue}
+import java.util.{ Comparator, PriorityQueue }
import java.util.concurrent._
import akka.util._
@@ -31,42 +31,38 @@ sealed trait MailboxType
case class UnboundedMailbox() extends MailboxType
case class BoundedMailbox(
- val capacity: Int = { if (Dispatchers.MAILBOX_CAPACITY < 0) Int.MaxValue else Dispatchers.MAILBOX_CAPACITY },
+ val capacity: Int = { if (Dispatchers.MAILBOX_CAPACITY < 0) Int.MaxValue else Dispatchers.MAILBOX_CAPACITY },
val pushTimeOut: Duration = Dispatchers.MAILBOX_PUSH_TIME_OUT) extends MailboxType {
- if (capacity < 0) throw new IllegalArgumentException("The capacity for BoundedMailbox can not be negative")
+ if (capacity < 0) throw new IllegalArgumentException("The capacity for BoundedMailbox can not be negative")
if (pushTimeOut eq null) throw new IllegalArgumentException("The push time-out for BoundedMailbox can not be null")
}
-trait UnboundedMessageQueueSemantics extends MessageQueue { self: BlockingQueue[MessageInvocation] =>
- @inline final def enqueue(handle: MessageInvocation): Unit = this add handle
- @inline final def dequeue(): MessageInvocation = this.poll()
+trait UnboundedMessageQueueSemantics extends MessageQueue { self: BlockingQueue[MessageInvocation] ⇒
+ @inline
+ final def enqueue(handle: MessageInvocation): Unit = this add handle
+ @inline
+ final def dequeue(): MessageInvocation = this.poll()
}
-trait BoundedMessageQueueSemantics extends MessageQueue { self: BlockingQueue[MessageInvocation] =>
+trait BoundedMessageQueueSemantics extends MessageQueue { self: BlockingQueue[MessageInvocation] ⇒
def pushTimeOut: Duration
final def enqueue(handle: MessageInvocation) {
if (pushTimeOut.length > 0) {
this.offer(handle, pushTimeOut.length, pushTimeOut.unit) || {
- throw new MessageQueueAppendFailedException("Couldn't enqueue message " + handle + " to " + toString) }
+ throw new MessageQueueAppendFailedException("Couldn't enqueue message " + handle + " to " + toString)
+ }
} else this put handle
}
- @inline final def dequeue(): MessageInvocation = this.poll()
+ @inline
+ final def dequeue(): MessageInvocation = this.poll()
}
-class DefaultUnboundedMessageQueue extends
- LinkedBlockingQueue[MessageInvocation] with
- UnboundedMessageQueueSemantics
+class DefaultUnboundedMessageQueue extends LinkedBlockingQueue[MessageInvocation] with UnboundedMessageQueueSemantics
-class DefaultBoundedMessageQueue(capacity: Int, val pushTimeOut: Duration) extends
- LinkedBlockingQueue[MessageInvocation](capacity) with
- BoundedMessageQueueSemantics
+class DefaultBoundedMessageQueue(capacity: Int, val pushTimeOut: Duration) extends LinkedBlockingQueue[MessageInvocation](capacity) with BoundedMessageQueueSemantics
-class UnboundedPriorityMessageQueue(cmp: Comparator[MessageInvocation]) extends
- PriorityBlockingQueue[MessageInvocation](11, cmp) with
- UnboundedMessageQueueSemantics
+class UnboundedPriorityMessageQueue(cmp: Comparator[MessageInvocation]) extends PriorityBlockingQueue[MessageInvocation](11, cmp) with UnboundedMessageQueueSemantics
-class BoundedPriorityMessageQueue(capacity: Int, val pushTimeOut: Duration, cmp: Comparator[MessageInvocation]) extends
- BoundedBlockingQueue[MessageInvocation](capacity, new PriorityQueue[MessageInvocation](11, cmp)) with
- BoundedMessageQueueSemantics
+class BoundedPriorityMessageQueue(capacity: Int, val pushTimeOut: Duration, cmp: Comparator[MessageInvocation]) extends BoundedBlockingQueue[MessageInvocation](capacity, new PriorityQueue[MessageInvocation](11, cmp)) with BoundedMessageQueueSemantics
diff --git a/akka-actor/src/main/scala/akka/dispatch/MessageHandling.scala b/akka-actor/src/main/scala/akka/dispatch/MessageHandling.scala
index 5fbc97ed36..f64c8109cb 100644
--- a/akka-actor/src/main/scala/akka/dispatch/MessageHandling.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/MessageHandling.scala
@@ -9,8 +9,8 @@ import java.util.concurrent.atomic.AtomicLong
import akka.event.EventHandler
import akka.config.Configuration
import akka.config.Config.TIME_UNIT
-import akka.util.{Duration, Switch, ReentrantGuard}
-import java.util.concurrent.ThreadPoolExecutor.{AbortPolicy, CallerRunsPolicy, DiscardOldestPolicy, DiscardPolicy}
+import akka.util.{ Duration, Switch, ReentrantGuard }
+import java.util.concurrent.ThreadPoolExecutor.{ AbortPolicy, CallerRunsPolicy, DiscardOldestPolicy, DiscardPolicy }
import akka.actor._
/**
@@ -26,21 +26,22 @@ final case class MessageInvocation(receiver: ActorRef,
try {
receiver.invoke(this)
} catch {
- case e: NullPointerException => throw new ActorInitializationException(
+ case e: NullPointerException ⇒ throw new ActorInitializationException(
"Don't call 'self ! message' in the Actor's constructor (in Scala this means in the body of the class).")
}
}
}
-final case class FutureInvocation[T](future: CompletableFuture[T], function: () => T, cleanup: () => Unit) extends Runnable {
+final case class FutureInvocation[T](future: CompletableFuture[T], function: () ⇒ T, cleanup: () ⇒ Unit) extends Runnable {
def run() {
future complete (try {
Right(function())
} catch {
- case e =>
+ case e ⇒
EventHandler.error(e, this, e.getMessage)
Left(e)
- } finally {
+ }
+ finally {
cleanup()
})
}
@@ -95,7 +96,7 @@ trait MessageDispatcher {
dispatch(invocation)
}
- private[akka] final def dispatchFuture[T](block: () => T, timeout: Long): Future[T] = {
+ private[akka] final def dispatchFuture[T](block: () ⇒ T, timeout: Long): Future[T] = {
futures.getAndIncrement()
try {
val future = new DefaultCompletableFuture[T](timeout)
@@ -110,23 +111,23 @@ trait MessageDispatcher {
executeFuture(FutureInvocation[T](future, block, futureCleanup))
future
} catch {
- case e =>
+ case e ⇒
futures.decrementAndGet
throw e
}
}
- private val futureCleanup: () => Unit =
- () => if (futures.decrementAndGet() == 0) {
+ private val futureCleanup: () ⇒ Unit =
+ () ⇒ if (futures.decrementAndGet() == 0) {
guard withGuard {
if (futures.get == 0 && uuids.isEmpty) {
shutdownSchedule match {
- case UNSCHEDULED =>
+ case UNSCHEDULED ⇒
shutdownSchedule = SCHEDULED
Scheduler.scheduleOnce(shutdownAction, timeoutMs, TimeUnit.MILLISECONDS)
- case SCHEDULED =>
+ case SCHEDULED ⇒
shutdownSchedule = RESCHEDULED
- case RESCHEDULED => //Already marked for reschedule
+ case RESCHEDULED ⇒ //Already marked for reschedule
}
}
}
@@ -149,12 +150,12 @@ trait MessageDispatcher {
actorRef.mailbox = null
if (uuids.isEmpty && futures.get == 0) {
shutdownSchedule match {
- case UNSCHEDULED =>
+ case UNSCHEDULED ⇒
shutdownSchedule = SCHEDULED
Scheduler.scheduleOnce(shutdownAction, timeoutMs, TimeUnit.MILLISECONDS)
- case SCHEDULED =>
+ case SCHEDULED ⇒
shutdownSchedule = RESCHEDULED
- case RESCHEDULED => //Already marked for reschedule
+ case RESCHEDULED ⇒ //Already marked for reschedule
}
}
}
@@ -168,8 +169,8 @@ trait MessageDispatcher {
while (i.hasNext()) {
val uuid = i.next()
Actor.registry.local.actorFor(uuid) match {
- case Some(actor) => actor.stop()
- case None => {}
+ case Some(actor) ⇒ actor.stop()
+ case None ⇒ {}
}
}
}
@@ -178,17 +179,17 @@ trait MessageDispatcher {
def run() {
guard withGuard {
shutdownSchedule match {
- case RESCHEDULED =>
+ case RESCHEDULED ⇒
shutdownSchedule = SCHEDULED
Scheduler.scheduleOnce(this, timeoutMs, TimeUnit.MILLISECONDS)
- case SCHEDULED =>
+ case SCHEDULED ⇒
if (uuids.isEmpty && futures.get == 0) {
active switchOff {
shutdown() // shut down in the dispatcher's references is zero
}
}
shutdownSchedule = UNSCHEDULED
- case UNSCHEDULED => //Do nothing
+ case UNSCHEDULED ⇒ //Do nothing
}
}
}
@@ -258,22 +259,22 @@ abstract class MessageDispatcherConfigurator {
}
}
- def configureThreadPool(config: Configuration, createDispatcher: => (ThreadPoolConfig) => MessageDispatcher): ThreadPoolConfigDispatcherBuilder = {
+ def configureThreadPool(config: Configuration, createDispatcher: ⇒ (ThreadPoolConfig) ⇒ MessageDispatcher): ThreadPoolConfigDispatcherBuilder = {
import ThreadPoolConfigDispatcherBuilder.conf_?
//Apply the following options to the config if they are present in the config
ThreadPoolConfigDispatcherBuilder(createDispatcher, ThreadPoolConfig()).configure(
- conf_?(config getInt "keep-alive-time")(time => _.setKeepAliveTime(Duration(time, TIME_UNIT))),
- conf_?(config getDouble "core-pool-size-factor")(factor => _.setCorePoolSizeFromFactor(factor)),
- conf_?(config getDouble "max-pool-size-factor")(factor => _.setMaxPoolSizeFromFactor(factor)),
- conf_?(config getInt "executor-bounds")(bounds => _.setExecutorBounds(bounds)),
- conf_?(config getBool "allow-core-timeout")(allow => _.setAllowCoreThreadTimeout(allow)),
+ conf_?(config getInt "keep-alive-time")(time ⇒ _.setKeepAliveTime(Duration(time, TIME_UNIT))),
+ conf_?(config getDouble "core-pool-size-factor")(factor ⇒ _.setCorePoolSizeFromFactor(factor)),
+ conf_?(config getDouble "max-pool-size-factor")(factor ⇒ _.setMaxPoolSizeFromFactor(factor)),
+ conf_?(config getInt "executor-bounds")(bounds ⇒ _.setExecutorBounds(bounds)),
+ conf_?(config getBool "allow-core-timeout")(allow ⇒ _.setAllowCoreThreadTimeout(allow)),
conf_?(config getString "rejection-policy" map {
- case "abort" => new AbortPolicy()
- case "caller-runs" => new CallerRunsPolicy()
- case "discard-oldest" => new DiscardOldestPolicy()
- case "discard" => new DiscardPolicy()
- case x => throw new IllegalArgumentException("[%s] is not a valid rejectionPolicy!" format x)
- })(policy => _.setRejectionPolicy(policy)))
+ case "abort" ⇒ new AbortPolicy()
+ case "caller-runs" ⇒ new CallerRunsPolicy()
+ case "discard-oldest" ⇒ new DiscardOldestPolicy()
+ case "discard" ⇒ new DiscardPolicy()
+ case x ⇒ throw new IllegalArgumentException("[%s] is not a valid rejectionPolicy!" format x)
+ })(policy ⇒ _.setRejectionPolicy(policy)))
}
}
diff --git a/akka-actor/src/main/scala/akka/dispatch/ThreadBasedDispatcher.scala b/akka-actor/src/main/scala/akka/dispatch/ThreadBasedDispatcher.scala
index ae2c2ecfc3..c365329834 100644
--- a/akka-actor/src/main/scala/akka/dispatch/ThreadBasedDispatcher.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/ThreadBasedDispatcher.scala
@@ -4,7 +4,7 @@
package akka.dispatch
-import akka.actor.{ActorRef}
+import akka.actor.{ ActorRef }
import akka.util.Duration
import java.util.concurrent.atomic.AtomicReference
@@ -16,7 +16,7 @@ import java.util.concurrent.atomic.AtomicReference
*/
class ThreadBasedDispatcher(_actor: ActorRef, _mailboxType: MailboxType)
extends ExecutorBasedEventDrivenDispatcher(
- _actor.uuid.toString,Dispatchers.THROUGHPUT,-1,_mailboxType,ThreadBasedDispatcher.oneThread) {
+ _actor.uuid.toString, Dispatchers.THROUGHPUT, -1, _mailboxType, ThreadBasedDispatcher.oneThread) {
private[akka] val owner = new AtomicReference[ActorRef](_actor)
@@ -32,13 +32,13 @@ class ThreadBasedDispatcher(_actor: ActorRef, _mailboxType: MailboxType)
override def register(actorRef: ActorRef) = {
val actor = owner.get()
if ((actor ne null) && actorRef != actor) throw new IllegalArgumentException("Cannot register to anyone but " + actor)
- owner.compareAndSet(null,actorRef) //Register if unregistered
+ owner.compareAndSet(null, actorRef) //Register if unregistered
super.register(actorRef)
}
override def unregister(actorRef: ActorRef) = {
super.unregister(actorRef)
- owner.compareAndSet(actorRef,null) //Unregister (prevent memory leak)
+ owner.compareAndSet(actorRef, null) //Unregister (prevent memory leak)
}
}
diff --git a/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala b/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala
index a1ae48a6ae..f260cf39b4 100644
--- a/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala
@@ -6,7 +6,7 @@ package akka.dispatch
import java.util.Collection
import java.util.concurrent._
-import atomic.{AtomicLong, AtomicInteger}
+import atomic.{ AtomicLong, AtomicInteger }
import ThreadPoolExecutor.CallerRunsPolicy
import akka.util.Duration
@@ -14,14 +14,14 @@ import akka.event.EventHandler
object ThreadPoolConfig {
type Bounds = Int
- type FlowHandler = Either[RejectedExecutionHandler,Bounds]
- type QueueFactory = () => BlockingQueue[Runnable]
+ type FlowHandler = Either[RejectedExecutionHandler, Bounds]
+ type QueueFactory = () ⇒ BlockingQueue[Runnable]
val defaultAllowCoreThreadTimeout: Boolean = false
- val defaultCorePoolSize: Int = 16
- val defaultMaxPoolSize: Int = 128
- val defaultTimeout: Duration = Duration(60000L,TimeUnit.MILLISECONDS)
- def defaultFlowHandler: FlowHandler = flowHandler(new CallerRunsPolicy)
+ val defaultCorePoolSize: Int = 16
+ val defaultMaxPoolSize: Int = 128
+ val defaultTimeout: Duration = Duration(60000L, TimeUnit.MILLISECONDS)
+ def defaultFlowHandler: FlowHandler = flowHandler(new CallerRunsPolicy)
def flowHandler(rejectionHandler: RejectedExecutionHandler): FlowHandler = Left(rejectionHandler)
def flowHandler(bounds: Int): FlowHandler = Right(bounds)
@@ -31,46 +31,46 @@ object ThreadPoolConfig {
(Runtime.getRuntime.availableProcessors * multiplier).ceil.toInt
def arrayBlockingQueue(capacity: Int, fair: Boolean): QueueFactory =
- () => new ArrayBlockingQueue[Runnable](capacity,fair)
+ () ⇒ new ArrayBlockingQueue[Runnable](capacity, fair)
def synchronousQueue(fair: Boolean): QueueFactory =
- () => new SynchronousQueue[Runnable](fair)
+ () ⇒ new SynchronousQueue[Runnable](fair)
def linkedBlockingQueue(): QueueFactory =
- () => new LinkedBlockingQueue[Runnable]()
+ () ⇒ new LinkedBlockingQueue[Runnable]()
def linkedBlockingQueue(capacity: Int): QueueFactory =
- () => new LinkedBlockingQueue[Runnable](capacity)
+ () ⇒ new LinkedBlockingQueue[Runnable](capacity)
def reusableQueue(queue: BlockingQueue[Runnable]): QueueFactory =
- () => queue
+ () ⇒ queue
def reusableQueue(queueFactory: QueueFactory): QueueFactory = {
val queue = queueFactory()
- () => queue
+ () ⇒ queue
}
}
case class ThreadPoolConfig(allowCorePoolTimeout: Boolean = ThreadPoolConfig.defaultAllowCoreThreadTimeout,
- corePoolSize: Int = ThreadPoolConfig.defaultCorePoolSize,
- maxPoolSize: Int = ThreadPoolConfig.defaultMaxPoolSize,
- threadTimeout: Duration = ThreadPoolConfig.defaultTimeout,
- flowHandler: ThreadPoolConfig.FlowHandler = ThreadPoolConfig.defaultFlowHandler,
- queueFactory: ThreadPoolConfig.QueueFactory = ThreadPoolConfig.linkedBlockingQueue()) {
+ corePoolSize: Int = ThreadPoolConfig.defaultCorePoolSize,
+ maxPoolSize: Int = ThreadPoolConfig.defaultMaxPoolSize,
+ threadTimeout: Duration = ThreadPoolConfig.defaultTimeout,
+ flowHandler: ThreadPoolConfig.FlowHandler = ThreadPoolConfig.defaultFlowHandler,
+ queueFactory: ThreadPoolConfig.QueueFactory = ThreadPoolConfig.linkedBlockingQueue()) {
final def createLazyExecutorService(threadFactory: ThreadFactory): ExecutorService =
new LazyExecutorServiceWrapper(createExecutorService(threadFactory))
final def createExecutorService(threadFactory: ThreadFactory): ExecutorService = {
flowHandler match {
- case Left(rejectHandler) =>
+ case Left(rejectHandler) ⇒
val service = new ThreadPoolExecutor(corePoolSize, maxPoolSize, threadTimeout.length, threadTimeout.unit, queueFactory(), threadFactory, rejectHandler)
service.allowCoreThreadTimeOut(allowCorePoolTimeout)
service
- case Right(bounds) =>
+ case Right(bounds) ⇒
val service = new ThreadPoolExecutor(corePoolSize, maxPoolSize, threadTimeout.length, threadTimeout.unit, queueFactory(), threadFactory)
service.allowCoreThreadTimeOut(allowCorePoolTimeout)
- new BoundedExecutorDecorator(service,bounds)
+ new BoundedExecutorDecorator(service, bounds)
}
}
}
@@ -80,11 +80,10 @@ trait DispatcherBuilder {
}
object ThreadPoolConfigDispatcherBuilder {
- def conf_?[T](opt: Option[T])(fun: (T) => ThreadPoolConfigDispatcherBuilder => ThreadPoolConfigDispatcherBuilder):
- Option[(ThreadPoolConfigDispatcherBuilder) => ThreadPoolConfigDispatcherBuilder] = opt map fun
+ def conf_?[T](opt: Option[T])(fun: (T) ⇒ ThreadPoolConfigDispatcherBuilder ⇒ ThreadPoolConfigDispatcherBuilder): Option[(ThreadPoolConfigDispatcherBuilder) ⇒ ThreadPoolConfigDispatcherBuilder] = opt map fun
}
-case class ThreadPoolConfigDispatcherBuilder(dispatcherFactory: (ThreadPoolConfig) => MessageDispatcher, config: ThreadPoolConfig) extends DispatcherBuilder {
+case class ThreadPoolConfigDispatcherBuilder(dispatcherFactory: (ThreadPoolConfig) ⇒ MessageDispatcher, config: ThreadPoolConfig) extends DispatcherBuilder {
import ThreadPoolConfig._
def build = dispatcherFactory(config)
@@ -94,8 +93,8 @@ case class ThreadPoolConfigDispatcherBuilder(dispatcherFactory: (ThreadPoolConfi
def withNewThreadPoolWithCustomBlockingQueue(newQueueFactory: QueueFactory): ThreadPoolConfigDispatcherBuilder =
this.copy(config = config.copy(flowHandler = defaultFlowHandler, queueFactory = newQueueFactory))
- def withNewThreadPoolWithCustomBlockingQueue(queue: BlockingQueue[Runnable]): ThreadPoolConfigDispatcherBuilder =
- withNewThreadPoolWithCustomBlockingQueue(reusableQueue(queue))
+ def withNewThreadPoolWithCustomBlockingQueue(queue: BlockingQueue[Runnable]): ThreadPoolConfigDispatcherBuilder =
+ withNewThreadPoolWithCustomBlockingQueue(reusableQueue(queue))
def withNewThreadPoolWithLinkedBlockingQueueWithUnboundedCapacity: ThreadPoolConfigDispatcherBuilder =
this.copy(config = config.copy(queueFactory = linkedBlockingQueue(), flowHandler = defaultFlowHandler))
@@ -107,7 +106,7 @@ case class ThreadPoolConfigDispatcherBuilder(dispatcherFactory: (ThreadPoolConfi
this.copy(config = config.copy(queueFactory = synchronousQueue(fair), flowHandler = defaultFlowHandler))
def withNewThreadPoolWithArrayBlockingQueueWithCapacityAndFairness(capacity: Int, fair: Boolean): ThreadPoolConfigDispatcherBuilder =
- this.copy(config = config.copy(queueFactory = arrayBlockingQueue(capacity,fair), flowHandler = defaultFlowHandler))
+ this.copy(config = config.copy(queueFactory = arrayBlockingQueue(capacity, fair), flowHandler = defaultFlowHandler))
def setCorePoolSize(size: Int): ThreadPoolConfigDispatcherBuilder =
this.copy(config = config.copy(corePoolSize = size))
@@ -125,7 +124,7 @@ case class ThreadPoolConfigDispatcherBuilder(dispatcherFactory: (ThreadPoolConfi
this.copy(config = config.copy(flowHandler = flowHandler(bounds)))
def setKeepAliveTimeInMillis(time: Long): ThreadPoolConfigDispatcherBuilder =
- setKeepAliveTime(Duration(time,TimeUnit.MILLISECONDS))
+ setKeepAliveTime(Duration(time, TimeUnit.MILLISECONDS))
def setKeepAliveTime(time: Duration): ThreadPoolConfigDispatcherBuilder =
this.copy(config = config.copy(threadTimeout = time))
@@ -139,8 +138,7 @@ case class ThreadPoolConfigDispatcherBuilder(dispatcherFactory: (ThreadPoolConfi
def setAllowCoreThreadTimeout(allow: Boolean): ThreadPoolConfigDispatcherBuilder =
this.copy(config = config.copy(allowCorePoolTimeout = allow))
- def configure(fs: Option[Function[ThreadPoolConfigDispatcherBuilder,ThreadPoolConfigDispatcherBuilder]]*):
- ThreadPoolConfigDispatcherBuilder = fs.foldLeft(this)( (c,f) => f.map( _(c) ).getOrElse(c))
+ def configure(fs: Option[Function[ThreadPoolConfigDispatcherBuilder, ThreadPoolConfigDispatcherBuilder]]*): ThreadPoolConfigDispatcherBuilder = fs.foldLeft(this)((c, f) ⇒ f.map(_(c)).getOrElse(c))
}
/**
@@ -159,15 +157,15 @@ object MonitorableThread {
val DEFAULT_NAME = "MonitorableThread"
// FIXME use MonitorableThread.created and MonitorableThread.alive in monitoring
- val created = new AtomicInteger
- val alive = new AtomicInteger
+ val created = new AtomicInteger
+ val alive = new AtomicInteger
}
/**
* @author Jonas Bonér
*/
class MonitorableThread(runnable: Runnable, name: String)
- extends Thread(runnable, name + "-" + MonitorableThread.created.incrementAndGet) {
+ extends Thread(runnable, name + "-" + MonitorableThread.created.incrementAndGet) {
setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
def uncaughtException(thread: Thread, cause: Throwable) = {}
@@ -202,10 +200,10 @@ class BoundedExecutorDecorator(val executor: ExecutorService, bound: Int) extend
}
})
} catch {
- case e: RejectedExecutionException =>
+ case e: RejectedExecutionException ⇒
EventHandler.warning(this, e.toString)
semaphore.release
- case e: Throwable =>
+ case e: Throwable ⇒
EventHandler.error(e, this, e.getMessage)
throw e
}
@@ -252,6 +250,6 @@ trait LazyExecutorService extends ExecutorServiceDelegate {
}
}
-class LazyExecutorServiceWrapper(executorFactory: => ExecutorService) extends LazyExecutorService {
+class LazyExecutorServiceWrapper(executorFactory: ⇒ ExecutorService) extends LazyExecutorService {
def createExecutor = executorFactory
}
diff --git a/akka-actor/src/main/scala/akka/event/EventHandler.scala b/akka-actor/src/main/scala/akka/event/EventHandler.scala
index 8f8c59a497..4cbab1eaef 100644
--- a/akka-actor/src/main/scala/akka/event/EventHandler.scala
+++ b/akka-actor/src/main/scala/akka/event/EventHandler.scala
@@ -7,7 +7,7 @@ package akka.event
import akka.actor._
import akka.config.Config._
import akka.config.ConfigurationException
-import akka.util.{ListenerManagement, ReflectiveAccess}
+import akka.util.{ ListenerManagement, ReflectiveAccess }
import akka.serialization._
import akka.AkkaException
@@ -53,18 +53,19 @@ import akka.AkkaException
* @author Jonas Bonér
*/
object EventHandler extends ListenerManagement {
- import java.io.{StringWriter, PrintWriter}
+ import java.io.{ StringWriter, PrintWriter }
import java.text.DateFormat
import java.util.Date
import akka.dispatch.Dispatchers
- val ErrorLevel = 1
+ val ErrorLevel = 1
val WarningLevel = 2
- val InfoLevel = 3
- val DebugLevel = 4
+ val InfoLevel = 3
+ val DebugLevel = 4
sealed trait Event {
- @transient val thread: Thread = Thread.currentThread
+ @transient
+ val thread: Thread = Thread.currentThread
val level: Int
}
case class Error(cause: Throwable, instance: AnyRef, message: Any = "") extends Event {
@@ -80,10 +81,10 @@ object EventHandler extends ListenerManagement {
override val level = DebugLevel
}
- val error = "[ERROR] [%s] [%s] [%s] %s\n%s".intern
+ val error = "[ERROR] [%s] [%s] [%s] %s\n%s".intern
val warning = "[WARN] [%s] [%s] [%s] %s".intern
- val info = "[INFO] [%s] [%s] [%s] %s".intern
- val debug = "[DEBUG] [%s] [%s] [%s] %s".intern
+ val info = "[INFO] [%s] [%s] [%s] %s".intern
+ val debug = "[DEBUG] [%s] [%s] [%s] %s".intern
val generic = "[GENERIC] [%s] [%s]".intern
class EventHandlerException extends AkkaException
@@ -93,36 +94,36 @@ object EventHandler extends ListenerManagement {
implicit object defaultListenerFormat extends StatelessActorFormat[DefaultListener]
val level: Int = config.getString("akka.event-handler-level", "INFO") match {
- case "ERROR" => ErrorLevel
- case "WARNING" => WarningLevel
- case "INFO" => InfoLevel
- case "DEBUG" => DebugLevel
- case unknown => throw new ConfigurationException(
- "Configuration option 'akka.event-handler-level' is invalid [" + unknown + "]")
+ case "ERROR" ⇒ ErrorLevel
+ case "WARNING" ⇒ WarningLevel
+ case "INFO" ⇒ InfoLevel
+ case "DEBUG" ⇒ DebugLevel
+ case unknown ⇒ throw new ConfigurationException(
+ "Configuration option 'akka.event-handler-level' is invalid [" + unknown + "]")
}
def start() {
try {
val defaultListeners = config.getList("akka.event-handlers") match {
- case Nil => "akka.event.EventHandler$DefaultListener" :: Nil
- case listeners => listeners
+ case Nil ⇒ "akka.event.EventHandler$DefaultListener" :: Nil
+ case listeners ⇒ listeners
}
- defaultListeners foreach { listenerName =>
+ defaultListeners foreach { listenerName ⇒
try {
ReflectiveAccess.getClassFor[Actor](listenerName) match {
- case r: Right[_, Class[Actor]] => addListener(Actor.actorOf(r.b, listenerName).start())
- case l: Left[Exception,_] => throw l.a
+ case r: Right[_, Class[Actor]] ⇒ addListener(Actor.actorOf(r.b, listenerName).start())
+ case l: Left[Exception, _] ⇒ throw l.a
}
} catch {
- case e: Exception =>
+ case e: Exception ⇒
throw new ConfigurationException(
"Event Handler specified in config can't be loaded [" + listenerName +
- "] due to [" + e.toString + "]", e)
+ "] due to [" + e.toString + "]", e)
}
}
info(this, "Starting up EventHandler")
} catch {
- case e: Exception =>
+ case e: Exception ⇒
e.printStackTrace()
throw new ConfigurationException("Could not start Event Handler due to [" + e.toString + "]")
}
@@ -143,11 +144,11 @@ object EventHandler extends ListenerManagement {
notifyListeners(event)
}
- def notify[T <: Event : ClassManifest](event: => T) {
+ def notify[T <: Event: ClassManifest](event: ⇒ T) {
if (level >= levelFor(classManifest[T].erasure.asInstanceOf[Class[_ <: Event]])) notifyListeners(event)
}
- def error(cause: Throwable, instance: AnyRef, message: => String) {
+ def error(cause: Throwable, instance: AnyRef, message: ⇒ String) {
if (level >= ErrorLevel) notifyListeners(Error(cause, instance, message))
}
@@ -155,7 +156,7 @@ object EventHandler extends ListenerManagement {
if (level >= ErrorLevel) notifyListeners(Error(cause, instance, message))
}
- def error(instance: AnyRef, message: => String) {
+ def error(instance: AnyRef, message: ⇒ String) {
if (level >= ErrorLevel) notifyListeners(Error(new EventHandlerException, instance, message))
}
@@ -163,7 +164,7 @@ object EventHandler extends ListenerManagement {
if (level >= ErrorLevel) notifyListeners(Error(new EventHandlerException, instance, message))
}
- def warning(instance: AnyRef, message: => String) {
+ def warning(instance: AnyRef, message: ⇒ String) {
if (level >= WarningLevel) notifyListeners(Warning(instance, message))
}
@@ -171,7 +172,7 @@ object EventHandler extends ListenerManagement {
if (level >= WarningLevel) notifyListeners(Warning(instance, message))
}
- def info(instance: AnyRef, message: => String) {
+ def info(instance: AnyRef, message: ⇒ String) {
if (level >= InfoLevel) notifyListeners(Info(instance, message))
}
@@ -179,7 +180,7 @@ object EventHandler extends ListenerManagement {
if (level >= InfoLevel) notifyListeners(Info(instance, message))
}
- def debug(instance: AnyRef, message: => String) {
+ def debug(instance: AnyRef, message: ⇒ String) {
if (level >= DebugLevel) notifyListeners(Debug(instance, message))
}
@@ -201,43 +202,43 @@ object EventHandler extends ListenerManagement {
}
private def levelFor(eventClass: Class[_ <: Event]) = {
- if (eventClass.isInstanceOf[Error]) ErrorLevel
+ if (eventClass.isInstanceOf[Error]) ErrorLevel
else if (eventClass.isInstanceOf[Warning]) WarningLevel
- else if (eventClass.isInstanceOf[Info]) InfoLevel
- else if (eventClass.isInstanceOf[Debug]) DebugLevel
- else DebugLevel
+ else if (eventClass.isInstanceOf[Info]) InfoLevel
+ else if (eventClass.isInstanceOf[Debug]) DebugLevel
+ else DebugLevel
}
class DefaultListener extends Actor {
self.dispatcher = EventHandlerDispatcher
def receive = {
- case event @ Error(cause, instance, message) =>
+ case event@Error(cause, instance, message) ⇒
println(error.format(
formattedTimestamp,
event.thread.getName,
instance.getClass.getSimpleName,
message,
stackTraceFor(cause)))
- case event @ Warning(instance, message) =>
+ case event@Warning(instance, message) ⇒
println(warning.format(
formattedTimestamp,
event.thread.getName,
instance.getClass.getSimpleName,
message))
- case event @ Info(instance, message) =>
+ case event@Info(instance, message) ⇒
println(info.format(
formattedTimestamp,
event.thread.getName,
instance.getClass.getSimpleName,
message))
- case event @ Debug(instance, message) =>
+ case event@Debug(instance, message) ⇒
println(debug.format(
formattedTimestamp,
event.thread.getName,
instance.getClass.getSimpleName,
message))
- case event =>
+ case event ⇒
println(generic.format(formattedTimestamp, event.toString))
}
}
diff --git a/akka-actor/src/main/scala/akka/japi/JavaAPI.scala b/akka-actor/src/main/scala/akka/japi/JavaAPI.scala
index 5d7bbf0a94..f5c4ccdcaa 100644
--- a/akka-actor/src/main/scala/akka/japi/JavaAPI.scala
+++ b/akka-actor/src/main/scala/akka/japi/JavaAPI.scala
@@ -3,7 +3,7 @@ package akka.japi
/**
* A Function interface. Used to create first-class-functions is Java (sort of).
*/
-trait Function[T,R] {
+trait Function[T, R] {
def apply(param: T): R
}
@@ -14,16 +14,18 @@ trait Function2[T1, T2, R] {
def apply(arg1: T1, arg2: T2): R
}
-/** A Procedure is like a Function, but it doesn't produce a return value
+/**
+ * A Procedure is like a Function, but it doesn't produce a return value
*/
trait Procedure[T] {
def apply(param: T): Unit
}
-/** A Procedure is like a Function, but it doesn't produce a return value
+/**
+ * A Procedure is like a Function, but it doesn't produce a return value
*/
-trait Procedure2[T1,T2] {
- def apply(param: T1, param2:T2): Unit
+trait Procedure2[T1, T2] {
+ def apply(param: T1, param2: T2): Unit
}
/**
@@ -41,13 +43,13 @@ trait Effect {
}
/**
- + * A constructor/factory, takes no parameters but creates a new value of type T every call
- + */
+ * + * A constructor/factory, takes no parameters but creates a new value of type T every call
+ * +
+ */
trait Creator[T] {
def create: T
}
-
/**
* This class represents optional values. Instances of Option
* are either instances of case class Some or it is case
diff --git a/akka-actor/src/main/scala/akka/remoteinterface/RemoteEventHandler.scala b/akka-actor/src/main/scala/akka/remoteinterface/RemoteEventHandler.scala
index 297ebdf7b7..4b1d7731fb 100644
--- a/akka-actor/src/main/scala/akka/remoteinterface/RemoteEventHandler.scala
+++ b/akka-actor/src/main/scala/akka/remoteinterface/RemoteEventHandler.scala
@@ -20,24 +20,23 @@ class RemoteEventHandler extends Actor {
def receive = {
// client
- case RemoteClientError(cause, client, address) => EventHandler.error(cause, client, "RemoteClientError - Address[%s]" format address.toString)
- case RemoteClientWriteFailed(request, cause, client, address) => EventHandler.error(cause, client, "RemoteClientWriteFailed - Request[%s] Address[%s]".format(address.toString))
- case RemoteClientDisconnected(client, address) => EventHandler.info(client, "RemoteClientDisconnected - Address[%s]" format address.toString)
- case RemoteClientConnected(client, address) => EventHandler.info(client, "RemoteClientConnected - Address[%s]" format address.toString)
- case RemoteClientStarted(client, address) => EventHandler.info(client, "RemoteClientStarted - Address[%s]" format address.toString)
- case RemoteClientShutdown(client, address) => EventHandler.info(client, "RemoteClientShutdown - Address[%s]" format address.toString)
+ case RemoteClientError(cause, client, address) ⇒ EventHandler.error(cause, client, "RemoteClientError - Address[%s]" format address.toString)
+ case RemoteClientWriteFailed(request, cause, client, address) ⇒ EventHandler.error(cause, client, "RemoteClientWriteFailed - Request[%s] Address[%s]".format(address.toString))
+ case RemoteClientDisconnected(client, address) ⇒ EventHandler.info(client, "RemoteClientDisconnected - Address[%s]" format address.toString)
+ case RemoteClientConnected(client, address) ⇒ EventHandler.info(client, "RemoteClientConnected - Address[%s]" format address.toString)
+ case RemoteClientStarted(client, address) ⇒ EventHandler.info(client, "RemoteClientStarted - Address[%s]" format address.toString)
+ case RemoteClientShutdown(client, address) ⇒ EventHandler.info(client, "RemoteClientShutdown - Address[%s]" format address.toString)
// server
- case RemoteServerError(cause, server) => EventHandler.error(cause, server, "RemoteServerError")
- case RemoteServerWriteFailed(request, cause, server, clientAddress) => EventHandler.error(cause, server, "RemoteServerWriteFailed - Request[%s] Address[%s]" format (request, clientAddress.toString))
- case RemoteServerStarted(server) => EventHandler.info(server, "RemoteServerStarted")
- case RemoteServerShutdown(server) => EventHandler.info(server, "RemoteServerShutdown")
- case RemoteServerClientConnected(server, clientAddress) => EventHandler.info(server, "RemoteServerClientConnected - Address[%s]" format clientAddress.toString)
- case RemoteServerClientDisconnected(server, clientAddress) => EventHandler.info(server, "RemoteServerClientDisconnected - Address[%s]" format clientAddress.toString)
- case RemoteServerClientClosed(server, clientAddress) => EventHandler.info(server, "RemoteServerClientClosed - Address[%s]" format clientAddress.toString)
+ case RemoteServerError(cause, server) ⇒ EventHandler.error(cause, server, "RemoteServerError")
+ case RemoteServerWriteFailed(request, cause, server, clientAddress) ⇒ EventHandler.error(cause, server, "RemoteServerWriteFailed - Request[%s] Address[%s]" format (request, clientAddress.toString))
+ case RemoteServerStarted(server) ⇒ EventHandler.info(server, "RemoteServerStarted")
+ case RemoteServerShutdown(server) ⇒ EventHandler.info(server, "RemoteServerShutdown")
+ case RemoteServerClientConnected(server, clientAddress) ⇒ EventHandler.info(server, "RemoteServerClientConnected - Address[%s]" format clientAddress.toString)
+ case RemoteServerClientDisconnected(server, clientAddress) ⇒ EventHandler.info(server, "RemoteServerClientDisconnected - Address[%s]" format clientAddress.toString)
+ case RemoteServerClientClosed(server, clientAddress) ⇒ EventHandler.info(server, "RemoteServerClientClosed - Address[%s]" format clientAddress.toString)
- case _ => //ignore other
+ case _ ⇒ //ignore other
}
}
-
diff --git a/akka-actor/src/main/scala/akka/remoteinterface/RemoteInterface.scala b/akka-actor/src/main/scala/akka/remoteinterface/RemoteInterface.scala
index a1909ddd82..55b7bcb472 100644
--- a/akka-actor/src/main/scala/akka/remoteinterface/RemoteInterface.scala
+++ b/akka-actor/src/main/scala/akka/remoteinterface/RemoteInterface.scala
@@ -15,46 +15,46 @@ import scala.reflect.BeanProperty
import java.net.InetSocketAddress
import java.util.concurrent.ConcurrentHashMap
-import java.io.{PrintWriter, PrintStream}
+import java.io.{ PrintWriter, PrintStream }
import java.lang.reflect.InvocationTargetException
trait RemoteModule {
val UUID_PREFIX = "uuid:".intern
def optimizeLocalScoped_?(): Boolean //Apply optimizations for remote operations in local scope
- protected[akka] def notifyListeners(message: => Any): Unit
+ protected[akka] def notifyListeners(message: ⇒ Any): Unit
private[akka] def actors: ConcurrentHashMap[String, ActorRef]
private[akka] def actorsByUuid: ConcurrentHashMap[String, ActorRef]
- private[akka] def actorsFactories: ConcurrentHashMap[String, () => ActorRef]
+ private[akka] def actorsFactories: ConcurrentHashMap[String, () ⇒ ActorRef]
private[akka] def typedActors: ConcurrentHashMap[String, AnyRef]
private[akka] def typedActorsByUuid: ConcurrentHashMap[String, AnyRef]
- private[akka] def typedActorsFactories: ConcurrentHashMap[String, () => AnyRef]
+ private[akka] def typedActorsFactories: ConcurrentHashMap[String, () ⇒ AnyRef]
/** Lookup methods **/
- private[akka] def findActorByAddress(address: String) : ActorRef = actors.get(address)
+ private[akka] def findActorByAddress(address: String): ActorRef = actors.get(address)
- private[akka] def findActorByUuid(uuid: String) : ActorRef = actorsByUuid.get(uuid)
+ private[akka] def findActorByUuid(uuid: String): ActorRef = actorsByUuid.get(uuid)
- private[akka] def findActorFactory(address: String) : () => ActorRef = actorsFactories.get(address)
+ private[akka] def findActorFactory(address: String): () ⇒ ActorRef = actorsFactories.get(address)
- private[akka] def findTypedActorByAddress(address: String) : AnyRef = typedActors.get(address)
+ private[akka] def findTypedActorByAddress(address: String): AnyRef = typedActors.get(address)
- private[akka] def findTypedActorFactory(address: String) : () => AnyRef = typedActorsFactories.get(address)
+ private[akka] def findTypedActorFactory(address: String): () ⇒ AnyRef = typedActorsFactories.get(address)
- private[akka] def findTypedActorByUuid(uuid: String) : AnyRef = typedActorsByUuid.get(uuid)
+ private[akka] def findTypedActorByUuid(uuid: String): AnyRef = typedActorsByUuid.get(uuid)
- private[akka] def findActorByAddressOrUuid(address: String, uuid: String) : ActorRef = {
+ private[akka] def findActorByAddressOrUuid(address: String, uuid: String): ActorRef = {
var actorRefOrNull = if (address.startsWith(UUID_PREFIX)) findActorByUuid(address.substring(UUID_PREFIX.length))
- else findActorByAddress(address)
+ else findActorByAddress(address)
if (actorRefOrNull eq null) actorRefOrNull = findActorByUuid(uuid)
actorRefOrNull
}
- private[akka] def findTypedActorByAddressOrUuid(address: String, uuid: String) : AnyRef = {
+ private[akka] def findTypedActorByAddressOrUuid(address: String, uuid: String): AnyRef = {
var actorRefOrNull = if (address.startsWith(UUID_PREFIX)) findTypedActorByUuid(address.substring(UUID_PREFIX.length))
- else findTypedActorByAddress(address)
+ else findTypedActorByAddress(address)
if (actorRefOrNull eq null) actorRefOrNull = findTypedActorByUuid(uuid)
actorRefOrNull
}
@@ -130,8 +130,8 @@ class RemoteServerException private[akka] (message: String) extends AkkaExceptio
*/
case class CannotInstantiateRemoteExceptionDueToRemoteProtocolParsingErrorException private[akka] (cause: Throwable, originalClassName: String, originalMessage: String)
extends AkkaException("\nParsingError[%s]\nOriginalException[%s]\nOriginalMessage[%s]"
- .format(cause.toString, originalClassName, originalMessage)) {
- override def printStackTrace = cause.printStackTrace
+ .format(cause.toString, originalClassName, originalMessage)) {
+ override def printStackTrace = cause.printStackTrace
override def printStackTrace(printStream: PrintStream) = cause.printStackTrace(printStream)
override def printStackTrace(printWriter: PrintWriter) = cause.printStackTrace(printWriter)
}
@@ -156,14 +156,14 @@ abstract class RemoteSupport extends ListenerManagement with RemoteServerModule
}
protected override def manageLifeCycleOfListeners = false
- protected[akka] override def notifyListeners(message: => Any): Unit = super.notifyListeners(message)
+ protected[akka] override def notifyListeners(message: ⇒ Any): Unit = super.notifyListeners(message)
- private[akka] val actors = new ConcurrentHashMap[String, ActorRef]
- private[akka] val actorsByUuid = new ConcurrentHashMap[String, ActorRef]
- private[akka] val actorsFactories = new ConcurrentHashMap[String, () => ActorRef]
- private[akka] val typedActors = new ConcurrentHashMap[String, AnyRef]
- private[akka] val typedActorsByUuid = new ConcurrentHashMap[String, AnyRef]
- private[akka] val typedActorsFactories = new ConcurrentHashMap[String, () => AnyRef]
+ private[akka] val actors = new ConcurrentHashMap[String, ActorRef]
+ private[akka] val actorsByUuid = new ConcurrentHashMap[String, ActorRef]
+ private[akka] val actorsFactories = new ConcurrentHashMap[String, () ⇒ ActorRef]
+ private[akka] val typedActors = new ConcurrentHashMap[String, AnyRef]
+ private[akka] val typedActorsByUuid = new ConcurrentHashMap[String, AnyRef]
+ private[akka] val typedActorsFactories = new ConcurrentHashMap[String, () ⇒ AnyRef]
def clear {
actors.clear
@@ -201,28 +201,28 @@ trait RemoteServerModule extends RemoteModule {
*/
def start(): RemoteServerModule =
start(ReflectiveAccess.RemoteModule.configDefaultAddress.getAddress.getHostAddress,
- ReflectiveAccess.RemoteModule.configDefaultAddress.getPort,
- None)
+ ReflectiveAccess.RemoteModule.configDefaultAddress.getPort,
+ None)
/**
* Starts the server up
*/
def start(loader: ClassLoader): RemoteServerModule =
start(ReflectiveAccess.RemoteModule.configDefaultAddress.getAddress.getHostAddress,
- ReflectiveAccess.RemoteModule.configDefaultAddress.getPort,
- Option(loader))
+ ReflectiveAccess.RemoteModule.configDefaultAddress.getPort,
+ Option(loader))
/**
* Starts the server up
*/
def start(host: String, port: Int): RemoteServerModule =
- start(host,port,None)
+ start(host, port, None)
/**
* Starts the server up
*/
def start(host: String, port: Int, loader: ClassLoader): RemoteServerModule =
- start(host,port,Option(loader))
+ start(host, port, Option(loader))
/**
* Starts the server up
@@ -237,7 +237,7 @@ trait RemoteServerModule extends RemoteModule {
/**
* Register typed actor by interface name.
*/
- def registerTypedActor(intfClass: Class[_], typedActor: AnyRef) : Unit = registerTypedActor(intfClass.getName, typedActor)
+ def registerTypedActor(intfClass: Class[_], typedActor: AnyRef): Unit = registerTypedActor(intfClass.getName, typedActor)
/**
* Register remote typed actor by a specific id.
@@ -249,20 +249,20 @@ trait RemoteServerModule extends RemoteModule {
/**
* Register typed actor by interface name.
*/
- def registerTypedPerSessionActor(intfClass: Class[_], factory: => AnyRef) : Unit = registerTypedActor(intfClass.getName, factory)
+ def registerTypedPerSessionActor(intfClass: Class[_], factory: ⇒ AnyRef): Unit = registerTypedActor(intfClass.getName, factory)
/**
* Register typed actor by interface name.
* Java API
*/
- def registerTypedPerSessionActor(intfClass: Class[_], factory: Creator[AnyRef]) : Unit = registerTypedActor(intfClass.getName, factory)
+ def registerTypedPerSessionActor(intfClass: Class[_], factory: Creator[AnyRef]): Unit = registerTypedActor(intfClass.getName, factory)
/**
* Register remote typed actor by a specific id.
* @param address actor address
* @param typedActor typed actor to register
*/
- def registerTypedPerSessionActor(address: String, factory: => AnyRef): Unit
+ def registerTypedPerSessionActor(address: String, factory: ⇒ AnyRef): Unit
/**
* Register remote typed actor by a specific id.
@@ -295,7 +295,7 @@ trait RemoteServerModule extends RemoteModule {
*
* NOTE: If you use this method to register your remote actor then you must unregister the actor by this ID yourself.
*/
- def registerPerSession(address: String, factory: => ActorRef): Unit
+ def registerPerSession(address: String, factory: ⇒ ActorRef): Unit
/**
* Register Remote Session Actor by a specific 'id' passed as argument.
@@ -332,14 +332,14 @@ trait RemoteServerModule extends RemoteModule {
def unregisterTypedActor(address: String): Unit
/**
- * Unregister Remote Typed Actor by specific 'id'.
- *
- * NOTE: You need to call this method if you have registered an actor by a custom ID.
- */
- def unregisterTypedPerSessionActor(address: String): Unit
+ * Unregister Remote Typed Actor by specific 'id'.
+ *
+ * NOTE: You need to call this method if you have registered an actor by a custom ID.
+ */
+ def unregisterTypedPerSessionActor(address: String): Unit
}
-trait RemoteClientModule extends RemoteModule { self: RemoteModule =>
+trait RemoteClientModule extends RemoteModule { self: RemoteModule ⇒
def actorFor(address: String, hostname: String, port: Int): ActorRef =
actorFor(address, Actor.TIMEOUT, hostname, port, None)
diff --git a/akka-actor/src/main/scala/akka/routing/ConsistentHash.scala b/akka-actor/src/main/scala/akka/routing/ConsistentHash.scala
index 2b89b127ee..9e9a5e41ac 100644
--- a/akka-actor/src/main/scala/akka/routing/ConsistentHash.scala
+++ b/akka-actor/src/main/scala/akka/routing/ConsistentHash.scala
@@ -4,8 +4,8 @@
package akka.routing
-import scala.collection.immutable.{TreeSet, Seq}
-import scala.collection.mutable.{Buffer, Map}
+import scala.collection.immutable.{ TreeSet, Seq }
+import scala.collection.mutable.{ Buffer, Map }
// =============================================================================================
// Adapted from HashRing.scala in Debasish Ghosh's Redis Client, licensed under Apache 2 license
@@ -19,15 +19,15 @@ import scala.collection.mutable.{Buffer, Map}
* @author Jonas Bonér
*/
class ConsistentHash[T](nodes: Seq[T], replicas: Int) {
- private val cluster = Buffer[T]()
+ private val cluster = Buffer[T]()
private var sortedKeys = TreeSet[Long]()
- private var ring = Map[Long, T]()
+ private var ring = Map[Long, T]()
nodes.foreach(this += _)
def +=(node: T) {
cluster += node
- (1 to replicas) foreach { replica =>
+ (1 to replicas) foreach { replica ⇒
val key = hashFor((node + ":" + replica).getBytes("UTF-8"))
ring += (key -> node)
sortedKeys = sortedKeys + key
@@ -36,7 +36,7 @@ class ConsistentHash[T](nodes: Seq[T], replicas: Int) {
def -=(node: T) {
cluster -= node
- (1 to replicas) foreach { replica =>
+ (1 to replicas) foreach { replica ⇒
val key = hashFor((node + ":" + replica).getBytes("UTF-8"))
ring -= key
sortedKeys = sortedKeys - key
@@ -47,9 +47,9 @@ class ConsistentHash[T](nodes: Seq[T], replicas: Int) {
val hash = hashFor(key)
if (sortedKeys contains hash) ring(hash)
else {
- if (hash < sortedKeys.firstKey) ring(sortedKeys.firstKey)
- else if (hash > sortedKeys.lastKey) ring(sortedKeys.lastKey)
- else ring(sortedKeys.rangeImpl(None, Some(hash)).lastKey)
+ if (hash < sortedKeys.firstKey) ring(sortedKeys.firstKey)
+ else if (hash > sortedKeys.lastKey) ring(sortedKeys.lastKey)
+ else ring(sortedKeys.rangeImpl(None, Some(hash)).lastKey)
}
}
@@ -68,7 +68,8 @@ class ConsistentHash[T](nodes: Seq[T], replicas: Int) {
** |/ **
\* */
-/** An implementation of Austin Appleby's MurmurHash 3.0 algorithm
+/**
+ * An implementation of Austin Appleby's MurmurHash 3.0 algorithm
* (32 bit version); reference: http://code.google.com/p/smhasher
*
* This is the hash used by collections and case classes (including
@@ -79,14 +80,15 @@ class ConsistentHash[T](nodes: Seq[T], replicas: Int) {
* @since 2.9
*/
-import java.lang.Integer.{ rotateLeft => rotl }
+import java.lang.Integer.{ rotateLeft ⇒ rotl }
-/** A class designed to generate well-distributed non-cryptographic
+/**
+ * A class designed to generate well-distributed non-cryptographic
* hashes. It is designed to be passed to a collection's foreach method,
* or can take individual hash values with append. Its own hash code is
* set equal to the hash code of whatever it is hashing.
*/
-class MurmurHash[@specialized(Int,Long,Float,Double) T](seed: Int) extends (T => Unit) {
+class MurmurHash[@specialized(Int, Long, Float, Double) T](seed: Int) extends (T ⇒ Unit) {
import MurmurHash._
private var h = startHash(seed)
@@ -105,7 +107,7 @@ class MurmurHash[@specialized(Int,Long,Float,Double) T](seed: Int) extends (T =>
/** Incorporate the hash value of one item. */
def apply(t: T) {
- h = extendHash(h,t.##,c,k)
+ h = extendHash(h, t.##, c, k)
c = nextMagicA(c)
k = nextMagicB(k)
hashed = false
@@ -113,7 +115,7 @@ class MurmurHash[@specialized(Int,Long,Float,Double) T](seed: Int) extends (T =>
/** Incorporate a known hash value. */
def append(i: Int) {
- h = extendHash(h,i,c,k)
+ h = extendHash(h, i, c, k)
c = nextMagicA(c)
k = nextMagicB(k)
hashed = false
@@ -130,7 +132,8 @@ class MurmurHash[@specialized(Int,Long,Float,Double) T](seed: Int) extends (T =>
override def hashCode = hash
}
-/** An object designed to generate well-distributed non-cryptographic
+/**
+ * An object designed to generate well-distributed non-cryptographic
* hashes. It is designed to hash a collection of integers; along with
* the integers to hash, it generates two magic streams of integers to
* increase the distribution of repetitive input sequences. Thus,
@@ -172,7 +175,8 @@ object MurmurHash {
/** The initial magic integer in the second stream. */
def startMagicB = hiddenMagicB
- /** Incorporates a new value into an existing hash.
+ /**
+ * Incorporates a new value into an existing hash.
*
* @param hash the prior hash value
* @param value the new value to incorporate
@@ -181,18 +185,18 @@ object MurmurHash {
* @return the updated hash value
*/
def extendHash(hash: Int, value: Int, magicA: Int, magicB: Int) = {
- (hash ^ rotl(value*magicA,11)*magicB)*3 + visibleMixer
+ (hash ^ rotl(value * magicA, 11) * magicB) * 3 + visibleMixer
}
/** Given a magic integer from the first stream, compute the next */
- def nextMagicA(magicA: Int) = magicA*5 + hiddenMixerA
+ def nextMagicA(magicA: Int) = magicA * 5 + hiddenMixerA
/** Given a magic integer from the second stream, compute the next */
- def nextMagicB(magicB: Int) = magicB*5 + hiddenMixerB
+ def nextMagicB(magicB: Int) = magicB * 5 + hiddenMixerB
/** Once all hashes have been incorporated, this performs a final mixing */
def finalizeHash(hash: Int) = {
- var i = (hash ^ (hash>>>16))
+ var i = (hash ^ (hash >>> 16))
i *= finalMixer1
i ^= (i >>> 13)
i *= finalMixer2
@@ -221,25 +225,26 @@ object MurmurHash {
var c = hiddenMagicA
var k = hiddenMagicB
var j = 0
- while (j+1 < s.length) {
- val i = (s.charAt(j)<<16) + s.charAt(j+1);
- h = extendHash(h,i,c,k)
+ while (j + 1 < s.length) {
+ val i = (s.charAt(j) << 16) + s.charAt(j + 1);
+ h = extendHash(h, i, c, k)
c = nextMagicA(c)
k = nextMagicB(k)
j += 2
}
- if (j < s.length) h = extendHash(h,s.charAt(j),c,k)
+ if (j < s.length) h = extendHash(h, s.charAt(j), c, k)
finalizeHash(h)
}
- /** Compute a hash that is symmetric in its arguments--that is,
+ /**
+ * Compute a hash that is symmetric in its arguments--that is,
* where the order of appearance of elements does not matter.
* This is useful for hashing sets, for example.
*/
def symmetricHash[T](xs: TraversableOnce[T], seed: Int) = {
- var a,b,n = 0
+ var a, b, n = 0
var c = 1
- xs.foreach(i => {
+ xs.foreach(i ⇒ {
val h = i.##
a += h
b ^= h
diff --git a/akka-actor/src/main/scala/akka/routing/Listeners.scala b/akka-actor/src/main/scala/akka/routing/Listeners.scala
index 3b774d9323..448511d8dd 100644
--- a/akka-actor/src/main/scala/akka/routing/Listeners.scala
+++ b/akka-actor/src/main/scala/akka/routing/Listeners.scala
@@ -4,14 +4,14 @@
package akka.routing
-import akka.actor.{Actor, ActorRef}
+import akka.actor.{ Actor, ActorRef }
import java.util.concurrent.ConcurrentSkipListSet
import scala.collection.JavaConversions._
sealed trait ListenerMessage
case class Listen(listener: ActorRef) extends ListenerMessage
case class Deafen(listener: ActorRef) extends ListenerMessage
-case class WithListeners(f: (ActorRef) => Unit) extends ListenerMessage
+case class WithListeners(f: (ActorRef) ⇒ Unit) extends ListenerMessage
/**
* Listeners is a generic trait to implement listening capability on an Actor.
@@ -24,13 +24,13 @@ case class WithListeners(f: (ActorRef) => Unit) extends ListenerMessage
*
* Send WithListeners(fun) to traverse the current listeners.
*/
-trait Listeners { self: Actor =>
+trait Listeners { self: Actor ⇒
private val listeners = new ConcurrentSkipListSet[ActorRef]
protected def listenerManagement: Receive = {
- case Listen(l) => listeners add l
- case Deafen(l) => listeners remove l
- case WithListeners(f) => listeners foreach f
+ case Listen(l) ⇒ listeners add l
+ case Deafen(l) ⇒ listeners remove l
+ case WithListeners(f) ⇒ listeners foreach f
}
protected def gossip(msg: Any) = listeners foreach (_ ! msg)
diff --git a/akka-actor/src/main/scala/akka/routing/Pool.scala b/akka-actor/src/main/scala/akka/routing/Pool.scala
index c95a80b0fc..c036616521 100644
--- a/akka-actor/src/main/scala/akka/routing/Pool.scala
+++ b/akka-actor/src/main/scala/akka/routing/Pool.scala
@@ -4,7 +4,7 @@
package akka.routing
-import akka.actor.{Actor, ActorRef, PoisonPill}
+import akka.actor.{ Actor, ActorRef, PoisonPill }
/**
* Actor pooling
@@ -13,21 +13,21 @@ import akka.actor.{Actor, ActorRef, PoisonPill}
* There are a handful of basic concepts that need to be understood when working with and defining your pool.
*
* Selectors - A selector is a trait that determines how and how many pooled actors will receive an incoming message.
- * Capacitors - A capacitor is a trait that influences the size of pool. There are effectively two types.
+ * Capacitors - A capacitor is a trait that influences the size of pool. There are effectively two types.
* The first determines the size itself - either fixed or bounded.
* The second determines how to adjust of the pool according to some internal pressure characteristic.
* Filters - A filter can be used to refine the raw pressure value returned from a capacitor.
- *
- * It should be pointed out that all actors in the pool are treated as essentially equivalent. This is not to say
+ *
+ * It should be pointed out that all actors in the pool are treated as essentially equivalent. This is not to say
* that one couldn't instance different classes within the pool, only that the pool, when selecting and routing,
* will not take any type information into consideration.
- *
+ *
* @author Garrick Evans
*/
object ActorPool {
case object Stat
- case class Stats(size:Int)
+ case class Stats(size: Int)
}
/**
@@ -44,7 +44,7 @@ trait ActorPool {
* - checks the current capacity and adjusts accordingly if needed
* - routes the incoming message to a selection set of delegate actors
*/
-trait DefaultActorPool extends ActorPool { this: Actor =>
+trait DefaultActorPool extends ActorPool { this: Actor ⇒
import ActorPool._
import akka.actor.MaximumNumberOfRestartsWithinTimeRangeReached
@@ -52,23 +52,23 @@ trait DefaultActorPool extends ActorPool { this: Actor =>
private var _lastCapacityChange = 0
private var _lastSelectorCount = 0
- override def postStop() = _delegates foreach {
- delegate => try {
+ override def postStop() = _delegates foreach { delegate ⇒
+ try {
delegate ! PoisonPill
- } catch { case e: Exception => } //Ignore any exceptions here
+ } catch { case e: Exception ⇒ } //Ignore any exceptions here
}
protected def _route(): Receive = {
// for testing...
- case Stat =>
+ case Stat ⇒
self reply_? Stats(_delegates length)
- case max: MaximumNumberOfRestartsWithinTimeRangeReached =>
+ case max: MaximumNumberOfRestartsWithinTimeRangeReached ⇒
_delegates = _delegates filterNot { _.uuid == max.victim.uuid }
- case msg =>
+ case msg ⇒
resizeIfAppropriate()
select(_delegates) match {
- case (selectedDelegates, count) =>
+ case (selectedDelegates, count) ⇒
_lastSelectorCount = count
selectedDelegates foreach { _ forward msg } //Should we really send the same message to several actors?
}
@@ -77,20 +77,21 @@ trait DefaultActorPool extends ActorPool { this: Actor =>
private def resizeIfAppropriate() {
val requestedCapacity = capacity(_delegates)
val newDelegates = requestedCapacity match {
- case qty if qty > 0 =>
- _delegates ++ { for (i <- 0 until requestedCapacity) yield {
- val delegate = instance()
- self startLink delegate
- delegate
+ case qty if qty > 0 ⇒
+ _delegates ++ {
+ for (i ← 0 until requestedCapacity) yield {
+ val delegate = instance()
+ self startLink delegate
+ delegate
+ }
}
- }
- case qty if qty < 0 =>
+ case qty if qty < 0 ⇒
_delegates.splitAt(_delegates.length + requestedCapacity) match {
- case (keep, abandon) =>
+ case (keep, abandon) ⇒
abandon foreach { _ ! PoisonPill }
keep
}
- case _ => _delegates //No change
+ case _ ⇒ _delegates //No change
}
_lastCapacityChange = requestedCapacity
@@ -98,7 +99,6 @@ trait DefaultActorPool extends ActorPool { this: Actor =>
}
}
-
/**
* Selectors
* These traits define how, when a message needs to be routed, delegate(s) are chosen from the pool
@@ -133,13 +133,13 @@ trait RoundRobinSelector {
def selectionCount: Int
def partialFill: Boolean
- def select(delegates:Seq[ActorRef]):Tuple2[Iterator[ActorRef], Int] = {
+ def select(delegates: Seq[ActorRef]): Tuple2[Iterator[ActorRef], Int] = {
val length = delegates.length
val take = if (partialFill) math.min(selectionCount, length)
- else selectionCount
+ else selectionCount
val set =
- for (i <- 0 until take) yield {
+ for (i ← 0 until take) yield {
_last = (_last + 1) % length
delegates(_last)
}
@@ -148,7 +148,6 @@ trait RoundRobinSelector {
}
}
-
/**
* Capacitors
* These traits define how to alter the size of the pool
@@ -158,7 +157,7 @@ trait RoundRobinSelector {
* Ensures a fixed number of delegates in the pool
*/
trait FixedSizeCapacitor {
- def limit:Int
+ def limit: Int
def capacity(delegates: Seq[ActorRef]): Int = (limit - delegates.size) max 0
}
@@ -170,8 +169,8 @@ trait BoundedCapacitor {
def upperBound: Int
def capacity(delegates: Seq[ActorRef]): Int = {
- val current = delegates length
- val delta = _eval(delegates)
+ val current = delegates length
+ val delta = _eval(delegates)
val proposed = current + delta
if (proposed < lowerBound) delta + (lowerBound - proposed)
@@ -186,7 +185,7 @@ trait BoundedCapacitor {
* Returns the number of delegates required to manage the current message backlogs
*/
trait MailboxPressureCapacitor {
- def pressureThreshold:Int
+ def pressureThreshold: Int
def pressure(delegates: Seq[ActorRef]): Int =
delegates count { _.mailboxSize > pressureThreshold }
}
@@ -199,7 +198,6 @@ trait ActiveFuturesPressureCapacitor {
delegates count { _.senderFuture.isDefined }
}
-
/**
*/
trait CapacityStrategy {
@@ -230,7 +228,7 @@ trait Filter {
// are updated consistently. ramping up is always + and backing off
// is always - and each should return 0 otherwise...
def filter(pressure: Int, capacity: Int): Int =
- rampup (pressure, capacity) + backoff (pressure, capacity)
+ rampup(pressure, capacity) + backoff(pressure, capacity)
}
trait BasicFilter extends Filter with BasicRampup with BasicBackoff
@@ -247,7 +245,7 @@ trait BasicNoBackoffFilter extends BasicRampup {
*/
trait BasicRampup {
def rampupRate: Double
-
+
def rampup(pressure: Int, capacity: Int): Int =
if (pressure < capacity) 0 else math.ceil(rampupRate * capacity) toInt
}
@@ -280,8 +278,8 @@ trait RunningMeanBackoff {
_capacity += capacity
if (capacity > 0 && pressure / capacity < backoffThreshold
- && _capacity > 0 && _pressure / _capacity < backoffThreshold) //Why does the entire clause need to be true?
- math.floor(-1.0 * backoffRate * (capacity-pressure)).toInt
+ && _capacity > 0 && _pressure / _capacity < backoffThreshold) //Why does the entire clause need to be true?
+ math.floor(-1.0 * backoffRate * (capacity - pressure)).toInt
else 0
}
diff --git a/akka-actor/src/main/scala/akka/routing/Routing.scala b/akka-actor/src/main/scala/akka/routing/Routing.scala
index ef8f63e545..b87eef67bc 100644
--- a/akka-actor/src/main/scala/akka/routing/Routing.scala
+++ b/akka-actor/src/main/scala/akka/routing/Routing.scala
@@ -4,7 +4,7 @@
package akka.routing
-import akka.actor.{UntypedActor, Actor, ActorRef}
+import akka.actor.{ UntypedActor, Actor, ActorRef }
import akka.actor.Actor._
import akka.actor.ActorRef
@@ -24,7 +24,7 @@ object Routing {
* and then filtered.apply.
*/
def filter[A, B](filter: PF[A, Unit], filtered: PF[A, B]): PF[A, B] = {
- case a: A if filtered.isDefinedAt(a) && filter.isDefinedAt(a) =>
+ case a: A if filtered.isDefinedAt(a) && filter.isDefinedAt(a) ⇒
filter(a)
filtered(a)
}
@@ -32,13 +32,13 @@ object Routing {
/**
* Interceptor is a filter(x,y) where x.isDefinedAt is considered to be always true.
*/
- def intercept[A, B](interceptor: (A) => Unit, interceptee: PF[A, B]): PF[A, B] =
- filter({case a if a.isInstanceOf[A] => interceptor(a)}, interceptee)
+ def intercept[A, B](interceptor: (A) ⇒ Unit, interceptee: PF[A, B]): PF[A, B] =
+ filter({ case a if a.isInstanceOf[A] ⇒ interceptor(a) }, interceptee)
/**
* Creates a LoadBalancer from the thunk-supplied InfiniteIterator.
*/
- def loadBalancerActor(actors: => InfiniteIterator[ActorRef]): ActorRef =
+ def loadBalancerActor(actors: ⇒ InfiniteIterator[ActorRef]): ActorRef =
actorOf(new Actor with LoadBalancer {
val seq = actors
}).start()
@@ -46,7 +46,7 @@ object Routing {
/**
* Creates a Dispatcher given a routing and a message-transforming function.
*/
- def dispatcherActor(routing: PF[Any, ActorRef], msgTransformer: (Any) => Any): ActorRef =
+ def dispatcherActor(routing: PF[Any, ActorRef], msgTransformer: (Any) ⇒ Any): ActorRef =
actorOf(new Actor with Dispatcher {
override def transform(msg: Any) = msgTransformer(msg)
def routes = routing
@@ -63,8 +63,8 @@ object Routing {
* Creates an actor that pipes all incoming messages to
* both another actor and through the supplied function
*/
- def loggerActor(actorToLog: ActorRef, logger: (Any) => Unit): ActorRef =
- dispatcherActor({case _ => actorToLog}, logger)
+ def loggerActor(actorToLog: ActorRef, logger: (Any) ⇒ Unit): ActorRef =
+ dispatcherActor({ case _ ⇒ actorToLog }, logger)
}
/**
@@ -80,7 +80,8 @@ trait InfiniteIterator[T] extends Iterator[T] {
case class CyclicIterator[T](val items: Seq[T]) extends InfiniteIterator[T] {
def this(items: java.util.List[T]) = this(items.toList)
- @volatile private[this] var current: Seq[T] = items
+ @volatile
+ private[this] var current: Seq[T] = items
def hasNext = items != Nil
@@ -90,26 +91,26 @@ case class CyclicIterator[T](val items: Seq[T]) extends InfiniteIterator[T] {
nc.head
}
- override def exists(f: T => Boolean): Boolean = items.exists(f)
+ override def exists(f: T ⇒ Boolean): Boolean = items.exists(f)
}
/**
* This InfiniteIterator always returns the Actor that has the currently smallest mailbox
* useful for work-stealing.
*/
-case class SmallestMailboxFirstIterator(val items : Seq[ActorRef]) extends InfiniteIterator[ActorRef] {
+case class SmallestMailboxFirstIterator(val items: Seq[ActorRef]) extends InfiniteIterator[ActorRef] {
def this(items: java.util.List[ActorRef]) = this(items.toList)
def hasNext = items != Nil
- def next = items.reduceLeft((a1, a2) => if (a1.mailboxSize < a2.mailboxSize) a1 else a2)
+ def next = items.reduceLeft((a1, a2) ⇒ if (a1.mailboxSize < a2.mailboxSize) a1 else a2)
- override def exists(f: ActorRef => Boolean): Boolean = items.exists(f)
+ override def exists(f: ActorRef ⇒ Boolean): Boolean = items.exists(f)
}
/**
* A Dispatcher is a trait whose purpose is to route incoming messages to actors.
*/
-trait Dispatcher { this: Actor =>
+trait Dispatcher { this: Actor ⇒
protected def transform(msg: Any): Any = msg
@@ -118,9 +119,9 @@ trait Dispatcher { this: Actor =>
protected def broadcast(message: Any) {}
protected def dispatch: Receive = {
- case Routing.Broadcast(message) =>
+ case Routing.Broadcast(message) ⇒
broadcast(message)
- case a if routes.isDefinedAt(a) =>
+ case a if routes.isDefinedAt(a) ⇒
if (isSenderDefined) routes(a).forward(transform(a))(someSelf)
else routes(a).!(transform(a))(None)
}
@@ -158,16 +159,16 @@ abstract class UntypedDispatcher extends UntypedActor {
* A LoadBalancer is a specialized kind of Dispatcher, that is supplied an InfiniteIterator of targets
* to dispatch incoming messages to.
*/
-trait LoadBalancer extends Dispatcher { self: Actor =>
+trait LoadBalancer extends Dispatcher { self: Actor ⇒
protected def seq: InfiniteIterator[ActorRef]
protected def routes = {
- case x if seq.hasNext => seq.next
+ case x if seq.hasNext ⇒ seq.next
}
override def broadcast(message: Any) = seq.items.foreach(_ ! message)
- override def isDefinedAt(msg: Any) = seq.exists( _.isDefinedAt(msg) )
+ override def isDefinedAt(msg: Any) = seq.exists(_.isDefinedAt(msg))
}
/**
@@ -183,6 +184,6 @@ abstract class UntypedLoadBalancer extends UntypedDispatcher {
override def broadcast(message: Any) = seq.items.foreach(_ ! message)
- override def isDefinedAt(msg: Any) = seq.exists( _.isDefinedAt(msg) )
+ override def isDefinedAt(msg: Any) = seq.exists(_.isDefinedAt(msg))
}
diff --git a/akka-actor/src/main/scala/akka/serialization/Format.scala b/akka-actor/src/main/scala/akka/serialization/Format.scala
index bd7cb09392..114dc54830 100644
--- a/akka-actor/src/main/scala/akka/serialization/Format.scala
+++ b/akka-actor/src/main/scala/akka/serialization/Format.scala
@@ -6,13 +6,14 @@ package akka.serialization
import akka.actor.Actor
-import java.io.{ObjectOutputStream, ByteArrayOutputStream, ObjectInputStream, ByteArrayInputStream}
+import java.io.{ ObjectOutputStream, ByteArrayOutputStream, ObjectInputStream, ByteArrayInputStream }
/**
* @author Jonas Bonér
*/
trait Serializer extends scala.Serializable {
- @volatile var classLoader: Option[ClassLoader] = None
+ @volatile
+ var classLoader: Option[ClassLoader] = None
def deepClone(obj: AnyRef): AnyRef = fromBinary(toBinary(obj), Some(obj.getClass))
def toBinary(obj: AnyRef): Array[Byte]
@@ -39,7 +40,7 @@ trait Format[T <: Actor] extends FromBinary[T] with ToBinary[T]
object Format {
object Default extends Serializer {
- import java.io.{ObjectOutputStream, ByteArrayOutputStream, ObjectInputStream, ByteArrayInputStream}
+ import java.io.{ ObjectOutputStream, ByteArrayOutputStream, ObjectInputStream, ByteArrayInputStream }
//import org.apache.commons.io.input.ClassLoaderObjectInputStream
def toBinary(obj: AnyRef): Array[Byte] = {
diff --git a/akka-actor/src/main/scala/akka/util/Address.scala b/akka-actor/src/main/scala/akka/util/Address.scala
index 794039498c..23920b725e 100644
--- a/akka-actor/src/main/scala/akka/util/Address.scala
+++ b/akka-actor/src/main/scala/akka/util/Address.scala
@@ -8,8 +8,8 @@ import java.net.InetSocketAddress
object Address {
def apply(hostname: String, port: Int) = new Address(hostname, port)
def apply(inetAddress: InetSocketAddress): Address = inetAddress match {
- case null => null
- case inet => new Address(inet.getAddress.getHostAddress, inet.getPort)
+ case null ⇒ null
+ case inet ⇒ new Address(inet.getAddress.getHostAddress, inet.getPort)
}
}
@@ -23,7 +23,7 @@ class Address(val hostname: String, val port: Int) {
override def equals(that: Any): Boolean = {
that.isInstanceOf[Address] &&
- that.asInstanceOf[Address].hostname == hostname &&
- that.asInstanceOf[Address].port == port
+ that.asInstanceOf[Address].hostname == hostname &&
+ that.asInstanceOf[Address].port == port
}
}
diff --git a/akka-actor/src/main/scala/akka/util/AkkaLoader.scala b/akka-actor/src/main/scala/akka/util/AkkaLoader.scala
index c780cb48f3..cb246f2ecf 100644
--- a/akka-actor/src/main/scala/akka/util/AkkaLoader.scala
+++ b/akka-actor/src/main/scala/akka/util/AkkaLoader.scala
@@ -13,14 +13,15 @@ import akka.actor.Actor
class AkkaLoader {
private val hasBooted = new Switch(false)
- @volatile private var _bundles: Option[Bootable] = None
+ @volatile
+ private var _bundles: Option[Bootable] = None
def bundles = _bundles;
/*
* Boot initializes the specified bundles
*/
- def boot(withBanner: Boolean, b : Bootable): Unit = hasBooted switchOn {
+ def boot(withBanner: Boolean, b: Bootable): Unit = hasBooted switchOn {
if (withBanner) printBanner()
println("Starting Akka...")
b.onLoad
diff --git a/akka-actor/src/main/scala/akka/util/BoundedBlockingQueue.scala b/akka-actor/src/main/scala/akka/util/BoundedBlockingQueue.scala
index ba4e508454..48d25613ad 100644
--- a/akka-actor/src/main/scala/akka/util/BoundedBlockingQueue.scala
+++ b/akka-actor/src/main/scala/akka/util/BoundedBlockingQueue.scala
@@ -12,12 +12,12 @@ class BoundedBlockingQueue[E <: AnyRef](
val maxCapacity: Int, private val backing: Queue[E]) extends AbstractQueue[E] with BlockingQueue[E] {
backing match {
- case null => throw new IllegalArgumentException("Backing Queue may not be null")
- case b: BlockingQueue[_] =>
+ case null ⇒ throw new IllegalArgumentException("Backing Queue may not be null")
+ case b: BlockingQueue[_] ⇒
require(maxCapacity > 0)
require(b.size() == 0)
require(b.remainingCapacity >= maxCapacity)
- case b: Queue[_] =>
+ case b: Queue[_] ⇒
require(b.size() == 0)
require(maxCapacity > 0)
}
@@ -74,7 +74,7 @@ class BoundedBlockingQueue[E <: AnyRef](
var nanos = unit.toNanos(timeout)
lock.lockInterruptibly()
try {
- while(backing.size() == maxCapacity) {
+ while (backing.size() == maxCapacity) {
if (nanos <= 0)
return false
else
@@ -94,21 +94,21 @@ class BoundedBlockingQueue[E <: AnyRef](
try {
var result: E = null.asInstanceOf[E]
var hasResult = false
- while(!hasResult) {
+ while (!hasResult) {
hasResult = backing.poll() match {
- case null if nanos <= 0 =>
+ case null if nanos <= 0 ⇒
result = null.asInstanceOf[E]
true
- case null =>
+ case null ⇒
try {
nanos = notEmpty.awaitNanos(nanos)
} catch {
- case ie: InterruptedException =>
+ case ie: InterruptedException ⇒
notEmpty.signal()
throw ie
}
false
- case e =>
+ case e ⇒
notFull.signal()
result = e
true
@@ -124,8 +124,8 @@ class BoundedBlockingQueue[E <: AnyRef](
lock.lock()
try {
backing.poll() match {
- case null => null.asInstanceOf[E]
- case e =>
+ case null ⇒ null.asInstanceOf[E]
+ case e ⇒
notFull.signal()
e
}
@@ -204,10 +204,10 @@ class BoundedBlockingQueue[E <: AnyRef](
try {
var n = 0
var e: E = null.asInstanceOf[E]
- while(n < maxElements) {
+ while (n < maxElements) {
backing.poll() match {
- case null => return n
- case e =>
+ case null ⇒ return n
+ case e ⇒
c add e
n += 1
}
@@ -280,7 +280,7 @@ class BoundedBlockingQueue[E <: AnyRef](
lock.lock()
try {
val i = backing.iterator()
- while(i.hasNext) {
+ while (i.hasNext) {
if (i.next eq target) {
i.remove()
notFull.signal()
diff --git a/akka-actor/src/main/scala/akka/util/Convert.scala b/akka-actor/src/main/scala/akka/util/Convert.scala
index 85f274d26f..d91267bf6d 100644
--- a/akka-actor/src/main/scala/akka/util/Convert.scala
+++ b/akka-actor/src/main/scala/akka/util/Convert.scala
@@ -10,7 +10,7 @@ package akka.util
object Convert {
def intToBytes(value: Int): Array[Byte] = {
- val bytes = Array.fill[Byte](4)(0)
+ val bytes = Array.fill[Byte](4)(0)
bytes(0) = (value >>> 24).asInstanceOf[Byte]
bytes(1) = (value >>> 16).asInstanceOf[Byte]
bytes(2) = (value >>> 8).asInstanceOf[Byte]
@@ -19,7 +19,7 @@ object Convert {
}
def bytesToInt(bytes: Array[Byte], offset: Int): Int = {
- (0 until 4).foldLeft(0)((value, index) => value + ((bytes(index + offset) & 0x000000FF) << ((4 - 1 - index) * 8)))
+ (0 until 4).foldLeft(0)((value, index) ⇒ value + ((bytes(index + offset) & 0x000000FF) << ((4 - 1 - index) * 8)))
}
def longToBytes(value: Long): Array[Byte] = {
@@ -30,19 +30,19 @@ object Convert {
writeBuffer(3) = (value >>> 32).asInstanceOf[Byte]
writeBuffer(4) = (value >>> 24).asInstanceOf[Byte]
writeBuffer(5) = (value >>> 16).asInstanceOf[Byte]
- writeBuffer(6) = (value >>> 8).asInstanceOf[Byte]
- writeBuffer(7) = (value >>> 0).asInstanceOf[Byte]
+ writeBuffer(6) = (value >>> 8).asInstanceOf[Byte]
+ writeBuffer(7) = (value >>> 0).asInstanceOf[Byte]
writeBuffer
}
def bytesToLong(buf: Array[Byte]): Long = {
((buf(0) & 0xFFL) << 56) |
- ((buf(1) & 0xFFL) << 48) |
- ((buf(2) & 0xFFL) << 40) |
- ((buf(3) & 0xFFL) << 32) |
- ((buf(4) & 0xFFL) << 24) |
- ((buf(5) & 0xFFL) << 16) |
- ((buf(6) & 0xFFL) << 8) |
- ((buf(7) & 0xFFL) << 0)
+ ((buf(1) & 0xFFL) << 48) |
+ ((buf(2) & 0xFFL) << 40) |
+ ((buf(3) & 0xFFL) << 32) |
+ ((buf(4) & 0xFFL) << 24) |
+ ((buf(5) & 0xFFL) << 16) |
+ ((buf(6) & 0xFFL) << 8) |
+ ((buf(7) & 0xFFL) << 0)
}
}
diff --git a/akka-actor/src/main/scala/akka/util/Crypt.scala b/akka-actor/src/main/scala/akka/util/Crypt.scala
index 63d6aff4df..bf83a546a7 100644
--- a/akka-actor/src/main/scala/akka/util/Crypt.scala
+++ b/akka-actor/src/main/scala/akka/util/Crypt.scala
@@ -4,7 +4,7 @@
package akka.util
-import java.security.{MessageDigest, SecureRandom}
+import java.security.{ MessageDigest, SecureRandom }
/**
* @author Jonas Bonér
@@ -15,11 +15,11 @@ object Crypt {
lazy val random = SecureRandom.getInstance("SHA1PRNG")
- def md5(text: String): String = md5(unifyLineSeparator(text).getBytes("ASCII"))
+ def md5(text: String): String = md5(unifyLineSeparator(text).getBytes("ASCII"))
- def md5(bytes: Array[Byte]): String = digest(bytes, MessageDigest.getInstance("MD5"))
+ def md5(bytes: Array[Byte]): String = digest(bytes, MessageDigest.getInstance("MD5"))
- def sha1(text: String): String = sha1(unifyLineSeparator(text).getBytes("ASCII"))
+ def sha1(text: String): String = sha1(unifyLineSeparator(text).getBytes("ASCII"))
def sha1(bytes: Array[Byte]): String = digest(bytes, MessageDigest.getInstance("SHA1"))
@@ -36,7 +36,7 @@ object Crypt {
def hexify(bytes: Array[Byte]): String = {
val builder = new StringBuilder
- bytes.foreach { byte => builder.append(hex.charAt((byte & 0xF) >> 4)).append(hex.charAt(byte & 0xF)) }
+ bytes.foreach { byte ⇒ builder.append(hex.charAt((byte & 0xF) >> 4)).append(hex.charAt(byte & 0xF)) }
builder.toString
}
diff --git a/akka-actor/src/main/scala/akka/util/Duration.scala b/akka-actor/src/main/scala/akka/util/Duration.scala
index 4e105c198f..2e4b69756b 100644
--- a/akka-actor/src/main/scala/akka/util/Duration.scala
+++ b/akka-actor/src/main/scala/akka/util/Duration.scala
@@ -6,14 +6,14 @@ package akka.util
import java.util.concurrent.TimeUnit
import TimeUnit._
-import java.lang.{Long => JLong, Double => JDouble}
+import java.lang.{ Long ⇒ JLong, Double ⇒ JDouble }
object Duration {
- def apply(length: Long, unit: TimeUnit) : Duration = new FiniteDuration(length, unit)
- def apply(length: Double, unit: TimeUnit) : Duration = fromNanos(unit.toNanos(1) * length)
- def apply(length: Long, unit: String) : Duration = new FiniteDuration(length, timeUnit(unit))
+ def apply(length: Long, unit: TimeUnit): Duration = new FiniteDuration(length, unit)
+ def apply(length: Double, unit: TimeUnit): Duration = fromNanos(unit.toNanos(1) * length)
+ def apply(length: Long, unit: String): Duration = new FiniteDuration(length, timeUnit(unit))
- def fromNanos(nanos : Long) : Duration = {
+ def fromNanos(nanos: Long): Duration = {
if (nanos % 86400000000000L == 0) {
Duration(nanos / 86400000000000L, DAYS)
} else if (nanos % 3600000000000L == 0) {
@@ -31,18 +31,18 @@ object Duration {
}
}
- def fromNanos(nanos : Double) : Duration = fromNanos((nanos + 0.5).asInstanceOf[Long])
+ def fromNanos(nanos: Double): Duration = fromNanos((nanos + 0.5).asInstanceOf[Long])
/**
* Construct a Duration by parsing a String. In case of a format error, a
* RuntimeException is thrown. See `unapply(String)` for more information.
*/
- def apply(s : String) : Duration = unapply(s) getOrElse sys.error("format error")
+ def apply(s: String): Duration = unapply(s) getOrElse sys.error("format error")
/**
* Deconstruct a Duration into length and unit if it is finite.
*/
- def unapply(d : Duration) : Option[(Long, TimeUnit)] = {
+ def unapply(d: Duration): Option[(Long, TimeUnit)] = {
if (d.finite_?) {
Some((d.length, d.unit))
} else {
@@ -50,15 +50,15 @@ object Duration {
}
}
- private val RE = ("""^\s*(\d+(?:\.\d+)?)\s*"""+ // length part
- "(?:"+ // units are distinguished in separate match groups
- "(d|day|days)|"+
- "(h|hour|hours)|"+
- "(min|minute|minutes)|"+
- "(s|sec|second|seconds)|"+
- "(ms|milli|millis|millisecond|milliseconds)|"+
- "(µs|micro|micros|microsecond|microseconds)|"+
- "(ns|nano|nanos|nanosecond|nanoseconds)"+
+ private val RE = ("""^\s*(\d+(?:\.\d+)?)\s*""" + // length part
+ "(?:" + // units are distinguished in separate match groups
+ "(d|day|days)|" +
+ "(h|hour|hours)|" +
+ "(min|minute|minutes)|" +
+ "(s|sec|second|seconds)|" +
+ "(ms|milli|millis|millisecond|milliseconds)|" +
+ "(µs|micro|micros|microsecond|microseconds)|" +
+ "(ns|nano|nanos|nanosecond|nanoseconds)" +
""")\s*$""").r // close the non-capturing group
private val REinf = """^\s*Inf\s*$""".r
private val REminf = """^\s*(?:-\s*|Minus)Inf\s*""".r
@@ -68,73 +68,67 @@ object Duration {
* whitespace is allowed before, between and after the parts. Infinities are
* designated by `"Inf"` and `"-Inf"` or `"MinusInf"`.
*/
- def unapply(s : String) : Option[Duration] = s match {
- case RE(length, d, h, m, s, ms, mus, ns) =>
- if ( d ne null) Some(Duration(JDouble.parseDouble(length), DAYS)) else
- if ( h ne null) Some(Duration(JDouble.parseDouble(length), HOURS)) else
- if ( m ne null) Some(Duration(JDouble.parseDouble(length), MINUTES)) else
- if ( s ne null) Some(Duration(JDouble.parseDouble(length), SECONDS)) else
- if ( ms ne null) Some(Duration(JDouble.parseDouble(length), MILLISECONDS)) else
- if (mus ne null) Some(Duration(JDouble.parseDouble(length), MICROSECONDS)) else
- if ( ns ne null) Some(Duration(JDouble.parseDouble(length), NANOSECONDS)) else
- sys.error("made some error in regex (should not be possible)")
- case REinf() => Some(Inf)
- case REminf() => Some(MinusInf)
- case _ => None
+ def unapply(s: String): Option[Duration] = s match {
+ case RE(length, d, h, m, s, ms, mus, ns) ⇒
+ if (d ne null) Some(Duration(JDouble.parseDouble(length), DAYS)) else if (h ne null) Some(Duration(JDouble.parseDouble(length), HOURS)) else if (m ne null) Some(Duration(JDouble.parseDouble(length), MINUTES)) else if (s ne null) Some(Duration(JDouble.parseDouble(length), SECONDS)) else if (ms ne null) Some(Duration(JDouble.parseDouble(length), MILLISECONDS)) else if (mus ne null) Some(Duration(JDouble.parseDouble(length), MICROSECONDS)) else if (ns ne null) Some(Duration(JDouble.parseDouble(length), NANOSECONDS)) else
+ sys.error("made some error in regex (should not be possible)")
+ case REinf() ⇒ Some(Inf)
+ case REminf() ⇒ Some(MinusInf)
+ case _ ⇒ None
}
/**
* Parse TimeUnit from string representation.
*/
def timeUnit(unit: String) = unit.toLowerCase match {
- case "d" | "day" | "days" => DAYS
- case "h" | "hour" | "hours" => HOURS
- case "min" | "minute" | "minutes" => MINUTES
- case "s" | "sec" | "second" | "seconds" => SECONDS
- case "ms" | "milli" | "millis" | "millisecond" | "milliseconds" => MILLISECONDS
- case "µs" | "micro" | "micros" | "microsecond" | "microseconds" => MICROSECONDS
- case "ns" | "nano" | "nanos" | "nanosecond" | "nanoseconds" => NANOSECONDS
+ case "d" | "day" | "days" ⇒ DAYS
+ case "h" | "hour" | "hours" ⇒ HOURS
+ case "min" | "minute" | "minutes" ⇒ MINUTES
+ case "s" | "sec" | "second" | "seconds" ⇒ SECONDS
+ case "ms" | "milli" | "millis" | "millisecond" | "milliseconds" ⇒ MILLISECONDS
+ case "µs" | "micro" | "micros" | "microsecond" | "microseconds" ⇒ MICROSECONDS
+ case "ns" | "nano" | "nanos" | "nanosecond" | "nanoseconds" ⇒ NANOSECONDS
}
- val Zero : Duration = new FiniteDuration(0, NANOSECONDS)
+ val Zero: Duration = new FiniteDuration(0, NANOSECONDS)
trait Infinite {
- this : Duration =>
+ this: Duration ⇒
- override def equals(other : Any) = false
+ override def equals(other: Any) = false
- def +(other : Duration) : Duration =
+ def +(other: Duration): Duration =
other match {
- case _ : this.type => this
- case _ : Infinite => throw new IllegalArgumentException("illegal addition of infinities")
- case _ => this
+ case _: this.type ⇒ this
+ case _: Infinite ⇒ throw new IllegalArgumentException("illegal addition of infinities")
+ case _ ⇒ this
}
- def -(other : Duration) : Duration =
+ def -(other: Duration): Duration =
other match {
- case _ : this.type => throw new IllegalArgumentException("illegal subtraction of infinities")
- case _ => this
+ case _: this.type ⇒ throw new IllegalArgumentException("illegal subtraction of infinities")
+ case _ ⇒ this
}
- def *(factor : Double) : Duration = this
- def /(factor : Double) : Duration = this
- def /(other : Duration) : Double =
+ def *(factor: Double): Duration = this
+ def /(factor: Double): Duration = this
+ def /(other: Duration): Double =
other match {
- case _ : Infinite => throw new IllegalArgumentException("illegal division of infinities")
+ case _: Infinite ⇒ throw new IllegalArgumentException("illegal division of infinities")
// maybe questionable but pragmatic: Inf / 0 => Inf
- case x => Double.PositiveInfinity * (if ((this > Zero) ^ (other >= Zero)) -1 else 1)
+ case x ⇒ Double.PositiveInfinity * (if ((this > Zero) ^ (other >= Zero)) -1 else 1)
}
-
+
def finite_? = false
-
- def length : Long = throw new IllegalArgumentException("length not allowed on infinite Durations")
- def unit : TimeUnit = throw new IllegalArgumentException("unit not allowed on infinite Durations")
- def toNanos : Long = throw new IllegalArgumentException("toNanos not allowed on infinite Durations")
- def toMicros : Long = throw new IllegalArgumentException("toMicros not allowed on infinite Durations")
- def toMillis : Long = throw new IllegalArgumentException("toMillis not allowed on infinite Durations")
- def toSeconds : Long = throw new IllegalArgumentException("toSeconds not allowed on infinite Durations")
- def toMinutes : Long = throw new IllegalArgumentException("toMinutes not allowed on infinite Durations")
- def toHours : Long = throw new IllegalArgumentException("toHours not allowed on infinite Durations")
- def toDays : Long = throw new IllegalArgumentException("toDays not allowed on infinite Durations")
- def toUnit(unit : TimeUnit) : Double = throw new IllegalArgumentException("toUnit not allowed on infinite Durations")
+
+ def length: Long = throw new IllegalArgumentException("length not allowed on infinite Durations")
+ def unit: TimeUnit = throw new IllegalArgumentException("unit not allowed on infinite Durations")
+ def toNanos: Long = throw new IllegalArgumentException("toNanos not allowed on infinite Durations")
+ def toMicros: Long = throw new IllegalArgumentException("toMicros not allowed on infinite Durations")
+ def toMillis: Long = throw new IllegalArgumentException("toMillis not allowed on infinite Durations")
+ def toSeconds: Long = throw new IllegalArgumentException("toSeconds not allowed on infinite Durations")
+ def toMinutes: Long = throw new IllegalArgumentException("toMinutes not allowed on infinite Durations")
+ def toHours: Long = throw new IllegalArgumentException("toHours not allowed on infinite Durations")
+ def toDays: Long = throw new IllegalArgumentException("toDays not allowed on infinite Durations")
+ def toUnit(unit: TimeUnit): Double = throw new IllegalArgumentException("toUnit not allowed on infinite Durations")
def printHMS = toString
}
@@ -143,12 +137,12 @@ object Duration {
* Infinite duration: greater than any other and not equal to any other,
* including itself.
*/
- val Inf : Duration = new Duration with Infinite {
+ val Inf: Duration = new Duration with Infinite {
override def toString = "Duration.Inf"
- def >(other : Duration) = true
- def >=(other : Duration) = true
- def <(other : Duration) = false
- def <=(other : Duration) = false
+ def >(other: Duration) = true
+ def >=(other: Duration) = true
+ def <(other: Duration) = false
+ def <=(other: Duration) = false
def unary_- : Duration = MinusInf
}
@@ -156,20 +150,20 @@ object Duration {
* Infinite negative duration: lesser than any other and not equal to any other,
* including itself.
*/
- val MinusInf : Duration = new Duration with Infinite {
+ val MinusInf: Duration = new Duration with Infinite {
override def toString = "Duration.MinusInf"
- def >(other : Duration) = false
- def >=(other : Duration) = false
- def <(other : Duration) = true
- def <=(other : Duration) = true
+ def >(other: Duration) = false
+ def >=(other: Duration) = false
+ def <(other: Duration) = true
+ def <=(other: Duration) = true
def unary_- : Duration = Inf
}
// Java Factories
- def create(length : Long, unit : TimeUnit) : Duration = apply(length, unit)
- def create(length : Double, unit : TimeUnit) : Duration = apply(length, unit)
- def create(length : Long, unit : String) : Duration = apply(length, unit)
- def parse(s : String) : Duration = unapply(s).get
+ def create(length: Long, unit: TimeUnit): Duration = apply(length, unit)
+ def create(length: Double, unit: TimeUnit): Duration = apply(length, unit)
+ def create(length: Long, unit: String): Duration = apply(length, unit)
+ def parse(s: String): Duration = unapply(s).get
}
/**
@@ -218,39 +212,39 @@ object Duration {
*
*/
abstract class Duration {
- def length : Long
- def unit : TimeUnit
- def toNanos : Long
- def toMicros : Long
- def toMillis : Long
- def toSeconds : Long
- def toMinutes : Long
- def toHours : Long
- def toDays : Long
- def toUnit(unit : TimeUnit) : Double
- def printHMS : String
- def <(other : Duration) : Boolean
- def <=(other : Duration) : Boolean
- def >(other : Duration) : Boolean
- def >=(other : Duration) : Boolean
- def +(other : Duration) : Duration
- def -(other : Duration) : Duration
- def *(factor : Double) : Duration
- def /(factor : Double) : Duration
- def /(other : Duration) : Double
+ def length: Long
+ def unit: TimeUnit
+ def toNanos: Long
+ def toMicros: Long
+ def toMillis: Long
+ def toSeconds: Long
+ def toMinutes: Long
+ def toHours: Long
+ def toDays: Long
+ def toUnit(unit: TimeUnit): Double
+ def printHMS: String
+ def <(other: Duration): Boolean
+ def <=(other: Duration): Boolean
+ def >(other: Duration): Boolean
+ def >=(other: Duration): Boolean
+ def +(other: Duration): Duration
+ def -(other: Duration): Duration
+ def *(factor: Double): Duration
+ def /(factor: Double): Duration
+ def /(other: Duration): Double
def unary_- : Duration
def finite_? : Boolean
// Java API
- def lt(other : Duration) = this < other
- def lteq(other : Duration) = this <= other
- def gt(other : Duration) = this > other
- def gteq(other : Duration) = this >= other
- def plus(other : Duration) = this + other
- def minus(other : Duration) = this - other
- def mul(factor : Double) = this * factor
- def div(factor : Double) = this / factor
- def div(other : Duration) = this / other
+ def lt(other: Duration) = this < other
+ def lteq(other: Duration) = this <= other
+ def gt(other: Duration) = this > other
+ def gteq(other: Duration) = this >= other
+ def plus(other: Duration) = this + other
+ def minus(other: Duration) = this - other
+ def mul(factor: Double) = this * factor
+ def div(factor: Double) = this / factor
+ def div(other: Duration) = this / other
def neg() = -this
def isFinite() = finite_?
}
@@ -267,28 +261,28 @@ class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duration {
def toMinutes = unit.toMinutes(length)
def toHours = unit.toHours(length)
def toDays = unit.toDays(length)
- def toUnit(u : TimeUnit) = long2double(toNanos) / NANOSECONDS.convert(1, u)
+ def toUnit(u: TimeUnit) = long2double(toNanos) / NANOSECONDS.convert(1, u)
override def toString = this match {
- case Duration(1, DAYS) => "1 day"
- case Duration(x, DAYS) => x+" days"
- case Duration(1, HOURS) => "1 hour"
- case Duration(x, HOURS) => x+" hours"
- case Duration(1, MINUTES) => "1 minute"
- case Duration(x, MINUTES) => x+" minutes"
- case Duration(1, SECONDS) => "1 second"
- case Duration(x, SECONDS) => x+" seconds"
- case Duration(1, MILLISECONDS) => "1 millisecond"
- case Duration(x, MILLISECONDS) => x+" milliseconds"
- case Duration(1, MICROSECONDS) => "1 microsecond"
- case Duration(x, MICROSECONDS) => x+" microseconds"
- case Duration(1, NANOSECONDS) => "1 nanosecond"
- case Duration(x, NANOSECONDS) => x+" nanoseconds"
+ case Duration(1, DAYS) ⇒ "1 day"
+ case Duration(x, DAYS) ⇒ x + " days"
+ case Duration(1, HOURS) ⇒ "1 hour"
+ case Duration(x, HOURS) ⇒ x + " hours"
+ case Duration(1, MINUTES) ⇒ "1 minute"
+ case Duration(x, MINUTES) ⇒ x + " minutes"
+ case Duration(1, SECONDS) ⇒ "1 second"
+ case Duration(x, SECONDS) ⇒ x + " seconds"
+ case Duration(1, MILLISECONDS) ⇒ "1 millisecond"
+ case Duration(x, MILLISECONDS) ⇒ x + " milliseconds"
+ case Duration(1, MICROSECONDS) ⇒ "1 microsecond"
+ case Duration(x, MICROSECONDS) ⇒ x + " microseconds"
+ case Duration(1, NANOSECONDS) ⇒ "1 nanosecond"
+ case Duration(x, NANOSECONDS) ⇒ x + " nanoseconds"
}
def printHMS = "%02d:%02d:%06.3f".format(toHours, toMinutes % 60, toMillis / 1000. % 60)
- def <(other : Duration) = {
+ def <(other: Duration) = {
if (other.finite_?) {
toNanos < other.asInstanceOf[FiniteDuration].toNanos
} else {
@@ -296,7 +290,7 @@ class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duration {
}
}
- def <=(other : Duration) = {
+ def <=(other: Duration) = {
if (other.finite_?) {
toNanos <= other.asInstanceOf[FiniteDuration].toNanos
} else {
@@ -304,7 +298,7 @@ class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duration {
}
}
- def >(other : Duration) = {
+ def >(other: Duration) = {
if (other.finite_?) {
toNanos > other.asInstanceOf[FiniteDuration].toNanos
} else {
@@ -312,7 +306,7 @@ class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duration {
}
}
- def >=(other : Duration) = {
+ def >=(other: Duration) = {
if (other.finite_?) {
toNanos >= other.asInstanceOf[FiniteDuration].toNanos
} else {
@@ -320,7 +314,7 @@ class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duration {
}
}
- def +(other : Duration) = {
+ def +(other: Duration) = {
if (!other.finite_?) {
other
} else {
@@ -329,7 +323,7 @@ class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duration {
}
}
- def -(other : Duration) = {
+ def -(other: Duration) = {
if (!other.finite_?) {
other
} else {
@@ -338,19 +332,19 @@ class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duration {
}
}
- def *(factor : Double) = fromNanos(long2double(toNanos) * factor)
+ def *(factor: Double) = fromNanos(long2double(toNanos) * factor)
- def /(factor : Double) = fromNanos(long2double(toNanos) / factor)
+ def /(factor: Double) = fromNanos(long2double(toNanos) / factor)
- def /(other : Duration) = if (other.finite_?) long2double(toNanos) / other.toNanos else 0
+ def /(other: Duration) = if (other.finite_?) long2double(toNanos) / other.toNanos else 0
def unary_- = Duration(-length, unit)
def finite_? = true
- override def equals(other : Any) =
+ override def equals(other: Any) =
other.isInstanceOf[FiniteDuration] &&
- toNanos == other.asInstanceOf[FiniteDuration].toNanos
+ toNanos == other.asInstanceOf[FiniteDuration].toNanos
override def hashCode = toNanos.asInstanceOf[Int]
}
@@ -362,13 +356,13 @@ class DurationInt(n: Int) {
def nano = Duration(n, NANOSECONDS)
def microseconds = Duration(n, MICROSECONDS)
- def micros = Duration(n, MICROSECONDS)
+ def micros = Duration(n, MICROSECONDS)
def microsecond = Duration(n, MICROSECONDS)
- def micro = Duration(n, MICROSECONDS)
+ def micro = Duration(n, MICROSECONDS)
- def milliseconds = Duration(n, MILLISECONDS)
+ def milliseconds = Duration(n, MILLISECONDS)
def millis = Duration(n, MILLISECONDS)
- def millisecond = Duration(n, MILLISECONDS)
+ def millisecond = Duration(n, MILLISECONDS)
def milli = Duration(n, MILLISECONDS)
def seconds = Duration(n, SECONDS)
@@ -391,13 +385,13 @@ class DurationLong(n: Long) {
def nano = Duration(n, NANOSECONDS)
def microseconds = Duration(n, MICROSECONDS)
- def micros = Duration(n, MICROSECONDS)
+ def micros = Duration(n, MICROSECONDS)
def microsecond = Duration(n, MICROSECONDS)
- def micro = Duration(n, MICROSECONDS)
+ def micro = Duration(n, MICROSECONDS)
- def milliseconds = Duration(n, MILLISECONDS)
+ def milliseconds = Duration(n, MILLISECONDS)
def millis = Duration(n, MILLISECONDS)
- def millisecond = Duration(n, MILLISECONDS)
+ def millisecond = Duration(n, MILLISECONDS)
def milli = Duration(n, MILLISECONDS)
def seconds = Duration(n, SECONDS)
@@ -420,13 +414,13 @@ class DurationDouble(d: Double) {
def nano = Duration(d, NANOSECONDS)
def microseconds = Duration(d, MICROSECONDS)
- def micros = Duration(d, MICROSECONDS)
+ def micros = Duration(d, MICROSECONDS)
def microsecond = Duration(d, MICROSECONDS)
- def micro = Duration(d, MICROSECONDS)
+ def micro = Duration(d, MICROSECONDS)
- def milliseconds = Duration(d, MILLISECONDS)
+ def milliseconds = Duration(d, MILLISECONDS)
def millis = Duration(d, MILLISECONDS)
- def millisecond = Duration(d, MILLISECONDS)
+ def millisecond = Duration(d, MILLISECONDS)
def milli = Duration(d, MILLISECONDS)
def seconds = Duration(d, SECONDS)
diff --git a/akka-actor/src/main/scala/akka/util/HashCode.scala b/akka-actor/src/main/scala/akka/util/HashCode.scala
index 51d2926bb9..4dc74c932a 100644
--- a/akka-actor/src/main/scala/akka/util/HashCode.scala
+++ b/akka-actor/src/main/scala/akka/util/HashCode.scala
@@ -4,8 +4,8 @@
package akka.util
-import java.lang.reflect.{Array => JArray}
-import java.lang.{Float => JFloat, Double => JDouble}
+import java.lang.reflect.{ Array ⇒ JArray }
+import java.lang.{ Float ⇒ JFloat, Double ⇒ JDouble }
/**
* Set of methods which allow easy implementation of hashCode.
@@ -28,25 +28,25 @@ object HashCode {
val SEED = 23
def hash(seed: Int, any: Any): Int = any match {
- case value: Boolean => hash(seed, value)
- case value: Char => hash(seed, value)
- case value: Short => hash(seed, value)
- case value: Int => hash(seed, value)
- case value: Long => hash(seed, value)
- case value: Float => hash(seed, value)
- case value: Double => hash(seed, value)
- case value: Byte => hash(seed, value)
- case value: AnyRef =>
+ case value: Boolean ⇒ hash(seed, value)
+ case value: Char ⇒ hash(seed, value)
+ case value: Short ⇒ hash(seed, value)
+ case value: Int ⇒ hash(seed, value)
+ case value: Long ⇒ hash(seed, value)
+ case value: Float ⇒ hash(seed, value)
+ case value: Double ⇒ hash(seed, value)
+ case value: Byte ⇒ hash(seed, value)
+ case value: AnyRef ⇒
var result = seed
if (value eq null) result = hash(result, 0)
else if (!isArray(value)) result = hash(result, value.hashCode())
- else for (id <- 0 until JArray.getLength(value)) result = hash(result, JArray.get(value, id)) // is an array
+ else for (id ← 0 until JArray.getLength(value)) result = hash(result, JArray.get(value, id)) // is an array
result
}
def hash(seed: Int, value: Boolean): Int = firstTerm(seed) + (if (value) 1 else 0)
def hash(seed: Int, value: Char): Int = firstTerm(seed) + value.asInstanceOf[Int]
def hash(seed: Int, value: Int): Int = firstTerm(seed) + value
- def hash(seed: Int, value: Long): Int = firstTerm(seed) + (value ^ (value >>> 32) ).asInstanceOf[Int]
+ def hash(seed: Int, value: Long): Int = firstTerm(seed) + (value ^ (value >>> 32)).asInstanceOf[Int]
def hash(seed: Int, value: Float): Int = hash(seed, JFloat.floatToIntBits(value))
def hash(seed: Int, value: Double): Int = hash(seed, JDouble.doubleToLongBits(value))
diff --git a/akka-actor/src/main/scala/akka/util/Helpers.scala b/akka-actor/src/main/scala/akka/util/Helpers.scala
index 405df37aac..6b80dfec5a 100644
--- a/akka-actor/src/main/scala/akka/util/Helpers.scala
+++ b/akka-actor/src/main/scala/akka/util/Helpers.scala
@@ -23,28 +23,27 @@ object Helpers {
}
def bytesToInt(bytes: Array[Byte], offset: Int): Int = {
- (0 until 4).foldLeft(0)((value, index) => value + ((bytes(index + offset) & 0x000000FF) << ((4 - 1 - index) * 8)))
+ (0 until 4).foldLeft(0)((value, index) ⇒ value + ((bytes(index + offset) & 0x000000FF) << ((4 - 1 - index) * 8)))
}
def flatten[T: ClassManifest](array: Array[Any]) = array.flatMap {
- case arr: Array[T] => arr
- case elem: T => Array(elem)
+ case arr: Array[T] ⇒ arr
+ case elem: T ⇒ Array(elem)
}
- def ignore[E : Manifest](body: => Unit) {
- try {
- body
- }
- catch {
- case e if manifest[E].erasure.isAssignableFrom(e.getClass) => ()
- }
- }
-
- def withPrintStackTraceOnError(body: => Unit) {
+ def ignore[E: Manifest](body: ⇒ Unit) {
try {
body
} catch {
- case e: Throwable =>
+ case e if manifest[E].erasure.isAssignableFrom(e.getClass) ⇒ ()
+ }
+ }
+
+ def withPrintStackTraceOnError(body: ⇒ Unit) {
+ try {
+ body
+ } catch {
+ case e: Throwable ⇒
EventHandler.error(e, this, e.toString)
throw e
}
@@ -67,7 +66,7 @@ object Helpers {
try {
narrow(o)
} catch {
- case e: ClassCastException =>
+ case e: ClassCastException ⇒
None
}
@@ -80,7 +79,7 @@ object Helpers {
* res0: ResultOrError[Int] = ResultOrError@a96606
*
* scala> res0()
- res1: Int = 1
+ * res1: Int = 1
*
* scala> res0() = 3
*
@@ -103,20 +102,20 @@ object Helpers {
* at Re...
*
*/
- class ResultOrError[R](result: R){
+ class ResultOrError[R](result: R) {
private[this] var contents: Either[R, Throwable] = Left(result)
- def update(value: => R) {
+ def update(value: ⇒ R) {
contents = try {
Left(value)
} catch {
- case (error : Throwable) => Right(error)
+ case (error: Throwable) ⇒ Right(error)
}
}
def apply() = contents match {
- case Left(result) => result
- case Right(error) => throw error.fillInStackTrace
+ case Left(result) ⇒ result
+ case Right(error) ⇒ throw error.fillInStackTrace
}
}
object ResultOrError {
diff --git a/akka-actor/src/main/scala/akka/util/JMX.scala b/akka-actor/src/main/scala/akka/util/JMX.scala
index 05ba9c9ff1..d75269c1e0 100644
--- a/akka-actor/src/main/scala/akka/util/JMX.scala
+++ b/akka-actor/src/main/scala/akka/util/JMX.scala
@@ -7,7 +7,7 @@ package akka.util
import akka.event.EventHandler
import java.lang.management.ManagementFactory
-import javax.management.{ObjectInstance, ObjectName, InstanceAlreadyExistsException, InstanceNotFoundException}
+import javax.management.{ ObjectInstance, ObjectName, InstanceAlreadyExistsException, InstanceNotFoundException }
/**
* @author Jonas Bonér
@@ -21,9 +21,9 @@ object JMX {
def register(name: ObjectName, mbean: AnyRef): Option[ObjectInstance] = try {
Some(mbeanServer.registerMBean(mbean, name))
} catch {
- case e: InstanceAlreadyExistsException =>
+ case e: InstanceAlreadyExistsException ⇒
Some(mbeanServer.getObjectInstance(name))
- case e: Exception =>
+ case e: Exception ⇒
EventHandler.error(e, this, "Error when registering mbean [%s]".format(mbean))
None
}
@@ -31,7 +31,7 @@ object JMX {
def unregister(mbean: ObjectName) = try {
mbeanServer.unregisterMBean(mbean)
} catch {
- case e: InstanceNotFoundException => {}
- case e: Exception => EventHandler.error(e, this, "Error while unregistering mbean [%s]".format(mbean))
+ case e: InstanceNotFoundException ⇒ {}
+ case e: Exception ⇒ EventHandler.error(e, this, "Error while unregistering mbean [%s]".format(mbean))
}
}
diff --git a/akka-actor/src/main/scala/akka/util/ListenerManagement.scala b/akka-actor/src/main/scala/akka/util/ListenerManagement.scala
index ede46fc80a..e667890914 100644
--- a/akka-actor/src/main/scala/akka/util/ListenerManagement.scala
+++ b/akka-actor/src/main/scala/akka/util/ListenerManagement.scala
@@ -5,7 +5,7 @@
package akka.util
import java.util.concurrent.ConcurrentSkipListSet
-import akka.actor.{ActorInitializationException, ActorRef}
+import akka.actor.{ ActorInitializationException, ActorRef }
/**
* A manager for listener actors. Intended for mixin by observables.
@@ -50,7 +50,7 @@ trait ListenerManagement {
*/
def hasListener(listener: ActorRef): Boolean = listeners.contains(listener)
- protected[akka] def notifyListeners(message: => Any) {
+ protected[akka] def notifyListeners(message: ⇒ Any) {
if (hasListeners) {
val msg = message
val iterator = listeners.iterator
@@ -61,7 +61,7 @@ trait ListenerManagement {
try {
listener ! msg
} catch {
- case e : ActorInitializationException =>
+ case e: ActorInitializationException ⇒
if (listener.isShutdown) iterator.remove()
}
}
@@ -71,7 +71,7 @@ trait ListenerManagement {
/**
* Execute f with each listener as argument. ActorInitializationException is not handled.
*/
- protected[akka] def foreachListener(f: (ActorRef) => Unit) {
+ protected[akka] def foreachListener(f: (ActorRef) ⇒ Unit) {
val iterator = listeners.iterator
while (iterator.hasNext) {
val listener = iterator.next
diff --git a/akka-actor/src/main/scala/akka/util/LockUtil.scala b/akka-actor/src/main/scala/akka/util/LockUtil.scala
index bf72714c33..b281ca89be 100644
--- a/akka-actor/src/main/scala/akka/util/LockUtil.scala
+++ b/akka-actor/src/main/scala/akka/util/LockUtil.scala
@@ -4,8 +4,8 @@
package akka.util
-import java.util.concurrent.locks.{ReentrantReadWriteLock, ReentrantLock}
-import java.util.concurrent.atomic. {AtomicBoolean}
+import java.util.concurrent.locks.{ ReentrantReadWriteLock, ReentrantLock }
+import java.util.concurrent.atomic.{ AtomicBoolean }
import akka.event.EventHandler
/**
@@ -14,7 +14,7 @@ import akka.event.EventHandler
final class ReentrantGuard {
val lock = new ReentrantLock
- final def withGuard[T](body: => T): T = {
+ final def withGuard[T](body: ⇒ T): T = {
lock.lock
try {
body
@@ -23,8 +23,8 @@ final class ReentrantGuard {
}
}
- final def tryWithGuard[T](body: => T): T = {
- while(!lock.tryLock) { Thread.sleep(10) } // wait on the monitor to be unlocked
+ final def tryWithGuard[T](body: ⇒ T): T = {
+ while (!lock.tryLock) { Thread.sleep(10) } // wait on the monitor to be unlocked
try {
body
} finally {
@@ -41,7 +41,7 @@ class ReadWriteGuard {
val readLock = rwl.readLock
val writeLock = rwl.writeLock
- def withWriteGuard[T](body: => T): T = {
+ def withWriteGuard[T](body: ⇒ T): T = {
writeLock.lock
try {
body
@@ -50,7 +50,7 @@ class ReadWriteGuard {
}
}
- def withReadGuard[T](body: => T): T = {
+ def withReadGuard[T](body: ⇒ T): T = {
readLock.lock
try {
body
@@ -67,7 +67,7 @@ class ReadWriteGuard {
class SimpleLock {
val acquired = new AtomicBoolean(false)
- def ifPossible(perform: () => Unit): Boolean = {
+ def ifPossible(perform: () ⇒ Unit): Boolean = {
if (tryLock()) {
try {
perform
@@ -78,7 +78,7 @@ class SimpleLock {
} else false
}
- def ifPossibleYield[T](perform: () => T): Option[T] = {
+ def ifPossibleYield[T](perform: () ⇒ T): Option[T] = {
if (tryLock()) {
try {
Some(perform())
@@ -88,7 +88,7 @@ class SimpleLock {
} else None
}
- def ifPossibleApply[T,R](value: T)(function: (T) => R): Option[R] = {
+ def ifPossibleApply[T, R](value: T)(function: (T) ⇒ R): Option[R] = {
if (tryLock()) {
try {
Some(function(value))
@@ -100,11 +100,11 @@ class SimpleLock {
def tryLock() = {
if (acquired.get) false
- else acquired.compareAndSet(false,true)
+ else acquired.compareAndSet(false, true)
}
def tryUnlock() = {
- acquired.compareAndSet(true,false)
+ acquired.compareAndSet(true, false)
}
def locked = acquired.get
@@ -120,12 +120,12 @@ class SimpleLock {
class Switch(startAsOn: Boolean = false) {
private val switch = new AtomicBoolean(startAsOn)
- protected def transcend(from: Boolean, action: => Unit): Boolean = synchronized {
+ protected def transcend(from: Boolean, action: ⇒ Unit): Boolean = synchronized {
if (switch.compareAndSet(from, !from)) {
try {
action
} catch {
- case e: Throwable =>
+ case e: Throwable ⇒
EventHandler.error(e, this, e.getMessage)
switch.compareAndSet(!from, from) // revert status
throw e
@@ -134,61 +134,61 @@ class Switch(startAsOn: Boolean = false) {
} else false
}
- def switchOff(action: => Unit): Boolean = transcend(from = true, action)
- def switchOn(action: => Unit): Boolean = transcend(from = false, action)
+ def switchOff(action: ⇒ Unit): Boolean = transcend(from = true, action)
+ def switchOn(action: ⇒ Unit): Boolean = transcend(from = false, action)
def switchOff: Boolean = synchronized { switch.compareAndSet(true, false) }
- def switchOn: Boolean = synchronized { switch.compareAndSet(false, true) }
+ def switchOn: Boolean = synchronized { switch.compareAndSet(false, true) }
- def ifOnYield[T](action: => T): Option[T] = {
+ def ifOnYield[T](action: ⇒ T): Option[T] = {
if (switch.get) Some(action)
else None
}
- def ifOffYield[T](action: => T): Option[T] = {
+ def ifOffYield[T](action: ⇒ T): Option[T] = {
if (!switch.get) Some(action)
else None
}
- def ifOn(action: => Unit): Boolean = {
+ def ifOn(action: ⇒ Unit): Boolean = {
if (switch.get) {
action
true
} else false
}
- def ifOff(action: => Unit): Boolean = {
+ def ifOff(action: ⇒ Unit): Boolean = {
if (!switch.get) {
action
true
} else false
}
- def whileOnYield[T](action: => T): Option[T] = synchronized {
+ def whileOnYield[T](action: ⇒ T): Option[T] = synchronized {
if (switch.get) Some(action)
else None
}
- def whileOffYield[T](action: => T): Option[T] = synchronized {
+ def whileOffYield[T](action: ⇒ T): Option[T] = synchronized {
if (!switch.get) Some(action)
else None
}
- def whileOn(action: => Unit): Boolean = synchronized {
+ def whileOn(action: ⇒ Unit): Boolean = synchronized {
if (switch.get) {
action
true
} else false
}
- def whileOff(action: => Unit): Boolean = synchronized {
+ def whileOff(action: ⇒ Unit): Boolean = synchronized {
if (switch.get) {
action
true
} else false
}
- def ifElseYield[T](on: => T)(off: => T) = synchronized {
+ def ifElseYield[T](on: ⇒ T)(off: ⇒ T) = synchronized {
if (switch.get) on else off
}
diff --git a/akka-actor/src/main/scala/akka/util/ReflectiveAccess.scala b/akka-actor/src/main/scala/akka/util/ReflectiveAccess.scala
index cb9e8ab0a3..ef0fe59bc9 100644
--- a/akka-actor/src/main/scala/akka/util/ReflectiveAccess.scala
+++ b/akka-actor/src/main/scala/akka/util/ReflectiveAccess.scala
@@ -4,8 +4,8 @@
package akka.util
-import akka.dispatch.{Future, CompletableFuture, MessageInvocation}
-import akka.config.{Config, ModuleNotAvailableException}
+import akka.dispatch.{ Future, CompletableFuture, MessageInvocation }
+import akka.config.{ Config, ModuleNotAvailableException }
import akka.remoteinterface.RemoteSupport
import akka.actor._
@@ -24,13 +24,13 @@ object ReflectiveAccess {
val loader = getClass.getClassLoader
- lazy val isRemotingEnabled: Boolean = RemoteModule.isEnabled
+ lazy val isRemotingEnabled: Boolean = RemoteModule.isEnabled
lazy val isTypedActorEnabled: Boolean = TypedActorModule.isEnabled
- lazy val isClusterEnabled: Boolean = ClusterModule.isEnabled
+ lazy val isClusterEnabled: Boolean = ClusterModule.isEnabled
- def ensureClusterEnabled() { ClusterModule.ensureEnabled() }
- def ensureRemotingEnabled() { RemoteModule.ensureEnabled() }
- def ensureTypedActorEnabled() { TypedActorModule.ensureEnabled() }
+ def ensureClusterEnabled() { ClusterModule.ensureEnabled() }
+ def ensureRemotingEnabled() { RemoteModule.ensureEnabled() }
+ def ensureTypedActorEnabled() { TypedActorModule.ensureEnabled() }
/**
* Reflective access to the Cluster module.
@@ -41,15 +41,15 @@ object ReflectiveAccess {
import java.net.InetAddress
import com.eaio.uuid.UUID
import akka.cluster.NodeAddress
- import Config.{config, TIME_UNIT}
+ import Config.{ config, TIME_UNIT }
- val name = config.getString("akka.cluster.name", "default")
- val zooKeeperServers = config.getString("akka.cluster.zookeeper-server-addresses", "localhost:2181")
- val sessionTimeout = Duration(config.getInt("akka.cluster.session-timeout", 60), TIME_UNIT).toMillis.toInt
- val connectionTimeout = Duration(config.getInt("akka.cluster.connection-timeout", 60), TIME_UNIT).toMillis.toInt
+ val name = config.getString("akka.cluster.name", "default")
+ val zooKeeperServers = config.getString("akka.cluster.zookeeper-server-addresses", "localhost:2181")
+ val sessionTimeout = Duration(config.getInt("akka.cluster.session-timeout", 60), TIME_UNIT).toMillis.toInt
+ val connectionTimeout = Duration(config.getInt("akka.cluster.connection-timeout", 60), TIME_UNIT).toMillis.toInt
val maxTimeToWaitUntilConnected = Duration(config.getInt("akka.cluster.max-time-to-wait-until-connected", 30), TIME_UNIT).toMillis.toInt
- val shouldCompressData = config.getBool("akka.cluster.use-compression", false)
- val nodeAddress = NodeAddress(name, Config.nodename, Config.hostname, Config.remoteServerPort)
+ val shouldCompressData = config.getBool("akka.cluster.use-compression", false)
+ val nodeAddress = NodeAddress(name, Config.nodename, Config.hostname, Config.remoteServerPort)
lazy val isEnabled = clusterInstance.isDefined
@@ -63,22 +63,22 @@ object ReflectiveAccess {
}
lazy val clusterInstance: Option[Cluster] = getObjectFor("akka.cluster.Cluster$") match {
- case Right(value) => Some(value)
- case Left(exception) =>
+ case Right(value) ⇒ Some(value)
+ case Left(exception) ⇒
EventHandler.debug(this, exception.toString)
None
}
lazy val clusterDeployerInstance: Option[ClusterDeployer] = getObjectFor("akka.cluster.ClusterDeployer$") match {
- case Right(value) => Some(value)
- case Left(exception) =>
+ case Right(value) ⇒ Some(value)
+ case Left(exception) ⇒
EventHandler.debug(this, exception.toString)
None
}
lazy val serializerClass: Option[Class[_]] = getClassFor("akka.serialization.Serializer") match {
- case Right(value) => Some(value)
- case Left(exception) =>
+ case Right(value) ⇒ Some(value)
+ case Left(exception) ⇒
EventHandler.debug(this, exception.toString)
None
}
@@ -97,13 +97,9 @@ object ReflectiveAccess {
def start()
def shutdown()
- def store[T <: Actor]
- (address: String, actorClass: Class[T], replicas: Int, serializeMailbox: Boolean)
- (implicit format: Format[T])
+ def store[T <: Actor](address: String, actorClass: Class[T], replicas: Int, serializeMailbox: Boolean)(implicit format: Format[T])
- def store[T <: Actor]
- (address: String, actorRef: ActorRef, replicas: Int, serializeMailbox: Boolean)
- (implicit format: Format[T])
+ def store[T <: Actor](address: String, actorRef: ActorRef, replicas: Int, serializeMailbox: Boolean)(implicit format: Format[T])
def remove(address: String)
def use(address: String): Array[ActorRef]
@@ -150,34 +146,33 @@ object ReflectiveAccess {
def ensureEnabled() = {
if (!isEnabled) {
- val e = new ModuleNotAvailableException("Can't load the remoting module, make sure that akka-remote.jar is on the classpath")
- EventHandler.debug(this, e.toString)
- throw e
+ val e = new ModuleNotAvailableException("Can't load the remoting module, make sure that akka-remote.jar is on the classpath")
+ EventHandler.debug(this, e.toString)
+ throw e
}
}
val remoteSupportClass = getClassFor[RemoteSupport](TRANSPORT) match {
- case Right(value) => Some(value)
- case Left(exception) =>
+ case Right(value) ⇒ Some(value)
+ case Left(exception) ⇒
EventHandler.debug(this, exception.toString)
None
}
- protected[akka] val defaultRemoteSupport: Option[() => RemoteSupport] =
- remoteSupportClass map { remoteClass =>
- () => createInstance[RemoteSupport](
+ protected[akka] val defaultRemoteSupport: Option[() ⇒ RemoteSupport] =
+ remoteSupportClass map { remoteClass ⇒
+ () ⇒ createInstance[RemoteSupport](
remoteClass,
Array[Class[_]](),
- Array[AnyRef]()
- ) match {
- case Right(value) => value
- case Left(exception) =>
- val e = new ModuleNotAvailableException(
- "Can't instantiate [%s] - make sure that akka-remote.jar is on the classpath".format(remoteClass.getName), exception)
- EventHandler.debug(this, e.toString)
- throw e
- }
- }
+ Array[AnyRef]()) match {
+ case Right(value) ⇒ value
+ case Left(exception) ⇒
+ val e = new ModuleNotAvailableException(
+ "Can't instantiate [%s] - make sure that akka-remote.jar is on the classpath".format(remoteClass.getName), exception)
+ EventHandler.debug(this, e.toString)
+ throw e
+ }
+ }
}
/**
@@ -204,8 +199,8 @@ object ReflectiveAccess {
val typedActorObjectInstance: Option[TypedActorObject] =
getObjectFor[TypedActorObject]("akka.actor.TypedActor$") match {
- case Right(value) => Some(value)
- case Left(exception)=>
+ case Right(value) ⇒ Some(value)
+ case Left(exception) ⇒
EventHandler.debug(this, exception.toString)
None
}
@@ -220,11 +215,11 @@ object ReflectiveAccess {
}
val noParams = Array[Class[_]]()
- val noArgs = Array[AnyRef]()
+ val noArgs = Array[AnyRef]()
def createInstance[T](clazz: Class[_],
params: Array[Class[_]],
- args: Array[AnyRef]): Either[Exception,T] = try {
+ args: Array[AnyRef]): Either[Exception, T] = try {
assert(clazz ne null)
assert(params ne null)
assert(args ne null)
@@ -232,10 +227,10 @@ object ReflectiveAccess {
ctor.setAccessible(true)
Right(ctor.newInstance(args: _*).asInstanceOf[T])
} catch {
- case e: java.lang.reflect.InvocationTargetException =>
+ case e: java.lang.reflect.InvocationTargetException ⇒
EventHandler.debug(this, e.getCause.toString)
Left(e)
- case e: Exception =>
+ case e: Exception ⇒
EventHandler.debug(this, e.toString)
Left(e)
}
@@ -243,33 +238,33 @@ object ReflectiveAccess {
def createInstance[T](fqn: String,
params: Array[Class[_]],
args: Array[AnyRef],
- classloader: ClassLoader = loader): Either[Exception,T] = try {
+ classloader: ClassLoader = loader): Either[Exception, T] = try {
assert(params ne null)
assert(args ne null)
getClassFor(fqn) match {
- case Right(value) =>
+ case Right(value) ⇒
val ctor = value.getDeclaredConstructor(params: _*)
ctor.setAccessible(true)
Right(ctor.newInstance(args: _*).asInstanceOf[T])
- case Left(exception) => Left(exception) //We could just cast this to Either[Exception, T] but it's ugly
+ case Left(exception) ⇒ Left(exception) //We could just cast this to Either[Exception, T] but it's ugly
}
} catch {
- case e: Exception =>
+ case e: Exception ⇒
Left(e)
}
//Obtains a reference to fqn.MODULE$
- def getObjectFor[T](fqn: String, classloader: ClassLoader = loader): Either[Exception,T] = try {
+ def getObjectFor[T](fqn: String, classloader: ClassLoader = loader): Either[Exception, T] = try {
getClassFor(fqn) match {
- case Right(value) =>
+ case Right(value) ⇒
val instance = value.getDeclaredField("MODULE$")
instance.setAccessible(true)
val obj = instance.get(null)
if (obj eq null) Left(new NullPointerException) else Right(obj.asInstanceOf[T])
- case Left(exception) => Left(exception) //We could just cast this to Either[Exception, T] but it's ugly
+ case Left(exception) ⇒ Left(exception) //We could just cast this to Either[Exception, T] but it's ugly
}
} catch {
- case e: Exception =>
+ case e: Exception ⇒
Left(e)
}
@@ -280,7 +275,7 @@ object ReflectiveAccess {
val first = try {
Right(classloader.loadClass(fqn).asInstanceOf[Class[T]])
} catch {
- case c: ClassNotFoundException => Left(c)
+ case c: ClassNotFoundException ⇒ Left(c)
}
if (first.isRight) first
@@ -289,15 +284,15 @@ object ReflectiveAccess {
val second = try {
Right(Thread.currentThread.getContextClassLoader.loadClass(fqn).asInstanceOf[Class[T]])
} catch {
- case c: ClassNotFoundException => Left(c)
+ case c: ClassNotFoundException ⇒ Left(c)
}
if (second.isRight) second
else {
val third = try {
- if (classloader ne loader) Right(loader.loadClass(fqn).asInstanceOf[Class[T]]) else Left(null) //Horrid
+ if (classloader ne loader) Right(loader.loadClass(fqn).asInstanceOf[Class[T]]) else Left(null) //Horrid
} catch {
- case c: ClassNotFoundException => Left(c)
+ case c: ClassNotFoundException ⇒ Left(c)
}
if (third.isRight) third
@@ -305,12 +300,12 @@ object ReflectiveAccess {
try {
Right(Class.forName(fqn).asInstanceOf[Class[T]]) // Last option is Class.forName
} catch {
- case c: ClassNotFoundException => Left(c)
+ case c: ClassNotFoundException ⇒ Left(c)
}
}
}
}
} catch {
- case e: Exception => Left(e)
+ case e: Exception ⇒ Left(e)
}
}
diff --git a/akka-actor/src/main/scala/akka/util/package.scala b/akka-actor/src/main/scala/akka/util/package.scala
index 662c0d7393..26a24929c9 100644
--- a/akka-actor/src/main/scala/akka/util/package.scala
+++ b/akka-actor/src/main/scala/akka/util/package.scala
@@ -11,17 +11,17 @@ package object duration {
implicit def longToDurationLong(n: Long) = new DurationLong(n)
implicit def doubleToDurationDouble(d: Double) = new DurationDouble(d)
- implicit def pairIntToDuration(p : (Int, TimeUnit)) = Duration(p._1, p._2)
- implicit def pairLongToDuration(p : (Long, TimeUnit)) = Duration(p._1, p._2)
- implicit def durationToPair(d : Duration) = (d.length, d.unit)
+ implicit def pairIntToDuration(p: (Int, TimeUnit)) = Duration(p._1, p._2)
+ implicit def pairLongToDuration(p: (Long, TimeUnit)) = Duration(p._1, p._2)
+ implicit def durationToPair(d: Duration) = (d.length, d.unit)
- implicit def intMult(i : Int) = new {
- def *(d : Duration) = d * i
+ implicit def intMult(i: Int) = new {
+ def *(d: Duration) = d * i
}
- implicit def longMult(l : Long) = new {
- def *(d : Duration) = d * l
+ implicit def longMult(l: Long) = new {
+ def *(d: Duration) = d * l
}
- implicit def doubleMult(f : Double) = new {
- def *(d : Duration) = d * f
+ implicit def doubleMult(f: Double) = new {
+ def *(d: Duration) = d * f
}
}
diff --git a/akka-cluster/src/main/scala/akka/cluster/Cluster.scala b/akka-cluster/src/main/scala/akka/cluster/Cluster.scala
index 2772652fb5..58faa0fdd5 100644
--- a/akka-cluster/src/main/scala/akka/cluster/Cluster.scala
+++ b/akka-cluster/src/main/scala/akka/cluster/Cluster.scala
@@ -6,18 +6,18 @@ package akka.cluster
import org.apache.zookeeper._
import org.apache.zookeeper.Watcher.Event._
import org.apache.zookeeper.data.Stat
-import org.apache.zookeeper.recipes.lock.{WriteLock, LockListener}
+import org.apache.zookeeper.recipes.lock.{ WriteLock, LockListener }
import org.I0Itec.zkclient._
import org.I0Itec.zkclient.serialize._
import org.I0Itec.zkclient.exception._
-import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference, AtomicInteger}
-import java.util.concurrent.{ConcurrentSkipListSet, CopyOnWriteArrayList, Callable, ConcurrentHashMap}
+import java.util.concurrent.atomic.{ AtomicBoolean, AtomicReference, AtomicInteger }
+import java.util.concurrent.{ ConcurrentSkipListSet, CopyOnWriteArrayList, Callable, ConcurrentHashMap }
import java.net.InetSocketAddress
import javax.management.StandardMBean
-import scala.collection.immutable.{HashMap, HashSet}
+import scala.collection.immutable.{ HashMap, HashSet }
import scala.collection.mutable.ConcurrentMap
import scala.collection.JavaConversions._
@@ -29,10 +29,10 @@ import Helpers._
import akka.actor._
import akka.actor.Actor._
import akka.event.EventHandler
-import akka.dispatch.{Dispatchers, Future}
+import akka.dispatch.{ Dispatchers, Future }
import akka.remoteinterface._
import akka.config.Config._
-import akka.serialization.{Format, Serializers}
+import akka.serialization.{ Format, Serializers }
import akka.serialization.Compression.LZF
import akka.AkkaException
@@ -41,7 +41,7 @@ import akka.cluster.zookeeper._
import com.eaio.uuid.UUID
import com.google.protobuf.ByteString
-import java.util.{List => JList}
+import java.util.{ List ⇒ JList }
// FIXME add watch for each node that when the entry for the node is removed then the node shuts itself down
// FIXME Provisioning data in ZK (file names etc) and files in S3 and on disk
@@ -131,13 +131,13 @@ object Cluster {
trait ChangeListener {
def notify(event: ChangeNotification, client: ClusterNode) {
event match {
- case NodeConnected(name) => nodeConnected(name, client)
- case NodeDisconnected(name) => nodeDisconnected(name, client)
- case NewLeader(name: String) => newLeader(name, client)
- case NewSession => thisNodeNewSession(client)
- case ThisNode.Connected => thisNodeConnected(client)
- case ThisNode.Disconnected => thisNodeDisconnected(client)
- case ThisNode.Expired => thisNodeExpired(client)
+ case NodeConnected(name) ⇒ nodeConnected(name, client)
+ case NodeDisconnected(name) ⇒ nodeDisconnected(name, client)
+ case NewLeader(name: String) ⇒ newLeader(name, client)
+ case NewSession ⇒ thisNodeNewSession(client)
+ case ThisNode.Connected ⇒ thisNodeConnected(client)
+ case ThisNode.Disconnected ⇒ thisNodeDisconnected(client)
+ case ThisNode.Expired ⇒ thisNodeExpired(client)
}
}
@@ -190,8 +190,8 @@ object Cluster {
private val _nodes = new AtomicReference[Nodes](new Nodes)
private val _clusterNames = new ConcurrentSkipListSet[String]
- private[cluster] def updateNodes(f: Nodes => Nodes) {
- while (Some(_nodes.get).map(node => _nodes.compareAndSet(node, f(node)) == false).get) {}
+ private[cluster] def updateNodes(f: Nodes ⇒ Nodes) {
+ while (Some(_nodes.get).map(node ⇒ _nodes.compareAndSet(node, f(node)) == false).get) {}
}
/**
@@ -232,9 +232,9 @@ object Cluster {
* Creates a new cluster node; ClusterNode.
*/
def apply(
- nodeAddress: NodeAddress,
- zkServerAddresses: String = Cluster.zooKeeperServers,
- serializer: ZkSerializer = Cluster.defaultSerializer): ClusterNode =
+ nodeAddress: NodeAddress,
+ zkServerAddresses: String = Cluster.zooKeeperServers,
+ serializer: ZkSerializer = Cluster.defaultSerializer): ClusterNode =
newNode(nodeAddress, zkServerAddresses, serializer)
/**
@@ -259,9 +259,9 @@ object Cluster {
* Creates a new cluster node; ClusterNode.
*/
def newNode(
- nodeAddress: NodeAddress,
- zkServerAddresses: String,
- serializer: ZkSerializer): ClusterNode = {
+ nodeAddress: NodeAddress,
+ zkServerAddresses: String,
+ serializer: ZkSerializer): ClusterNode = {
if (nodeAddress eq null) throw new IllegalArgumentException("NodeAddress can't be null")
@@ -309,7 +309,7 @@ object Cluster {
_zkServer.set(Some(zkServer))
zkServer
} catch {
- case e: Throwable =>
+ case e: Throwable ⇒
EventHandler.error(e, this, "Could not start local ZooKeeper cluster")
throw e
}
@@ -325,11 +325,10 @@ object Cluster {
EventHandler.info(this, "Resetting all clusters connected to in this JVM")
if (!clusters.isEmpty) {
- nodes foreach {
- tp =>
- val (_, node) = tp
- node.disconnect()
- node.remoteService.shutdown()
+ nodes foreach { tp ⇒
+ val (_, node) = tp
+ node.disconnect()
+ node.remoteService.shutdown()
}
implicit val zkClient = newZkClient
clusters foreach (resetNodesInCluster(_))
@@ -371,9 +370,8 @@ object Cluster {
if (uuid == "") throw new ClusterException("UUID is an empty string")
try {
new UUID(uuid)
- }
- catch {
- case e: StringIndexOutOfBoundsException =>
+ } catch {
+ case e: StringIndexOutOfBoundsException ⇒
val error = new ClusterException("UUID not valid [" + uuid + "]")
EventHandler.error(error, this, "")
throw error
@@ -394,11 +392,11 @@ object Cluster {
*
* @author Jonas Bonér
*/
-class ClusterNode private[akka](
- val nodeAddress: NodeAddress,
- val zkServerAddresses: String,
- val serializer: ZkSerializer) extends ErrorHandler {
- self =>
+class ClusterNode private[akka] (
+ val nodeAddress: NodeAddress,
+ val zkServerAddresses: String,
+ val serializer: ZkSerializer) extends ErrorHandler {
+ self ⇒
if (nodeAddress eq null) throw new IllegalArgumentException("'nodeAddress' can not be 'null'")
@@ -414,9 +412,9 @@ class ClusterNode private[akka](
val remoteClientLifeCycleListener = actorOf(new Actor {
def receive = {
- case RemoteClientError(cause, client, address) => client.shutdownClientModule()
- case RemoteClientDisconnected(client, address) => client.shutdownClientModule()
- case _ => //ignore other
+ case RemoteClientError(cause, client, address) ⇒ client.shutdownClientModule()
+ case RemoteClientDisconnected(client, address) ⇒ client.shutdownClientModule()
+ case _ ⇒ //ignore other
}
}, "akka.cluster.remoteClientLifeCycleListener").start()
@@ -530,7 +528,7 @@ class ClusterNode private[akka](
locallyCheckedOutActors.clear()
replicaConnections.toList.foreach({
- case (_, (address, _)) =>
+ case (_, (address, _)) ⇒
Actor.remote.shutdownClientConnection(address) // shut down client connections
})
@@ -602,36 +600,28 @@ class ClusterNode private[akka](
* with the actor passed in as argument. You can use this to save off snapshots of the actor to a highly
* available durable store.
*/
- def store[T <: Actor]
- (actorClass: Class[T], address: String)
- (implicit format: Format[T]): ClusterNode = store(Actor.actorOf(actorClass, address).start, 0, false)
+ def store[T <: Actor](actorClass: Class[T], address: String)(implicit format: Format[T]): ClusterNode = store(Actor.actorOf(actorClass, address).start, 0, false)
/**
* Clusters an actor of a specific type. If the actor is already clustered then the clustered version will be updated
* with the actor passed in as argument. You can use this to save off snapshots of the actor to a highly
* available durable store.
*/
- def store[T <: Actor]
- (actorClass: Class[T], address: String, replicationFactor: Int)
- (implicit format: Format[T]): ClusterNode = store(Actor.actorOf(actorClass, address).start, replicationFactor, false)
+ def store[T <: Actor](actorClass: Class[T], address: String, replicationFactor: Int)(implicit format: Format[T]): ClusterNode = store(Actor.actorOf(actorClass, address).start, replicationFactor, false)
/**
* Clusters an actor of a specific type. If the actor is already clustered then the clustered version will be updated
* with the actor passed in as argument. You can use this to save off snapshots of the actor to a highly
* available durable store.
*/
- def store[T <: Actor]
- (actorClass: Class[T], address: String, serializeMailbox: Boolean)
- (implicit format: Format[T]): ClusterNode = store(Actor.actorOf(actorClass, address).start, 0, serializeMailbox)
+ def store[T <: Actor](actorClass: Class[T], address: String, serializeMailbox: Boolean)(implicit format: Format[T]): ClusterNode = store(Actor.actorOf(actorClass, address).start, 0, serializeMailbox)
/**
* Clusters an actor of a specific type. If the actor is already clustered then the clustered version will be updated
* with the actor passed in as argument. You can use this to save off snapshots of the actor to a highly
* available durable store.
*/
- def store[T <: Actor]
- (actorClass: Class[T], address: String, replicationFactor: Int, serializeMailbox: Boolean)
- (implicit format: Format[T]): ClusterNode =
+ def store[T <: Actor](actorClass: Class[T], address: String, replicationFactor: Int, serializeMailbox: Boolean)(implicit format: Format[T]): ClusterNode =
store(Actor.actorOf(actorClass, address).start, replicationFactor, serializeMailbox)
/**
@@ -639,36 +629,28 @@ class ClusterNode private[akka](
* with the actor passed in as argument. You can use this to save off snapshots of the actor to a highly
* available durable store.
*/
- def store[T <: Actor]
- (actorRef: ActorRef)
- (implicit format: Format[T]): ClusterNode = store(actorRef, 0, false)
+ def store[T <: Actor](actorRef: ActorRef)(implicit format: Format[T]): ClusterNode = store(actorRef, 0, false)
/**
* Clusters an actor with UUID. If the actor is already clustered then the clustered version will be updated
* with the actor passed in as argument. You can use this to save off snapshots of the actor to a highly
* available durable store.
*/
- def store[T <: Actor]
- (actorRef: ActorRef, replicationFactor: Int)
- (implicit format: Format[T]): ClusterNode = store(actorRef, replicationFactor, false)
+ def store[T <: Actor](actorRef: ActorRef, replicationFactor: Int)(implicit format: Format[T]): ClusterNode = store(actorRef, replicationFactor, false)
/**
* Clusters an actor with UUID. If the actor is already clustered then the clustered version will be updated
* with the actor passed in as argument. You can use this to save off snapshots of the actor to a highly
* available durable store.
*/
- def store[T <: Actor]
- (actorRef: ActorRef, serializeMailbox: Boolean)
- (implicit format: Format[T]): ClusterNode = store(actorRef, 0, serializeMailbox)
+ def store[T <: Actor](actorRef: ActorRef, serializeMailbox: Boolean)(implicit format: Format[T]): ClusterNode = store(actorRef, 0, serializeMailbox)
/**
* Clusters an actor with UUID. If the actor is already clustered then the clustered version will be updated
* with the actor passed in as argument. You can use this to save off snapshots of the actor to a highly
* available durable store.
*/
- def store[T <: Actor]
- (actorRef: ActorRef, replicationFactor: Int, serializeMailbox: Boolean)
- (implicit format: Format[T]): ClusterNode = if (isConnected.isOn) {
+ def store[T <: Actor](actorRef: ActorRef, replicationFactor: Int, serializeMailbox: Boolean)(implicit format: Format[T]): ClusterNode = if (isConnected.isOn) {
import akka.serialization.ActorSerialization._
@@ -691,26 +673,26 @@ class ClusterNode private[akka](
try {
Left(zkClient.connection.create(actorRegistryPath, actorBytes, CreateMode.PERSISTENT))
} catch {
- case e: KeeperException.NodeExistsException => Right(e)
+ case e: KeeperException.NodeExistsException ⇒ Right(e)
}
}
}) match {
- case Left(path) => path
- case Right(exception) => actorRegistryPath
+ case Left(path) ⇒ path
+ case Right(exception) ⇒ actorRegistryPath
}
// create UUID -> Format registry
try {
zkClient.createPersistent(actorRegistryFormatPathFor(uuid), format)
} catch {
- case e: ZkNodeExistsException => zkClient.writeData(actorRegistryFormatPathFor(uuid), format)
+ case e: ZkNodeExistsException ⇒ zkClient.writeData(actorRegistryFormatPathFor(uuid), format)
}
// create UUID -> ADDRESS registry
try {
zkClient.createPersistent(actorRegistryActorAddressPathFor(uuid), actorRef.address)
} catch {
- case e: ZkNodeExistsException => zkClient.writeData(actorRegistryActorAddressPathFor(uuid), actorRef.address)
+ case e: ZkNodeExistsException ⇒ zkClient.writeData(actorRegistryActorAddressPathFor(uuid), actorRef.address)
}
// create UUID -> Address registry
@@ -728,9 +710,8 @@ class ClusterNode private[akka](
.setMessageType(USE)
.setActorUuid(uuidToUuidProtocol(uuid))
.build
- replicaConnectionsForReplicationFactor(replicationFactor) foreach {
- connection =>
- connection ! command
+ replicaConnectionsForReplicationFactor(replicationFactor) foreach { connection ⇒
+ connection ! command
}
this
@@ -757,7 +738,7 @@ class ClusterNode private[akka](
isConnected ifOn {
EventHandler.debug(this,
"Removing actor(s) with ADDRESS [%s] from cluster".format(address))
- uuidsForActorAddress(address) foreach (uuid => remove(uuid))
+ uuidsForActorAddress(address) foreach (uuid ⇒ remove(uuid))
}
this
}
@@ -766,9 +747,8 @@ class ClusterNode private[akka](
* Is the actor with uuid clustered or not?
*/
def isClustered(actorAddress: String): Boolean = if (isConnected.isOn) {
- actorUuidsForActorAddress(actorAddress) map {
- uuid =>
- zkClient.exists(actorRegistryPathFor(uuid))
+ actorUuidsForActorAddress(actorAddress) map { uuid ⇒
+ zkClient.exists(actorRegistryPathFor(uuid))
} exists (_ == true)
} else false
@@ -781,9 +761,8 @@ class ClusterNode private[akka](
* Is the actor with uuid in use or not?
*/
def isInUseOnNode(actorAddress: String, node: NodeAddress): Boolean = if (isConnected.isOn) {
- actorUuidsForActorAddress(actorAddress) map {
- uuid =>
- zkClient.exists(actorLocationsPathFor(uuid, node))
+ actorUuidsForActorAddress(actorAddress) map { uuid ⇒
+ zkClient.exists(actorLocationsPathFor(uuid, node))
} exists (_ == true)
} else false
@@ -796,39 +775,38 @@ class ClusterNode private[akka](
import akka.serialization.ActorSerialization._
- actorUuidsForActorAddress(actorAddress) map {
- uuid =>
- EventHandler.debug(this,
- "Checking out actor with UUID [%s] to be used on node [%s]".format(uuid, nodeAddress.nodeName))
+ actorUuidsForActorAddress(actorAddress) map { uuid ⇒
+ EventHandler.debug(this,
+ "Checking out actor with UUID [%s] to be used on node [%s]".format(uuid, nodeAddress.nodeName))
- ignore[ZkNodeExistsException](zkClient.createPersistent(actorAtNodePathFor(nodeAddress.nodeName, uuid), true))
- ignore[ZkNodeExistsException](zkClient.createEphemeral(actorLocationsPathFor(uuid, nodeAddress)))
+ ignore[ZkNodeExistsException](zkClient.createPersistent(actorAtNodePathFor(nodeAddress.nodeName, uuid), true))
+ ignore[ZkNodeExistsException](zkClient.createEphemeral(actorLocationsPathFor(uuid, nodeAddress)))
- // set home address
- ignore[ZkNodeExistsException](zkClient.createPersistent(actorRegistryNodePathFor(uuid)))
- ignore[ZkNodeExistsException](zkClient.createEphemeral(actorRegistryNodePathFor(uuid, remoteServerAddress)))
+ // set home address
+ ignore[ZkNodeExistsException](zkClient.createPersistent(actorRegistryNodePathFor(uuid)))
+ ignore[ZkNodeExistsException](zkClient.createEphemeral(actorRegistryNodePathFor(uuid, remoteServerAddress)))
- val actorPath = actorRegistryPathFor(uuid)
- zkClient.retryUntilConnected(new Callable[Either[Array[Byte], Exception]]() {
- def call: Either[Array[Byte], Exception] = {
- try {
- Left(if (shouldCompressData) LZF.uncompress(zkClient.connection.readData(actorPath, new Stat, false))
- else zkClient.connection.readData(actorPath, new Stat, false))
- } catch {
- case e: KeeperException.NodeExistsException => Right(e)
- }
+ val actorPath = actorRegistryPathFor(uuid)
+ zkClient.retryUntilConnected(new Callable[Either[Array[Byte], Exception]]() {
+ def call: Either[Array[Byte], Exception] = {
+ try {
+ Left(if (shouldCompressData) LZF.uncompress(zkClient.connection.readData(actorPath, new Stat, false))
+ else zkClient.connection.readData(actorPath, new Stat, false))
+ } catch {
+ case e: KeeperException.NodeExistsException ⇒ Right(e)
}
- }) match {
- case Left(bytes) =>
- locallyCheckedOutActors += (uuid -> bytes)
- // FIXME switch to ReplicatedActorRef here
- // val actor = new ReplicatedActorRef(fromBinary[T](bytes, remoteServerAddress)(format))
- val actor = fromBinary[T](bytes, remoteServerAddress)(format)
- remoteService.register(UUID_PREFIX + uuid, actor) // clustered refs are always registered and looked up by UUID
- actor.start()
- actor.asInstanceOf[LocalActorRef]
- case Right(exception) => throw exception
}
+ }) match {
+ case Left(bytes) ⇒
+ locallyCheckedOutActors += (uuid -> bytes)
+ // FIXME switch to ReplicatedActorRef here
+ // val actor = new ReplicatedActorRef(fromBinary[T](bytes, remoteServerAddress)(format))
+ val actor = fromBinary[T](bytes, remoteServerAddress)(format)
+ remoteService.register(UUID_PREFIX + uuid, actor) // clustered refs are always registered and looked up by UUID
+ actor.start()
+ actor.asInstanceOf[LocalActorRef]
+ case Right(exception) ⇒ throw exception
+ }
}
} else Array.empty[LocalActorRef]
@@ -843,12 +821,11 @@ class ClusterNode private[akka](
.setMessageType(USE)
.setActorUuid(uuidToUuidProtocol(uuid))
.build
- membershipNodes foreach {
- node =>
- replicaConnections.get(node) foreach {
- case (_, connection) =>
- connection ! command
- }
+ membershipNodes foreach { node ⇒
+ replicaConnections.get(node) foreach {
+ case (_, connection) ⇒
+ connection ! command
+ }
}
}
}
@@ -859,7 +836,7 @@ class ClusterNode private[akka](
def useActorOnNode(node: String, uuid: UUID) {
isConnected ifOn {
replicaConnections.get(node) foreach {
- case (_, connection) =>
+ case (_, connection) ⇒
connection ! RemoteDaemonMessageProtocol.newBuilder
.setMessageType(USE)
.setActorUuid(uuidToUuidProtocol(uuid))
@@ -873,15 +850,14 @@ class ClusterNode private[akka](
*/
def release(actorAddress: String) {
isConnected ifOn {
- actorUuidsForActorAddress(actorAddress) foreach {
- uuid =>
- EventHandler.debug(this,
- "Releasing actor with UUID [%s] after usage".format(uuid))
- locallyCheckedOutActors.remove(uuid)
- ignore[ZkNoNodeException](zkClient.deleteRecursive(actorAtNodePathFor(nodeAddress.nodeName, uuid)))
- ignore[ZkNoNodeException](zkClient.delete(actorAtNodePathFor(nodeAddress.nodeName, uuid)))
- ignore[ZkNoNodeException](zkClient.delete(actorLocationsPathFor(uuid, nodeAddress)))
- ignore[ZkNoNodeException](zkClient.delete(actorRegistryNodePathFor(uuid, remoteServerAddress)))
+ actorUuidsForActorAddress(actorAddress) foreach { uuid ⇒
+ EventHandler.debug(this,
+ "Releasing actor with UUID [%s] after usage".format(uuid))
+ locallyCheckedOutActors.remove(uuid)
+ ignore[ZkNoNodeException](zkClient.deleteRecursive(actorAtNodePathFor(nodeAddress.nodeName, uuid)))
+ ignore[ZkNoNodeException](zkClient.delete(actorAtNodePathFor(nodeAddress.nodeName, uuid)))
+ ignore[ZkNoNodeException](zkClient.delete(actorLocationsPathFor(uuid, nodeAddress)))
+ ignore[ZkNoNodeException](zkClient.delete(actorRegistryNodePathFor(uuid, remoteServerAddress)))
}
}
}
@@ -897,12 +873,11 @@ class ClusterNode private[akka](
.setMessageType(RELEASE)
.setActorUuid(uuidToUuidProtocol(uuid))
.build
- nodesForActorsInUseWithUuid(uuid) foreach {
- node =>
- replicaConnections.get(node) foreach {
- case (_, connection) =>
- connection ! command
- }
+ nodesForActorsInUseWithUuid(uuid) foreach { node ⇒
+ replicaConnections.get(node) foreach {
+ case (_, connection) ⇒
+ connection ! command
+ }
}
}
}
@@ -920,14 +895,13 @@ class ClusterNode private[akka](
def registerClusterActorRefForAddress(actorRef: ClusterActorRef, addresses: Array[(UUID, InetSocketAddress)]) {
addresses foreach {
- case (_, address) => clusterActorRefs.put(address, actorRef)
+ case (_, address) ⇒ clusterActorRefs.put(address, actorRef)
}
}
// FIXME remove?
def refByUuid(uuid: UUID): ActorRef = {
- val actor = Router newRouter (
- router, addresses,
+ val actor = Router newRouter (router, addresses,
uuidToString(uuid),
Actor.TIMEOUT, actorType)
registerClusterActorRefForAddress(actor, addresses)
@@ -937,8 +911,7 @@ class ClusterNode private[akka](
def refByAddress(actorAddress: String): ActorRef = {
//FIXME: unused uuids
val uuids = uuidsForActorAddress(actorAddress)
- val actor = Router newRouter (
- router, addresses,
+ val actor = Router newRouter (router, addresses,
actorAddress,
Actor.TIMEOUT, actorType)
registerClusterActorRefForAddress(actor, addresses)
@@ -959,7 +932,7 @@ class ClusterNode private[akka](
* Migrate the actor from node 'from' to node 'to'.
*/
def migrate(
- from: NodeAddress, to: NodeAddress, actorAddress: String) {
+ from: NodeAddress, to: NodeAddress, actorAddress: String) {
isConnected ifOn {
if (from eq null) throw new IllegalArgumentException("NodeAddress 'from' can not be 'null'")
if (to eq null) throw new IllegalArgumentException("NodeAddress 'to' can not be 'null'")
@@ -999,9 +972,8 @@ class ClusterNode private[akka](
def actorAddressForUuid(uuid: UUID): String = if (isConnected.isOn) {
try {
zkClient.readData(actorRegistryActorAddressPathFor(uuid)).asInstanceOf[String]
- }
- catch {
- case e: ZkNoNodeException => ""
+ } catch {
+ case e: ZkNoNodeException ⇒ ""
}
} else ""
@@ -1016,9 +988,8 @@ class ClusterNode private[akka](
def uuidsForActorAddress(actorAddress: String): Array[UUID] = if (isConnected.isOn) {
try {
zkClient.getChildren(actorAddressToUuidsPathFor(actorAddress)).toList.map(new UUID(_)).toArray.asInstanceOf[Array[UUID]]
- }
- catch {
- case e: ZkNoNodeException => Array[UUID]()
+ } catch {
+ case e: ZkNoNodeException ⇒ Array[UUID]()
}
} else Array.empty[UUID]
@@ -1028,9 +999,8 @@ class ClusterNode private[akka](
def nodesForActorsInUseWithUuid(uuid: UUID): Array[String] = if (isConnected.isOn) {
try {
zkClient.getChildren(actorLocationsPathFor(uuid)).toList.toArray.asInstanceOf[Array[String]]
- }
- catch {
- case e: ZkNoNodeException => Array[String]()
+ } catch {
+ case e: ZkNoNodeException ⇒ Array[String]()
}
} else Array.empty[String]
@@ -1039,14 +1009,13 @@ class ClusterNode private[akka](
*/
def nodesForActorsInUseWithAddress(address: String): Array[String] = if (isConnected.isOn) {
flatten {
- actorUuidsForActorAddress(address) map {
- uuid =>
- try {
- val list = zkClient.getChildren(actorLocationsPathFor(uuid))
- list.toList.toArray.asInstanceOf[Array[String]]
- } catch {
- case e: ZkNoNodeException => Array[String]()
- }
+ actorUuidsForActorAddress(address) map { uuid ⇒
+ try {
+ val list = zkClient.getChildren(actorLocationsPathFor(uuid))
+ list.toList.toArray.asInstanceOf[Array[String]]
+ } catch {
+ case e: ZkNoNodeException ⇒ Array[String]()
+ }
}
}
} else Array.empty[String]
@@ -1057,9 +1026,8 @@ class ClusterNode private[akka](
def uuidsForActorsInUseOnNode(nodeName: String): Array[UUID] = if (isConnected.isOn) {
try {
zkClient.getChildren(actorsAtNodePathFor(nodeName)).toList.map(new UUID(_)).toArray.asInstanceOf[Array[UUID]]
- }
- catch {
- case e: ZkNoNodeException => Array[UUID]()
+ } catch {
+ case e: ZkNoNodeException ⇒ Array[UUID]()
}
} else Array.empty[UUID]
@@ -1070,9 +1038,8 @@ class ClusterNode private[akka](
val uuids =
try {
zkClient.getChildren(actorsAtNodePathFor(nodeName)).toList.map(new UUID(_)).toArray.asInstanceOf[Array[UUID]]
- }
- catch {
- case e: ZkNoNodeException => Array[UUID]()
+ } catch {
+ case e: ZkNoNodeException ⇒ Array[UUID]()
}
actorAddressForUuids(uuids)
} else Array.empty[String]
@@ -1082,9 +1049,8 @@ class ClusterNode private[akka](
*/
def formatForActor[T <: Actor](actorAddress: String): Format[T] = {
- val formats = actorUuidsForActorAddress(actorAddress) map {
- uuid =>
- zkClient.readData(actorRegistryFormatPathFor(uuid), new Stat).asInstanceOf[Format[T]]
+ val formats = actorUuidsForActorAddress(actorAddress) map { uuid ⇒
+ zkClient.readData(actorRegistryFormatPathFor(uuid), new Stat).asInstanceOf[Format[T]]
}
val format = formats.head
@@ -1100,8 +1066,8 @@ class ClusterNode private[akka](
def addressesForActor(actorAddress: String): Array[(UUID, InetSocketAddress)] = {
try {
for {
- uuid <- actorUuidsForActorAddress(actorAddress)
- address <- zkClient.getChildren(actorRegistryNodePathFor(uuid)).toList
+ uuid ← actorUuidsForActorAddress(actorAddress)
+ address ← zkClient.getChildren(actorRegistryNodePathFor(uuid)).toList
} yield {
val tokenizer = new java.util.StringTokenizer(address, ":")
val hostname = tokenizer.nextToken // hostname
@@ -1109,7 +1075,7 @@ class ClusterNode private[akka](
(uuid, new InetSocketAddress(hostname, port))
}
} catch {
- case e: ZkNoNodeException => Array[(UUID, InetSocketAddress)]()
+ case e: ZkNoNodeException ⇒ Array[(UUID, InetSocketAddress)]()
}
}
@@ -1180,19 +1146,19 @@ class ClusterNode private[akka](
try {
Left(zkClient.connection.create(configurationPathFor(key), compressedBytes, CreateMode.PERSISTENT))
} catch {
- case e: KeeperException.NodeExistsException =>
+ case e: KeeperException.NodeExistsException ⇒
try {
Left(zkClient.connection.writeData(configurationPathFor(key), compressedBytes))
} catch {
- case e: Exception => Right(e)
+ case e: Exception ⇒ Right(e)
}
}
}
}) match {
- case Left(_) => {
+ case Left(_) ⇒ {
/* do nothing */
}
- case Right(exception) => throw exception
+ case Right(exception) ⇒ throw exception
}
}
@@ -1202,7 +1168,7 @@ class ClusterNode private[akka](
def getConfigElement(key: String): Array[Byte] = try {
zkClient.connection.readData(configurationPathFor(key), new Stat, true)
} catch {
- case e: KeeperException.NoNodeException => null
+ case e: KeeperException.NoNodeException ⇒ null
}
def removeConfigElement(key: String) {
@@ -1297,7 +1263,7 @@ class ClusterNode private[akka](
val numberOfReplicas = replicaConnections.size
val replicaConnectionsAsArray = replicaConnections.toList map {
- case (node, (address, actorRef)) => actorRef
+ case (node, (address, actorRef)) ⇒ actorRef
} // the ActorRefs
if (numberOfReplicas < replicationFactor) {
@@ -1319,13 +1285,12 @@ class ClusterNode private[akka](
* Connect to all available replicas unless already connected).
*/
private def connectToAllReplicas() {
- membershipNodes foreach {
- node =>
- if (!replicaConnections.contains(node)) {
- val address = addressForNode(node)
- val clusterDaemon = Actor.remote.actorFor(RemoteClusterDaemon.ADDRESS, address.getHostName, address.getPort)
- replicaConnections.put(node, (address, clusterDaemon))
- }
+ membershipNodes foreach { node ⇒
+ if (!replicaConnections.contains(node)) {
+ val address = addressForNode(node)
+ val clusterDaemon = Actor.remote.actorFor(RemoteClusterDaemon.ADDRESS, address.getHostName, address.getPort)
+ replicaConnections.put(node, (address, clusterDaemon))
+ }
}
}
@@ -1336,7 +1301,7 @@ class ClusterNode private[akka](
"Joining cluster as membership node [%s] on [%s]".format(nodeAddress, membershipNodePath))
zkClient.createEphemeral(membershipNodePath, nodeAddress.toString)
} catch {
- case e: ZkNodeExistsException =>
+ case e: ZkNodeExistsException ⇒
val error = new ClusterException("Can't join the cluster. The node name [" + nodeAddress.nodeName + "] is already in by another node")
EventHandler.error(error, this, "")
throw error
@@ -1357,62 +1322,58 @@ class ClusterNode private[akka](
}
private[cluster] def migrateFromFailedNodes[T <: Actor](currentSetOfClusterNodes: List[String]) = {
- findFailedNodes(currentSetOfClusterNodes).foreach {
- failedNodeName =>
+ findFailedNodes(currentSetOfClusterNodes).foreach { failedNodeName ⇒
- val allNodes = locallyCachedMembershipNodes.toList
- val myIndex = allNodes.indexWhere(_.endsWith(nodeAddress.nodeName))
- val failedNodeIndex = allNodes.indexWhere(_ == failedNodeName)
+ val allNodes = locallyCachedMembershipNodes.toList
+ val myIndex = allNodes.indexWhere(_.endsWith(nodeAddress.nodeName))
+ val failedNodeIndex = allNodes.indexWhere(_ == failedNodeName)
- // Migrate to the successor of the failed node (using a sorted circular list of the node names)
- if ((failedNodeIndex == 0 && myIndex == locallyCachedMembershipNodes.size - 1) || // No leftmost successor exists, check the tail
- (failedNodeIndex == myIndex + 1)) {
- // Am I the leftmost successor?
+ // Migrate to the successor of the failed node (using a sorted circular list of the node names)
+ if ((failedNodeIndex == 0 && myIndex == locallyCachedMembershipNodes.size - 1) || // No leftmost successor exists, check the tail
+ (failedNodeIndex == myIndex + 1)) {
+ // Am I the leftmost successor?
- // Yes I am the node to migrate the actor to (can only be one in the cluster)
- val actorUuidsForFailedNode = zkClient.getChildren(actorsAtNodePathFor(failedNodeName))
+ // Yes I am the node to migrate the actor to (can only be one in the cluster)
+ val actorUuidsForFailedNode = zkClient.getChildren(actorsAtNodePathFor(failedNodeName))
+ EventHandler.debug(this,
+ "Migrating actors from failed node [%s] to node [%s]: Actor UUIDs [%s]"
+ .format(failedNodeName, nodeAddress.nodeName, actorUuidsForFailedNode))
+
+ actorUuidsForFailedNode.foreach { uuid ⇒
EventHandler.debug(this,
- "Migrating actors from failed node [%s] to node [%s]: Actor UUIDs [%s]"
- .format(failedNodeName, nodeAddress.nodeName, actorUuidsForFailedNode))
+ "Cluster node [%s] has failed, migrating actor with UUID [%s] to [%s]"
+ .format(failedNodeName, uuid, nodeAddress.nodeName))
- actorUuidsForFailedNode.foreach {
- uuid =>
- EventHandler.debug(this,
- "Cluster node [%s] has failed, migrating actor with UUID [%s] to [%s]"
- .format(failedNodeName, uuid, nodeAddress.nodeName))
+ val actorAddress = actorAddressForUuid(uuidFrom(uuid))
+ migrateWithoutCheckingThatActorResidesOnItsHomeNode( // since the ephemeral node is already gone, so can't check
+ NodeAddress(nodeAddress.clusterName, failedNodeName), nodeAddress, actorAddress)
- val actorAddress = actorAddressForUuid(uuidFrom(uuid))
- migrateWithoutCheckingThatActorResidesOnItsHomeNode(// since the ephemeral node is already gone, so can't check
- NodeAddress(nodeAddress.clusterName, failedNodeName), nodeAddress, actorAddress)
+ implicit val format: Format[T] = formatForActor(actorAddress)
+ use(actorAddress) foreach { actor ⇒
+ // FIXME remove ugly reflection when we have 1.0 final which has 'fromBinary(byte, homeAddress)(format)'
+ //actor.homeAddress = remoteServerAddress
+ val homeAddress = classOf[LocalActorRef].getDeclaredField("homeAddress")
+ homeAddress.setAccessible(true)
+ homeAddress.set(actor, Some(remoteServerAddress))
- implicit val format: Format[T] = formatForActor(actorAddress)
- use(actorAddress) foreach {
- actor =>
- // FIXME remove ugly reflection when we have 1.0 final which has 'fromBinary(byte, homeAddress)(format)'
- //actor.homeAddress = remoteServerAddress
- val homeAddress = classOf[LocalActorRef].getDeclaredField("homeAddress")
- homeAddress.setAccessible(true)
- homeAddress.set(actor, Some(remoteServerAddress))
-
- remoteService.register(uuid, actor)
- }
- }
-
- // notify all available nodes that they should fail-over all connections from 'from' to 'to'
- val from = nodeNameToAddress.get(failedNodeName)
- val to = remoteServerAddress
- val command = RemoteDaemonMessageProtocol.newBuilder
- .setMessageType(FAIL_OVER_CONNECTIONS)
- .setPayload(ByteString.copyFrom(Serializers.Java.toBinary((from, to))))
- .build
- membershipNodes foreach {
- node =>
- replicaConnections.get(node) foreach {
- case (_, connection) =>
- connection ! command
- }
+ remoteService.register(uuid, actor)
}
}
+
+ // notify all available nodes that they should fail-over all connections from 'from' to 'to'
+ val from = nodeNameToAddress.get(failedNodeName)
+ val to = remoteServerAddress
+ val command = RemoteDaemonMessageProtocol.newBuilder
+ .setMessageType(FAIL_OVER_CONNECTIONS)
+ .setPayload(ByteString.copyFrom(Serializers.Java.toBinary((from, to))))
+ .build
+ membershipNodes foreach { node ⇒
+ replicaConnections.get(node) foreach {
+ case (_, connection) ⇒
+ connection ! command
+ }
+ }
+ }
}
}
@@ -1420,27 +1381,26 @@ class ClusterNode private[akka](
* Used when the ephemeral "home" node is already gone, so we can't check.
*/
private def migrateWithoutCheckingThatActorResidesOnItsHomeNode(
- from: NodeAddress, to: NodeAddress, actorAddress: String) {
+ from: NodeAddress, to: NodeAddress, actorAddress: String) {
- actorUuidsForActorAddress(actorAddress) map {
- uuid =>
- val actorAddress = actorAddressForUuid(uuid)
+ actorUuidsForActorAddress(actorAddress) map { uuid ⇒
+ val actorAddress = actorAddressForUuid(uuid)
- if (!isInUseOnNode(actorAddress, to)) {
- release(actorAddress)
+ if (!isInUseOnNode(actorAddress, to)) {
+ release(actorAddress)
- val newAddress = new InetSocketAddress(to.hostname, to.port)
- ignore[ZkNodeExistsException](zkClient.createPersistent(actorRegistryNodePathFor(uuid)))
- ignore[ZkNodeExistsException](zkClient.createEphemeral(actorRegistryNodePathFor(uuid, newAddress)))
- ignore[ZkNodeExistsException](zkClient.createEphemeral(actorLocationsPathFor(uuid, to)))
- ignore[ZkNodeExistsException](zkClient.createPersistent(actorAtNodePathFor(nodeAddress.nodeName, uuid)))
+ val newAddress = new InetSocketAddress(to.hostname, to.port)
+ ignore[ZkNodeExistsException](zkClient.createPersistent(actorRegistryNodePathFor(uuid)))
+ ignore[ZkNodeExistsException](zkClient.createEphemeral(actorRegistryNodePathFor(uuid, newAddress)))
+ ignore[ZkNodeExistsException](zkClient.createEphemeral(actorLocationsPathFor(uuid, to)))
+ ignore[ZkNodeExistsException](zkClient.createPersistent(actorAtNodePathFor(nodeAddress.nodeName, uuid)))
- ignore[ZkNoNodeException](zkClient.delete(actorLocationsPathFor(uuid, from)))
- ignore[ZkNoNodeException](zkClient.delete(actorAtNodePathFor(from.nodeName, uuid)))
+ ignore[ZkNoNodeException](zkClient.delete(actorLocationsPathFor(uuid, from)))
+ ignore[ZkNoNodeException](zkClient.delete(actorAtNodePathFor(from.nodeName, uuid)))
- // 'use' (check out) actor on the remote 'to' node
- useActorOnNode(to.nodeName, uuid)
- }
+ // 'use' (check out) actor on the remote 'to' node
+ useActorOnNode(to.nodeName, uuid)
+ }
}
}
@@ -1467,18 +1427,17 @@ class ClusterNode private[akka](
}
private def createNodeStructureIfNeeded() {
- baseNodes.foreach {
- path =>
- try {
- zkClient.create(path, null, CreateMode.PERSISTENT)
- EventHandler.debug(this, "Created node [%s]".format(path))
- } catch {
- case e: ZkNodeExistsException => {} // do nothing
- case e =>
- val error = new ClusterException(e.toString)
- EventHandler.error(error, this, "")
- throw error
- }
+ baseNodes.foreach { path ⇒
+ try {
+ zkClient.create(path, null, CreateMode.PERSISTENT)
+ EventHandler.debug(this, "Created node [%s]".format(path))
+ } catch {
+ case e: ZkNodeExistsException ⇒ {} // do nothing
+ case e ⇒
+ val error = new ClusterException(e.toString)
+ EventHandler.error(error, this, "")
+ throw error
+ }
}
}
@@ -1579,16 +1538,14 @@ class MembershipChildListener(self: ClusterNode) extends IZkChildListener with E
if (!childList.isEmpty) EventHandler.debug(this,
"MembershipChildListener at [%s] has children [%s]"
.format(self.nodeAddress.nodeName, childList.mkString(" ")))
- self.findNewlyConnectedMembershipNodes(childList) foreach {
- name =>
- self.nodeNameToAddress.put(name, self.addressForNode(name)) // update 'nodename-address' map
- self.publish(Cluster.NodeConnected(name))
+ self.findNewlyConnectedMembershipNodes(childList) foreach { name ⇒
+ self.nodeNameToAddress.put(name, self.addressForNode(name)) // update 'nodename-address' map
+ self.publish(Cluster.NodeConnected(name))
}
- self.findNewlyDisconnectedMembershipNodes(childList) foreach {
- name =>
- self.nodeNameToAddress.remove(name) // update 'nodename-address' map
- self.publish(Cluster.NodeDisconnected(name))
+ self.findNewlyDisconnectedMembershipNodes(childList) foreach { name ⇒
+ self.nodeNameToAddress.remove(name) // update 'nodename-address' map
+ self.publish(Cluster.NodeDisconnected(name))
}
self.locallyCachedMembershipNodes.clear()
@@ -1604,13 +1561,13 @@ class MembershipChildListener(self: ClusterNode) extends IZkChildListener with E
class StateListener(self: ClusterNode) extends IZkStateListener {
def handleStateChanged(state: KeeperState) {
state match {
- case KeeperState.SyncConnected =>
+ case KeeperState.SyncConnected ⇒
EventHandler.debug(this, "Cluster node [%s] - Connected".format(self.nodeAddress))
self.publish(Cluster.ThisNode.Connected)
- case KeeperState.Disconnected =>
+ case KeeperState.Disconnected ⇒
EventHandler.debug(this, "Cluster node [%s] - Disconnected".format(self.nodeAddress))
self.publish(Cluster.ThisNode.Disconnected)
- case KeeperState.Expired =>
+ case KeeperState.Expired ⇒
EventHandler.debug(this, "Cluster node [%s] - Expired".format(self.nodeAddress))
self.publish(Cluster.ThisNode.Expired)
}
@@ -1630,14 +1587,14 @@ class StateListener(self: ClusterNode) extends IZkStateListener {
* @author Jonas Bonér
*/
trait ErrorHandler {
- def withErrorHandler[T](body: => T) = {
+ def withErrorHandler[T](body: ⇒ T) = {
try {
body
} catch {
- case e: org.I0Itec.zkclient.exception.ZkInterruptedException => {
+ case e: org.I0Itec.zkclient.exception.ZkInterruptedException ⇒ {
/* ignore */
}
- case e: Throwable =>
+ case e: Throwable ⇒
EventHandler.error(e, this, e.toString)
throw e
}
@@ -1665,11 +1622,11 @@ class RemoteClusterDaemon(cluster: ClusterNode) extends Actor {
self.dispatcher = Dispatchers.newThreadBasedDispatcher(self)
def receive: Receive = {
- case message: RemoteDaemonMessageProtocol =>
+ case message: RemoteDaemonMessageProtocol ⇒
EventHandler.debug(this, "Received command to RemoteClusterDaemon [%s]".format(message))
message.getMessageType match {
- case USE =>
+ case USE ⇒
if (message.hasActorUuid) {
val uuid = uuidProtocolToUuid(message.getActorUuid)
val address = cluster.actorAddressForUuid(uuid)
@@ -1682,36 +1639,34 @@ class RemoteClusterDaemon(cluster: ClusterNode) extends Actor {
} else EventHandler.warning(this,
"None of 'uuid', or 'address' is specified, ignoring remote cluster daemon command [%s]".format(message))
- case RELEASE =>
+ case RELEASE ⇒
if (message.hasActorUuid) {
cluster release cluster.actorAddressForUuid(uuidProtocolToUuid(message.getActorUuid))
- }
- else if (message.hasActorAddress) {
+ } else if (message.hasActorAddress) {
cluster release message.getActorAddress
- }
- else EventHandler.warning(this,
+ } else EventHandler.warning(this,
"None of 'uuid' or 'actorAddress'' is specified, ignoring remote cluster daemon command [%s]".format(message))
- case START => cluster.start()
+ case START ⇒ cluster.start()
- case STOP => cluster.stop()
+ case STOP ⇒ cluster.stop()
- case DISCONNECT => cluster.disconnect()
+ case DISCONNECT ⇒ cluster.disconnect()
- case RECONNECT => cluster.reconnect()
+ case RECONNECT ⇒ cluster.reconnect()
- case RESIGN => cluster.resign()
+ case RESIGN ⇒ cluster.resign()
- case FAIL_OVER_CONNECTIONS =>
+ case FAIL_OVER_CONNECTIONS ⇒
val (from, to) = payloadFor(message, classOf[(InetSocketAddress, InetSocketAddress)])
cluster.failOverConnections(from, to)
- case FUNCTION_FUN0_UNIT =>
+ case FUNCTION_FUN0_UNIT ⇒
actorOf(new Actor() {
self.dispatcher = functionServerDispatcher
def receive = {
- case f: Function0[Unit] => try {
+ case f: Function0[Unit] ⇒ try {
f()
} finally {
self.stop()
@@ -1719,12 +1674,12 @@ class RemoteClusterDaemon(cluster: ClusterNode) extends Actor {
}
}).start ! payloadFor(message, classOf[Function0[Unit]])
- case FUNCTION_FUN0_ANY =>
+ case FUNCTION_FUN0_ANY ⇒
actorOf(new Actor() {
self.dispatcher = functionServerDispatcher
def receive = {
- case f: Function0[Any] => try {
+ case f: Function0[Any] ⇒ try {
self.reply(f())
} finally {
self.stop()
@@ -1732,12 +1687,12 @@ class RemoteClusterDaemon(cluster: ClusterNode) extends Actor {
}
}).start forward payloadFor(message, classOf[Function0[Any]])
- case FUNCTION_FUN1_ARG_UNIT =>
+ case FUNCTION_FUN1_ARG_UNIT ⇒
actorOf(new Actor() {
self.dispatcher = functionServerDispatcher
def receive = {
- case t: Tuple2[Function1[Any, Unit], Any] => try {
+ case t: Tuple2[Function1[Any, Unit], Any] ⇒ try {
t._1(t._2)
} finally {
self.stop()
@@ -1745,12 +1700,12 @@ class RemoteClusterDaemon(cluster: ClusterNode) extends Actor {
}
}).start ! payloadFor(message, classOf[Tuple2[Function1[Any, Unit], Any]])
- case FUNCTION_FUN1_ARG_ANY =>
+ case FUNCTION_FUN1_ARG_ANY ⇒
actorOf(new Actor() {
self.dispatcher = functionServerDispatcher
def receive = {
- case t: Tuple2[Function1[Any, Any], Any] => try {
+ case t: Tuple2[Function1[Any, Any], Any] ⇒ try {
self.reply(t._1(t._2))
} finally {
self.stop()
@@ -1759,7 +1714,7 @@ class RemoteClusterDaemon(cluster: ClusterNode) extends Actor {
}).start forward payloadFor(message, classOf[Tuple2[Function1[Any, Any], Any]])
}
- case unknown => EventHandler.warning(this, "Unknown message [%s]".format(unknown))
+ case unknown ⇒ EventHandler.warning(this, "Unknown message [%s]".format(unknown))
}
private def payloadFor[T](message: RemoteDaemonMessageProtocol, clazz: Class[T]): T = {
diff --git a/akka-cluster/src/main/scala/akka/cluster/ClusterActorRef.scala b/akka-cluster/src/main/scala/akka/cluster/ClusterActorRef.scala
index eb614a05fe..ec2060bfb5 100644
--- a/akka-cluster/src/main/scala/akka/cluster/ClusterActorRef.scala
+++ b/akka-cluster/src/main/scala/akka/cluster/ClusterActorRef.scala
@@ -25,7 +25,7 @@ class ClusterActorRef private[akka] (
actorType: ActorType,
val replicationStrategy: ReplicationStrategy)
extends RemoteActorRef(address, timeout, None, actorType) {
- this: ClusterActorRef with Router.Router =>
+ this: ClusterActorRef with Router.Router ⇒
EventHandler.debug(this, "Creating a ClusterActorRef for actor with address [%s]".format(address))
@@ -46,20 +46,20 @@ class ClusterActorRef private[akka] (
route[T](message, timeout)(senderOption).asInstanceOf[CompletableFuture[T]]
private[akka] def failOver(from: InetSocketAddress, to: InetSocketAddress) {
- addresses set (
- addresses.get map { case (address, actorRef) =>
+ addresses set (addresses.get map {
+ case (address, actorRef) ⇒
if (address == from) {
actorRef.stop()
(to, createRemoteActorRef(actorRef.uuid, to))
} else (address, actorRef)
- }
- )
+ })
}
private def createConnections(addresses: Array[Tuple2[UUID, InetSocketAddress]]): Map[InetSocketAddress, ActorRef] = {
var connections = Map.empty[InetSocketAddress, ActorRef]
- addresses foreach { case (uuid, address) =>
- connections = connections + (address -> createRemoteActorRef(uuid, address))
+ addresses foreach {
+ case (uuid, address) ⇒
+ connections = connections + (address -> createRemoteActorRef(uuid, address))
}
connections
}
diff --git a/akka-cluster/src/main/scala/akka/cluster/ClusterDeployer.scala b/akka-cluster/src/main/scala/akka/cluster/ClusterDeployer.scala
index 42984a6872..c850d72077 100644
--- a/akka-cluster/src/main/scala/akka/cluster/ClusterDeployer.scala
+++ b/akka-cluster/src/main/scala/akka/cluster/ClusterDeployer.scala
@@ -4,7 +4,7 @@
package akka.cluster
-import akka.actor.{DeploymentConfig, Deployer, DeploymentException}
+import akka.actor.{ DeploymentConfig, Deployer, DeploymentException }
import DeploymentConfig._
import akka.event.EventHandler
import akka.config.Config
@@ -13,9 +13,9 @@ import akka.util.Helpers._
import akka.cluster.zookeeper.AkkaZkClient
import org.apache.zookeeper.CreateMode
-import org.apache.zookeeper.recipes.lock.{WriteLock, LockListener}
+import org.apache.zookeeper.recipes.lock.{ WriteLock, LockListener }
-import org.I0Itec.zkclient.exception.{ZkNoNodeException, ZkNodeExistsException}
+import org.I0Itec.zkclient.exception.{ ZkNoNodeException, ZkNodeExistsException }
import scala.collection.JavaConversions.collectionAsScalaIterable
@@ -75,22 +75,20 @@ object ClusterDeployer {
Deploy(
address = RemoteClusterDaemon.ADDRESS,
routing = Direct,
- scope = Clustered(Deployer.defaultAddress, NoReplicas, Stateless))
- )
+ scope = Clustered(Deployer.defaultAddress, NoReplicas, Stateless)))
private[akka] def init(deployments: List[Deploy]) {
isConnected.switchOn {
- baseNodes.foreach {
- path =>
- try {
- ignore[ZkNodeExistsException](zkClient.create(path, null, CreateMode.PERSISTENT))
- EventHandler.debug(this, "Created node [%s]".format(path))
- } catch {
- case e =>
- val error = new DeploymentException(e.toString)
- EventHandler.error(error, this)
- throw error
- }
+ baseNodes.foreach { path ⇒
+ try {
+ ignore[ZkNodeExistsException](zkClient.create(path, null, CreateMode.PERSISTENT))
+ EventHandler.debug(this, "Created node [%s]".format(path))
+ } catch {
+ case e ⇒
+ val error = new DeploymentException(e.toString)
+ EventHandler.error(error, this)
+ throw error
+ }
}
val allDeployments = deployments ::: systemDeployments
@@ -121,9 +119,9 @@ object ClusterDeployer {
// FIXME trigger cluster-wide deploy action
} catch {
- case e: NullPointerException =>
+ case e: NullPointerException ⇒
handleError(new DeploymentException("Could not store deployment data [" + deployment + "] in ZooKeeper since client session is closed"))
- case e: Exception =>
+ case e: Exception ⇒
handleError(new DeploymentException("Could not store deployment data [" + deployment + "] in ZooKeeper due to: " + e))
}
}
@@ -134,7 +132,7 @@ object ClusterDeployer {
// FIXME trigger cluster-wide undeployment action
} catch {
- case e: Exception =>
+ case e: Exception ⇒
handleError(new DeploymentException("Could not undeploy deployment [" + deployment + "] in ZooKeeper due to: " + e))
}
}
@@ -142,11 +140,11 @@ object ClusterDeployer {
private[akka] def undeployAll() {
try {
for {
- child <- collectionAsScalaIterable(zkClient.getChildren(deploymentPath))
- deployment <- lookupDeploymentFor(child)
+ child ← collectionAsScalaIterable(zkClient.getChildren(deploymentPath))
+ deployment ← lookupDeploymentFor(child)
} undeploy(deployment)
} catch {
- case e: Exception =>
+ case e: Exception ⇒
handleError(new DeploymentException("Could not undeploy all deployment data in ZooKeeper due to: " + e))
}
}
@@ -155,8 +153,8 @@ object ClusterDeployer {
try {
Some(zkClient.readData(deploymentAddressPath.format(address)).asInstanceOf[Deploy])
} catch {
- case e: ZkNoNodeException => None
- case e: Exception =>
+ case e: ZkNoNodeException ⇒ None
+ case e: Exception ⇒
EventHandler.warning(this, e.toString)
None
}
diff --git a/akka-cluster/src/main/scala/akka/cluster/ReplicatedClusterRef.scala b/akka-cluster/src/main/scala/akka/cluster/ReplicatedClusterRef.scala
index 864870d2ec..ac1be8248d 100644
--- a/akka-cluster/src/main/scala/akka/cluster/ReplicatedClusterRef.scala
+++ b/akka-cluster/src/main/scala/akka/cluster/ReplicatedClusterRef.scala
@@ -13,13 +13,13 @@ import akka.dispatch._
import java.net.InetSocketAddress
import java.util.concurrent.atomic.AtomicReference
-import java.util.{ Map => JMap }
+import java.util.{ Map ⇒ JMap }
import akka.cluster.TransactionLog
/**
* @author Jonas Bonér
*/
-trait Replicable { this: Actor =>
+trait Replicable { this: Actor ⇒
}
/**
@@ -50,7 +50,7 @@ class ReplicatedActorRef private[akka] (actorRef: ActorRef, val address: String)
def start(): ActorRef = {
EventHandler.debug(this, "Starting ReplicatedActorRef for Actor [%s] with transaction log [%s]"
- .format(address, txLog.logId))
+ .format(address, txLog.logId))
actorRef.start()
}
@@ -87,8 +87,7 @@ class ReplicatedActorRef private[akka] (actorRef: ActorRef, val address: String)
message: Any,
timeout: Long,
senderOption: Option[ActorRef],
- senderFuture: Option[CompletableFuture[T]]): CompletableFuture[T]
- = actorRef.postMessageToMailboxAndCreateFutureResultWithTimeout(message, timeout, senderOption, senderFuture)
+ senderFuture: Option[CompletableFuture[T]]): CompletableFuture[T] = actorRef.postMessageToMailboxAndCreateFutureResultWithTimeout(message, timeout, senderOption, senderFuture)
protected[akka] def actorInstance: AtomicReference[Actor] = actorRef.actorInstance
protected[akka] def supervisor_=(sup: Option[ActorRef]) {
actorRef.supervisor_=(sup)
diff --git a/akka-cluster/src/main/scala/akka/cluster/Routing.scala b/akka-cluster/src/main/scala/akka/cluster/Routing.scala
index 0f7408be4b..3713766605 100644
--- a/akka-cluster/src/main/scala/akka/cluster/Routing.scala
+++ b/akka-cluster/src/main/scala/akka/cluster/Routing.scala
@@ -30,21 +30,21 @@ object Router {
replicationStrategy: ReplicationStrategy = ReplicationStrategy.WriteThrough): ClusterActorRef = {
routerType match {
- case Direct => new ClusterActorRef(
+ case Direct ⇒ new ClusterActorRef(
addresses, serviceId, timeout,
actorType, replicationStrategy) with Direct
- case Random => new ClusterActorRef(
+ case Random ⇒ new ClusterActorRef(
addresses, serviceId, timeout,
actorType, replicationStrategy) with Random
- case RoundRobin => new ClusterActorRef(
+ case RoundRobin ⇒ new ClusterActorRef(
addresses, serviceId, timeout,
actorType, replicationStrategy) with RoundRobin
- case LeastCPU => sys.error("Router LeastCPU not supported yet")
- case LeastRAM => sys.error("Router LeastRAM not supported yet")
- case LeastMessages => sys.error("Router LeastMessages not supported yet")
+ case LeastCPU ⇒ sys.error("Router LeastCPU not supported yet")
+ case LeastRAM ⇒ sys.error("Router LeastRAM not supported yet")
+ case LeastMessages ⇒ sys.error("Router LeastMessages not supported yet")
}
}
@@ -65,7 +65,7 @@ object Router {
trait Direct extends Router {
lazy val connection: Option[ActorRef] = {
if (connections.size == 0) throw new IllegalStateException("DirectRouter need a single replica connection found [0]")
- connections.toList.map({ case (address, actor) => actor }).headOption
+ connections.toList.map({ case (address, actor) ⇒ actor }).headOption
}
def route(message: Any)(implicit sender: Option[ActorRef]) {
@@ -75,7 +75,7 @@ object Router {
def route[T](message: Any, timeout: Long)(implicit sender: Option[ActorRef]): Future[T] =
if (connection.isDefined) connection.get.!!!(message, timeout)(sender)
- else throw new RoutingException("No node connections for router")
+ else throw new RoutingException("No node connections for router")
}
/**
@@ -91,12 +91,12 @@ object Router {
def route[T](message: Any, timeout: Long)(implicit sender: Option[ActorRef]): Future[T] =
if (next.isDefined) next.get.!!!(message, timeout)(sender)
- else throw new RoutingException("No node connections for router")
+ else throw new RoutingException("No node connections for router")
private def next: Option[ActorRef] = {
val nrOfConnections = connections.size
if (nrOfConnections == 0) None
- else Some(connections.toArray.apply(random.nextInt(nrOfConnections))._2)
+ else Some(connections.toArray.apply(random.nextInt(nrOfConnections))._2)
}
}
@@ -104,7 +104,7 @@ object Router {
* @author Jonas Bonér
*/
trait RoundRobin extends Router {
- private def items: List[ActorRef] = connections.toList.map({ case (address, actor) => actor })
+ private def items: List[ActorRef] = connections.toList.map({ case (address, actor) ⇒ actor })
@volatile
private var current = items
@@ -116,7 +116,7 @@ object Router {
def route[T](message: Any, timeout: Long)(implicit sender: Option[ActorRef]): Future[T] =
if (next.isDefined) next.get.!!!(message, timeout)(sender)
- else throw new RoutingException("No node connections for router")
+ else throw new RoutingException("No node connections for router")
private def hasNext = items != Nil
diff --git a/akka-cluster/src/main/scala/akka/cluster/TransactionLog.scala b/akka-cluster/src/main/scala/akka/cluster/TransactionLog.scala
index 3d0c466d20..b6e30fca1c 100644
--- a/akka-cluster/src/main/scala/akka/cluster/TransactionLog.scala
+++ b/akka-cluster/src/main/scala/akka/cluster/TransactionLog.scala
@@ -4,7 +4,7 @@ package akka.cluster
* Copyright (C) 2009-2011 Scalable Solutions AB
*/
-import org.apache.bookkeeper.client.{BookKeeper, LedgerHandle, LedgerEntry, BKException, AsyncCallback}
+import org.apache.bookkeeper.client.{ BookKeeper, LedgerHandle, LedgerEntry, BKException, AsyncCallback }
import org.apache.zookeeper.CreateMode
import org.I0Itec.zkclient.exception._
@@ -13,7 +13,7 @@ import akka.config._
import Config._
import akka.util._
import akka.event.EventHandler
-import akka.dispatch.{DefaultCompletableFuture, CompletableFuture}
+import akka.dispatch.{ DefaultCompletableFuture, CompletableFuture }
import akka.AkkaException
import akka.cluster.zookeeper._
@@ -41,7 +41,7 @@ class ReplicationException(message: String) extends AkkaException(message)
*
* @author Jonas Bonér
*/
-class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync: Boolean) {
+class TransactionLog private (ledger: LedgerHandle, val id: String, val isAsync: Boolean) {
import TransactionLog._
@@ -62,10 +62,10 @@ class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync:
entry,
new AsyncCallback.AddCallback {
def addComplete(
- returnCode: Int,
- ledgerHandle: LedgerHandle,
- entryId: Long,
- ctx: AnyRef) {
+ returnCode: Int,
+ ledgerHandle: LedgerHandle,
+ entryId: Long,
+ ctx: AnyRef) {
handleReturnCode(returnCode)
EventHandler.debug(this,
"Writing entry [%s] to log [%s]".format(entryId, logId))
@@ -78,7 +78,7 @@ class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync:
EventHandler.debug(this, "Writing entry [%s] to log [%s]".format(entryId, logId))
}
} catch {
- case e => handleError(e)
+ case e ⇒ handleError(e)
}
} else transactionClosedError
}
@@ -94,10 +94,10 @@ class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync:
snapshot,
new AsyncCallback.AddCallback {
def addComplete(
- returnCode: Int,
- ledgerHandle: LedgerHandle,
- entryId: Long,
- ctx: AnyRef) {
+ returnCode: Int,
+ ledgerHandle: LedgerHandle,
+ entryId: Long,
+ ctx: AnyRef) {
handleReturnCode(returnCode)
storeSnapshotMetaDataInZooKeeper(entryId)
}
@@ -108,7 +108,7 @@ class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync:
storeSnapshotMetaDataInZooKeeper(ledger.getLastAddPushed)
}
} catch {
- case e => handleError(e)
+ case e ⇒ handleError(e)
}
} else transactionClosedError
}
@@ -145,10 +145,10 @@ class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync:
from, to,
new AsyncCallback.ReadCallback {
def readComplete(
- returnCode: Int,
- ledgerHandle: LedgerHandle,
- enumeration: Enumeration[LedgerEntry],
- ctx: AnyRef) {
+ returnCode: Int,
+ ledgerHandle: LedgerHandle,
+ enumeration: Enumeration[LedgerEntry],
+ ctx: AnyRef) {
val future = ctx.asInstanceOf[CompletableFuture[Vector[Array[Byte]]]]
var entries = Vector[Array[Byte]]()
while (enumeration.hasMoreElements) {
@@ -169,7 +169,7 @@ class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync:
entries
}
} catch {
- case e => handleError(e)
+ case e ⇒ handleError(e)
}
} else transactionClosedError
@@ -188,11 +188,11 @@ class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync:
"Retrieved latest snapshot id [%s] from transaction log [%s]".format(snapshotId, logId))
snapshotId
} catch {
- case e: ZkNoNodeException =>
+ case e: ZkNoNodeException ⇒
handleError(new ReplicationException(
"Transaction log for UUID [" + id +
"] does not have a snapshot recorded in ZooKeeper"))
- case e => handleError(e)
+ case e ⇒ handleError(e)
}
}
@@ -216,7 +216,7 @@ class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync:
bookieClient.deleteLedger(logId)
}
} catch {
- case e => handleError(e)
+ case e ⇒ handleError(e)
}
}
}
@@ -232,9 +232,9 @@ class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync:
ledger.asyncClose(
new AsyncCallback.CloseCallback {
def closeComplete(
- returnCode: Int,
- ledgerHandle: LedgerHandle,
- ctx: AnyRef) {
+ returnCode: Int,
+ ledgerHandle: LedgerHandle,
+ ctx: AnyRef) {
handleReturnCode(returnCode)
}
},
@@ -243,7 +243,7 @@ class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync:
ledger.close()
}
} catch {
- case e => handleError(e)
+ case e ⇒ handleError(e)
}
}
}
@@ -253,14 +253,14 @@ class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync:
try {
zkClient.create(snapshotPath, null, CreateMode.PERSISTENT)
} catch {
- case e: ZkNodeExistsException => {} // do nothing
- case e => handleError(e)
+ case e: ZkNodeExistsException ⇒ {} // do nothing
+ case e ⇒ handleError(e)
}
try {
zkClient.writeData(snapshotPath, snapshotId)
} catch {
- case e =>
+ case e ⇒
handleError(new ReplicationException(
"Could not store transaction log snapshot meta-data in ZooKeeper for UUID [" +
id + "]"))
@@ -270,7 +270,7 @@ class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync:
} else transactionClosedError
}
- private def handleReturnCode(block: => Long) {
+ private def handleReturnCode(block: ⇒ Long) {
val code = block.toInt
if (code == BKException.Code.OK) {} // all fine
else handleError(BKException.create(code))
@@ -289,9 +289,9 @@ class TransactionLog private(ledger: LedgerHandle, val id: String, val isAsync:
object TransactionLog {
val digestType = config.getString("akka.cluster.replication.digest-type", "CRC32") match {
- case "CRC32" => BookKeeper.DigestType.CRC32
- case "MAC" => BookKeeper.DigestType.MAC
- case unknown => throw new ConfigurationException(
+ case "CRC32" ⇒ BookKeeper.DigestType.CRC32
+ case "MAC" ⇒ BookKeeper.DigestType.MAC
+ case unknown ⇒ throw new ConfigurationException(
"akka.cluster.replication.digest-type is invalid [" + unknown + "]")
}
val password = config.getString("akka.cluster.replication.password", "secret").getBytes("UTF-8")
@@ -315,8 +315,8 @@ object TransactionLog {
try {
zk.create(transactionLogNode, null, CreateMode.PERSISTENT)
} catch {
- case e: ZkNodeExistsException => {} // do nothing
- case e => handleError(e)
+ case e: ZkNodeExistsException ⇒ {} // do nothing
+ case e ⇒ handleError(e)
}
EventHandler.info(this,
@@ -325,10 +325,10 @@ object TransactionLog {
"\n\tensemble size [%s]" +
"\n\tquorum size [%s]" +
"\n\tlogging time out [%s]").format(
- digestType,
- ensembleSize,
- quorumSize,
- timeout))
+ digestType,
+ ensembleSize,
+ quorumSize,
+ timeout))
isConnected.switchOn
(bk, zk)
}
@@ -347,7 +347,7 @@ object TransactionLog {
bookieClient.halt()
EventHandler.info(this, "Transaction log shut down successfully")
} catch {
- case e => handleError(e)
+ case e ⇒ handleError(e)
}
}
}
@@ -368,9 +368,9 @@ object TransactionLog {
ensembleSize, quorumSize, digestType, password,
new AsyncCallback.CreateCallback {
def createComplete(
- returnCode: Int,
- ledgerHandle: LedgerHandle,
- ctx: AnyRef) {
+ returnCode: Int,
+ ledgerHandle: LedgerHandle,
+ ctx: AnyRef) {
val future = ctx.asInstanceOf[CompletableFuture[LedgerHandle]]
if (returnCode == BKException.Code.OK) future.completeWithResult(ledgerHandle)
else future.completeWithException(BKException.create(returnCode))
@@ -382,7 +382,7 @@ object TransactionLog {
bookieClient.createLedger(ensembleSize, quorumSize, digestType, password)
}
} catch {
- case e => handleError(e)
+ case e ⇒ handleError(e)
}
val logId = ledger.getId
@@ -391,7 +391,7 @@ object TransactionLog {
zkClient.writeData(txLogPath, logId)
logId
} catch {
- case e =>
+ case e ⇒
bookieClient.deleteLedger(logId) // clean up
handleError(new ReplicationException(
"Could not store transaction log [" + logId +
@@ -414,10 +414,10 @@ object TransactionLog {
"Retrieved transaction log [%s] for UUID [%s]".format(logId, id))
logId
} catch {
- case e: ZkNoNodeException =>
+ case e: ZkNoNodeException ⇒
handleError(new ReplicationException(
"Transaction log for UUID [" + id + "] does not exist in ZooKeeper"))
- case e => handleError(e)
+ case e ⇒ handleError(e)
}
val ledger = try {
@@ -427,9 +427,9 @@ object TransactionLog {
logId, digestType, password,
new AsyncCallback.OpenCallback {
def openComplete(
- returnCode: Int,
- ledgerHandle: LedgerHandle,
- ctx: AnyRef) {
+ returnCode: Int,
+ ledgerHandle: LedgerHandle,
+ ctx: AnyRef) {
val future = ctx.asInstanceOf[CompletableFuture[LedgerHandle]]
if (returnCode == BKException.Code.OK) future.completeWithResult(ledgerHandle)
else future.completeWithException(BKException.create(returnCode))
@@ -441,7 +441,7 @@ object TransactionLog {
bookieClient.openLedger(logId, digestType, password)
}
} catch {
- case e => handleError(e)
+ case e ⇒ handleError(e)
}
TransactionLog(ledger, id, isAsync)
@@ -467,7 +467,8 @@ object LocalBookKeeperEnsemble {
private val isRunning = new Switch(false)
private val port = 5555
- @volatile private var localBookKeeper: LocalBookKeeper = _
+ @volatile
+ private var localBookKeeper: LocalBookKeeper = _
/**
* TODO document method
diff --git a/akka-cluster/src/main/scala/akka/cluster/zookeeper/AkkaZkClient.scala b/akka-cluster/src/main/scala/akka/cluster/zookeeper/AkkaZkClient.scala
index 7b787a0d84..2b9a7a084f 100644
--- a/akka-cluster/src/main/scala/akka/cluster/zookeeper/AkkaZkClient.scala
+++ b/akka-cluster/src/main/scala/akka/cluster/zookeeper/AkkaZkClient.scala
@@ -26,8 +26,9 @@ class AkkaZkClient(zkServers: String,
_connection.close()
_connection.connect(this)
} catch {
- case e: InterruptedException => throw new ZkInterruptedException(e)
- } finally {
+ case e: InterruptedException ⇒ throw new ZkInterruptedException(e)
+ }
+ finally {
zkLock.unlock()
}
}
diff --git a/akka-cluster/src/main/scala/akka/cluster/zookeeper/ZooKeeperBarrier.scala b/akka-cluster/src/main/scala/akka/cluster/zookeeper/ZooKeeperBarrier.scala
index 76878618c0..e6e44c6520 100644
--- a/akka-cluster/src/main/scala/akka/cluster/zookeeper/ZooKeeperBarrier.scala
+++ b/akka-cluster/src/main/scala/akka/cluster/zookeeper/ZooKeeperBarrier.scala
@@ -9,10 +9,9 @@ import akka.util.duration._
import org.I0Itec.zkclient._
import org.I0Itec.zkclient.exception._
-import java.util.{List => JList}
+import java.util.{ List ⇒ JList }
import java.util.concurrent.CountDownLatch
-
class BarrierTimeoutException(message: String) extends RuntimeException(message)
/**
@@ -34,11 +33,11 @@ object ZooKeeperBarrier {
def apply(zkClient: ZkClient, cluster: String, name: String, node: String, count: Int, timeout: Duration) =
new ZooKeeperBarrier(zkClient, cluster + "-" + name, node, count, timeout)
- def ignore[E: Manifest](body: => Unit) {
+ def ignore[E: Manifest](body: ⇒ Unit) {
try {
body
} catch {
- case e if manifest[E].erasure.isAssignableFrom(e.getClass) => ()
+ case e if manifest[E].erasure.isAssignableFrom(e.getClass) ⇒ ()
}
}
}
@@ -49,7 +48,7 @@ object ZooKeeperBarrier {
class ZooKeeperBarrier(zkClient: ZkClient, name: String, node: String, count: Int, timeout: Duration)
extends IZkChildListener {
- import ZooKeeperBarrier.{BarriersNode, ignore}
+ import ZooKeeperBarrier.{ BarriersNode, ignore }
val barrier = BarriersNode + "/" + name
val entry = barrier + "/" + node
@@ -60,7 +59,7 @@ class ZooKeeperBarrier(zkClient: ZkClient, name: String, node: String, count: In
ignore[ZkNodeExistsException](zkClient.createPersistent(BarriersNode))
ignore[ZkNodeExistsException](zkClient.createPersistent(barrier))
- def apply(body: => Unit) {
+ def apply(body: ⇒ Unit) {
enter
body
leave()
diff --git a/akka-cluster/src/test/scala/akka/cluster/ClusterDeployerSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ClusterDeployerSpec.scala
index 7290c396e1..425096fb8d 100644
--- a/akka-cluster/src/test/scala/akka/cluster/ClusterDeployerSpec.scala
+++ b/akka-cluster/src/test/scala/akka/cluster/ClusterDeployerSpec.scala
@@ -11,7 +11,7 @@ import akka.actor._
object ClusterDeployerSpec {
class Pi extends Actor {
def receive = {
- case "Hello" => self.reply("World")
+ case "Hello" ⇒ self.reply("World")
}
}
}
@@ -20,24 +20,24 @@ class ClusterDeployerSpec extends WordSpec with MustMatchers with BeforeAndAfter
import ClusterDeployerSpec._
val dataPath = "_akka_cluster/data"
- val logPath = "_akka_cluster/log"
+ val logPath = "_akka_cluster/log"
var zkServer: ZkServer = _
"A ClusterDeployer" should {
"be able to deploy deployments in configuration file" in {
val deployments = Deployer.deploymentsInConfig
- deployments must not equal(Nil)
+ deployments must not equal (Nil)
ClusterDeployer.init(deployments)
- deployments map { oldDeployment =>
+ deployments map { oldDeployment ⇒
val newDeployment = ClusterDeployer.lookupDeploymentFor(oldDeployment.address)
newDeployment must be('defined)
oldDeployment must equal(newDeployment.get)
}
}
-/*
+ /*
"be able to create an actor deployed using ClusterDeployer" in {
val pi = Actor.actorOf[Pi]("service-pi")
pi must not equal(null)
@@ -50,7 +50,7 @@ class ClusterDeployerSpec extends WordSpec with MustMatchers with BeforeAndAfter
zkServer = Cluster.startLocalCluster(dataPath, logPath)
Thread.sleep(5000)
} catch {
- case e => e.printStackTrace()
+ case e ⇒ e.printStackTrace()
}
}
diff --git a/akka-cluster/src/test/scala/akka/cluster/ClusterMultiJvmSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ClusterMultiJvmSpec.scala
index edf0b46ff7..83a803ca9c 100644
--- a/akka-cluster/src/test/scala/akka/cluster/ClusterMultiJvmSpec.scala
+++ b/akka-cluster/src/test/scala/akka/cluster/ClusterMultiJvmSpec.scala
@@ -6,7 +6,7 @@ package akka.cluster
import org.scalatest.WordSpec
import org.scalatest.matchers.MustMatchers
-import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach}
+import org.scalatest.{ BeforeAndAfterAll, BeforeAndAfterEach }
import akka.cluster.zookeeper._
import org.I0Itec.zkclient._
@@ -15,7 +15,7 @@ object MultiNodeTest {
val NrOfNodes = 2
val ClusterName = "test-cluster"
val DataPath = "_akka_cluster/data"
- val LogPath = "_akka_cluster/log"
+ val LogPath = "_akka_cluster/log"
}
trait MultiNodeTest extends WordSpec with MustMatchers with BeforeAndAfterAll with BeforeAndAfterEach {
diff --git a/akka-cluster/src/test/scala/akka/cluster/ClusterSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ClusterSpec.scala
index 0f8e2e273a..f6c80ef094 100644
--- a/akka-cluster/src/test/scala/akka/cluster/ClusterSpec.scala
+++ b/akka-cluster/src/test/scala/akka/cluster/ClusterSpec.scala
@@ -8,7 +8,7 @@ import org.I0Itec.zkclient._
import akka.actor._
import akka.actor.Actor._
-import akka.serialization.{Serializers, SerializerBasedActorFormat}
+import akka.serialization.{ Serializers, SerializerBasedActorFormat }
import akka.util.Helpers._
import akka.actor.DeploymentConfig._
@@ -22,7 +22,7 @@ class MyJavaSerializableActor extends Actor with Serializable {
var count = 0
def receive = {
- case "hello" =>
+ case "hello" ⇒
count = count + 1
self.reply("world " + count)
}
diff --git a/akka-cluster/src/test/scala/akka/cluster/ClusteredFunctions.scala b/akka-cluster/src/test/scala/akka/cluster/ClusteredFunctions.scala
index 50e875c600..7c67583f52 100644
--- a/akka-cluster/src/test/scala/akka/cluster/ClusteredFunctions.scala
+++ b/akka-cluster/src/test/scala/akka/cluster/ClusteredFunctions.scala
@@ -11,7 +11,7 @@ import akka.dispatch.Futures
* @author Jonas Bonér
*/
object ClusteredFunctions {
-//sample.cluster.ClusteredFunctions.fun2
+ //sample.cluster.ClusteredFunctions.fun2
// run all
def run {
@@ -24,11 +24,11 @@ object ClusteredFunctions {
// Send Function0[Unit]
def fun1 = {
Cluster.startLocalCluster()
- val node = Cluster newNode (NodeAddress("test", "local", port = 9991)) start
+ val node = Cluster newNode (NodeAddress("test", "local", port = 9991)) start
val remote1 = Cluster newNode (NodeAddress("test", "remote1", port = 9992)) start
Thread.sleep(100)
- val fun = () => println("=============>>> AKKA ROCKS <<<=============")
+ val fun = () ⇒ println("=============>>> AKKA ROCKS <<<=============")
node send (fun, 2) // send and invoke function on to two cluster nodes
node.stop
@@ -39,11 +39,11 @@ object ClusteredFunctions {
// Send Function0[Any]
def fun2 = {
Cluster.startLocalCluster()
- val local = Cluster newNode (NodeAddress("test", "local", port = 9991)) start
+ val local = Cluster newNode (NodeAddress("test", "local", port = 9991)) start
val remote1 = Cluster newNode (NodeAddress("test", "remote1", port = 9992)) start
Thread.sleep(100)
- val fun = () => "AKKA ROCKS"
+ val fun = () ⇒ "AKKA ROCKS"
val futures = local send (fun, 2) // send and invoke function on to two cluster nodes and get result
val result = Futures.fold("")(futures)(_ + " - " + _).await.resultOrException
@@ -57,10 +57,10 @@ object ClusteredFunctions {
// Send Function1[Any, Unit]
def fun3 = {
Cluster.startLocalCluster()
- val local = Cluster newNode (NodeAddress("test", "local", port = 9991)) start
+ val local = Cluster newNode (NodeAddress("test", "local", port = 9991)) start
val remote1 = Cluster newNode (NodeAddress("test", "remote1", port = 9992)) start
- val fun = ((s: String) => println("=============>>> " + s + " <<<=============")).asInstanceOf[Function1[Any, Unit]]
+ val fun = ((s: String) ⇒ println("=============>>> " + s + " <<<=============")).asInstanceOf[Function1[Any, Unit]]
local send (fun, "AKKA ROCKS", 2) // send and invoke function on to two cluster nodes
local.stop
@@ -71,10 +71,10 @@ object ClusteredFunctions {
// Send Function1[Any, Any]
def fun4 = {
Cluster.startLocalCluster()
- val local = Cluster newNode (NodeAddress("test", "local", port = 9991)) start
+ val local = Cluster newNode (NodeAddress("test", "local", port = 9991)) start
val remote1 = Cluster newNode (NodeAddress("test", "remote1", port = 9992)) start
- val fun = ((i: Int) => i * i).asInstanceOf[Function1[Any, Any]]
+ val fun = ((i: Int) ⇒ i * i).asInstanceOf[Function1[Any, Any]]
val future1 = local send (fun, 2, 1) head // send and invoke function on one cluster node and get result
val future2 = local send (fun, 2, 1) head // send and invoke function on one cluster node and get result
diff --git a/akka-cluster/src/test/scala/akka/cluster/ClusteredPingPongSample.scala b/akka-cluster/src/test/scala/akka/cluster/ClusteredPingPongSample.scala
index 8c932ec79a..4e1b358d89 100644
--- a/akka-cluster/src/test/scala/akka/cluster/ClusteredPingPongSample.scala
+++ b/akka-cluster/src/test/scala/akka/cluster/ClusteredPingPongSample.scala
@@ -8,7 +8,7 @@ import akka.cluster._
import akka.actor._
import akka.actor.Actor._
-import akka.serialization.{Serializers, SerializerBasedActorFormat}
+import akka.serialization.{ Serializers, SerializerBasedActorFormat }
import java.util.concurrent.CountDownLatch
@@ -36,7 +36,7 @@ object PingPong {
var gameOverLatch: CountDownLatch = _
def receive = {
- case Ball =>
+ case Ball ⇒
if (count < NrOfPings) {
println("---->> PING (%s)" format count)
count += 1
@@ -46,16 +46,16 @@ object PingPong {
gameOverLatch.countDown
self.stop
}
- case Latch(latch) =>
+ case Latch(latch) ⇒
gameOverLatch = latch
}
}
class PongActor extends Actor with Serializable {
def receive = {
- case Ball =>
+ case Ball ⇒
self reply Ball
- case Stop =>
+ case Stop ⇒
self reply Stop
self.stop
}
@@ -146,4 +146,4 @@ object ClusteredPingPongSample {
Cluster.shutdownLocalCluster()
}
}
-*/
\ No newline at end of file
+*/
\ No newline at end of file
diff --git a/akka-cluster/src/test/scala/akka/cluster/PingPongMultiJvmExample.scala b/akka-cluster/src/test/scala/akka/cluster/PingPongMultiJvmExample.scala
index aef51de905..4856efd188 100644
--- a/akka-cluster/src/test/scala/akka/cluster/PingPongMultiJvmExample.scala
+++ b/akka-cluster/src/test/scala/akka/cluster/PingPongMultiJvmExample.scala
@@ -7,7 +7,7 @@ package example.cluster
import akka.cluster._
import akka.actor._
-import akka.serialization.{Serializers, SerializerBasedActorFormat}
+import akka.serialization.{ Serializers, SerializerBasedActorFormat }
import akka.util.duration._
object PingPong {
@@ -39,25 +39,25 @@ object PingPong {
var play = true
def receive = {
- case Pong =>
+ case Pong ⇒
if (play) {
println("---->> PING")
pong ! Ping
} else {
println("---->> GAME OVER")
}
- case Serve(player) =>
+ case Serve(player) ⇒
pong = player
println("---->> SERVE")
pong ! Ping
- case Stop =>
+ case Stop ⇒
play = false
}
}
class PongActor extends Actor with Serializable {
def receive = {
- case Ping =>
+ case Ping ⇒
println("---->> PONG")
self reply Pong
}
@@ -239,4 +239,4 @@ class PongNode(number: Int) {
node.stop
}
}
-*/
\ No newline at end of file
+*/
\ No newline at end of file
diff --git a/akka-cluster/src/test/scala/akka/cluster/ReplicationSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ReplicationSpec.scala
index 1120c977ed..42423a3afc 100644
--- a/akka-cluster/src/test/scala/akka/cluster/ReplicationSpec.scala
+++ b/akka-cluster/src/test/scala/akka/cluster/ReplicationSpec.scala
@@ -3,7 +3,7 @@
*/
package akka.cluster
-import org.apache.bookkeeper.client.{BookKeeper, BKException}
+import org.apache.bookkeeper.client.{ BookKeeper, BKException }
import BKException._
import org.apache.zookeeper.server.ZooKeeperServer
@@ -57,10 +57,10 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll
txlog1.close
val txlog2 = TransactionLog.logFor(uuid)
- val entries = txlog2.entriesInRange(0, 1).map(bytes => new String(bytes, "UTF-8"))
- entries.size must equal (2)
- entries(0) must equal ("hello")
- entries(1) must equal ("hello")
+ val entries = txlog2.entriesInRange(0, 1).map(bytes ⇒ new String(bytes, "UTF-8"))
+ entries.size must equal(2)
+ entries(0) must equal("hello")
+ entries(1) must equal("hello")
txlog2.close
}
@@ -75,12 +75,12 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll
txlog1.close
val txlog2 = TransactionLog.logFor(uuid)
- val entries = txlog2.entries.map(bytes => new String(bytes, "UTF-8"))
- entries.size must equal (4)
- entries(0) must equal ("hello")
- entries(1) must equal ("hello")
- entries(2) must equal ("hello")
- entries(3) must equal ("hello")
+ val entries = txlog2.entries.map(bytes ⇒ new String(bytes, "UTF-8"))
+ entries.size must equal(4)
+ entries(0) must equal("hello")
+ entries(1) must equal("hello")
+ entries(2) must equal("hello")
+ entries(3) must equal("hello")
txlog2.close
}
@@ -107,14 +107,14 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll
val txlog2 = TransactionLog.logFor(uuid)
val (snapshotAsBytes, entriesAsBytes) = txlog2.entriesFromLatestSnapshot
- new String(snapshotAsBytes, "UTF-8") must equal ("snapshot")
+ new String(snapshotAsBytes, "UTF-8") must equal("snapshot")
- val entries = entriesAsBytes.map(bytes => new String(bytes, "UTF-8"))
- entries.size must equal (4)
- entries(0) must equal ("hello")
- entries(1) must equal ("hello")
- entries(2) must equal ("hello")
- entries(3) must equal ("hello")
+ val entries = entriesAsBytes.map(bytes ⇒ new String(bytes, "UTF-8"))
+ entries.size must equal(4)
+ entries(0) must equal("hello")
+ entries(1) must equal("hello")
+ entries(2) must equal("hello")
+ entries(3) must equal("hello")
txlog2.close
}
@@ -136,12 +136,12 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll
val txlog2 = TransactionLog.logFor(uuid)
val (snapshotAsBytes, entriesAsBytes) = txlog2.entriesFromLatestSnapshot
- new String(snapshotAsBytes, "UTF-8") must equal ("snapshot")
+ new String(snapshotAsBytes, "UTF-8") must equal("snapshot")
- val entries = entriesAsBytes.map(bytes => new String(bytes, "UTF-8"))
- entries.size must equal (2)
- entries(0) must equal ("hello")
- entries(1) must equal ("hello")
+ val entries = entriesAsBytes.map(bytes ⇒ new String(bytes, "UTF-8"))
+ entries.size must equal(2)
+ entries(0) must equal("hello")
+ entries(1) must equal("hello")
txlog2.close
}
}
@@ -176,10 +176,10 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll
txlog1.close
val txlog2 = TransactionLog.logFor(uuid, true)
- val entries = txlog2.entriesInRange(0, 1).map(bytes => new String(bytes, "UTF-8"))
- entries.size must equal (2)
- entries(0) must equal ("hello")
- entries(1) must equal ("hello")
+ val entries = txlog2.entriesInRange(0, 1).map(bytes ⇒ new String(bytes, "UTF-8"))
+ entries.size must equal(2)
+ entries(0) must equal("hello")
+ entries(1) must equal("hello")
Thread.sleep(100)
txlog2.close
}
@@ -196,12 +196,12 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll
txlog1.close
val txlog2 = TransactionLog.logFor(uuid, true)
- val entries = txlog2.entries.map(bytes => new String(bytes, "UTF-8"))
- entries.size must equal (4)
- entries(0) must equal ("hello")
- entries(1) must equal ("hello")
- entries(2) must equal ("hello")
- entries(3) must equal ("hello")
+ val entries = txlog2.entries.map(bytes ⇒ new String(bytes, "UTF-8"))
+ entries.size must equal(4)
+ entries(0) must equal("hello")
+ entries(1) must equal("hello")
+ entries(2) must equal("hello")
+ entries(3) must equal("hello")
Thread.sleep(100)
txlog2.close
}
@@ -231,14 +231,14 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll
val txlog2 = TransactionLog.logFor(uuid, true)
val (snapshotAsBytes, entriesAsBytes) = txlog2.entriesFromLatestSnapshot
- new String(snapshotAsBytes, "UTF-8") must equal ("snapshot")
+ new String(snapshotAsBytes, "UTF-8") must equal("snapshot")
- val entries = entriesAsBytes.map(bytes => new String(bytes, "UTF-8"))
- entries.size must equal (4)
- entries(0) must equal ("hello")
- entries(1) must equal ("hello")
- entries(2) must equal ("hello")
- entries(3) must equal ("hello")
+ val entries = entriesAsBytes.map(bytes ⇒ new String(bytes, "UTF-8"))
+ entries.size must equal(4)
+ entries(0) must equal("hello")
+ entries(1) must equal("hello")
+ entries(2) must equal("hello")
+ entries(3) must equal("hello")
Thread.sleep(100)
txlog2.close
}
@@ -260,11 +260,11 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll
val txlog2 = TransactionLog.logFor(uuid, true)
val (snapshotAsBytes, entriesAsBytes) = txlog2.entriesFromLatestSnapshot
- new String(snapshotAsBytes, "UTF-8") must equal ("snapshot")
- val entries = entriesAsBytes.map(bytes => new String(bytes, "UTF-8"))
- entries.size must equal (2)
- entries(0) must equal ("hello")
- entries(1) must equal ("hello")
+ new String(snapshotAsBytes, "UTF-8") must equal("snapshot")
+ val entries = entriesAsBytes.map(bytes ⇒ new String(bytes, "UTF-8"))
+ entries.size must equal(2)
+ entries(0) must equal("hello")
+ entries(1) must equal("hello")
Thread.sleep(100)
txlog2.close
}
diff --git a/akka-http/src/main/scala/akka/http/AkkaRestServlet.scala b/akka-http/src/main/scala/akka/http/AkkaRestServlet.scala
index e91cf2690a..79b5337f93 100644
--- a/akka-http/src/main/scala/akka/http/AkkaRestServlet.scala
+++ b/akka-http/src/main/scala/akka/http/AkkaRestServlet.scala
@@ -10,29 +10,29 @@ import com.sun.jersey.spi.container.servlet.ServletContainer
* If you were using akka.comet.AkkaServlet before, but only use it for Jersey, you should switch to this servlet instead
*/
class AkkaRestServlet extends ServletContainer {
- import akka.config.Config.{config => c}
+ import akka.config.Config.{ config ⇒ c }
- val initParams = new java.util.HashMap[String,String]
+ val initParams = new java.util.HashMap[String, String]
- addInitParameter("com.sun.jersey.config.property.packages", c.getList("akka.http.resource-packages").mkString(";"))
- addInitParameter("com.sun.jersey.spi.container.ResourceFilters",c.getList("akka.http.filters").mkString(","))
+ addInitParameter("com.sun.jersey.config.property.packages", c.getList("akka.http.resource-packages").mkString(";"))
+ addInitParameter("com.sun.jersey.spi.container.ResourceFilters", c.getList("akka.http.filters").mkString(","))
-/**
- * Provide a fallback for default values
- */
- override def getInitParameter(key : String) =
- Option(super.getInitParameter(key)).getOrElse(initParams get key)
+ /**
+ * Provide a fallback for default values
+ */
+ override def getInitParameter(key: String) =
+ Option(super.getInitParameter(key)).getOrElse(initParams get key)
-/**
- * Provide a fallback for default values
- */
- override def getInitParameterNames() = {
- import scala.collection.JavaConversions._
- initParams.keySet.iterator ++ super.getInitParameterNames
- }
+ /**
+ * Provide a fallback for default values
+ */
+ override def getInitParameterNames() = {
+ import scala.collection.JavaConversions._
+ initParams.keySet.iterator ++ super.getInitParameterNames
+ }
- /**
- * Provide possibility to add config params
- */
- def addInitParameter(param: String, value: String): Unit = initParams.put(param,value)
+ /**
+ * Provide possibility to add config params
+ */
+ def addInitParameter(param: String, value: String): Unit = initParams.put(param, value)
}
diff --git a/akka-http/src/main/scala/akka/http/JettyContinuation.scala b/akka-http/src/main/scala/akka/http/JettyContinuation.scala
index 9c02cf03ff..7a0e6febac 100644
--- a/akka-http/src/main/scala/akka/http/JettyContinuation.scala
+++ b/akka-http/src/main/scala/akka/http/JettyContinuation.scala
@@ -10,7 +10,6 @@ import org.eclipse.jetty.server._
import org.eclipse.jetty.continuation._
import Types._
-
/**
* @author Garrick Evans
*/
@@ -18,22 +17,22 @@ trait JettyContinuation extends ContinuationListener {
import javax.servlet.http.HttpServletResponse
import MistSettings._
- val builder:() => tAsyncRequestContext
+ val builder: () ⇒ tAsyncRequestContext
val context: Option[tAsyncRequestContext] = Some(builder())
def go = _continuation.isDefined
- protected val _continuation:Option[AsyncContinuation] = {
+ protected val _continuation: Option[AsyncContinuation] = {
val continuation = context.get.asInstanceOf[AsyncContinuation]
(continuation.isInitial,
- continuation.isSuspended,
- continuation.isExpired) match {
+ continuation.isSuspended,
+ continuation.isExpired) match {
//
// the fresh continuation (coming through getAsyncContinuation)
//
- case (true, false, false) => {
+ case (true, false, false) ⇒ {
continuation.setTimeout(DefaultTimeout)
continuation.addContinuationListener(this)
@@ -44,7 +43,7 @@ trait JettyContinuation extends ContinuationListener {
//
// the fresh continuation (coming through startAsync instead)
//
- case (true, true, false) => {
+ case (true, true, false) ⇒ {
continuation.setTimeout(DefaultTimeout)
continuation.addContinuationListener(this)
@@ -55,7 +54,7 @@ trait JettyContinuation extends ContinuationListener {
// the timeout was reset and the continuation was resumed
// this happens when used with getAsyncContinuation
//
- case (false, false, false) => {
+ case (false, false, false) ⇒ {
continuation.setTimeout(continuation.getAttribute(TimeoutAttribute).asInstanceOf[Long])
continuation.suspend
@@ -67,7 +66,7 @@ trait JettyContinuation extends ContinuationListener {
// the timeout was reset and the continuation is still suspended
// this happens when used with startAsync
//
- case (false, true, false) => {
+ case (false, true, false) ⇒ {
continuation.setTimeout(continuation.getAttribute(TimeoutAttribute).asInstanceOf[Long])
continuation.removeAttribute(TimeoutAttribute)
@@ -77,21 +76,21 @@ trait JettyContinuation extends ContinuationListener {
//
// unexpected continution state(s) - log and do nothing
//
- case _ => {
+ case _ ⇒ {
//continuation.cancel
None
}
- }
+ }
}
- def suspended:Boolean = _continuation match {
- case None => false
- case Some(continuation) => (continuation.isSuspended || (continuation.getAttribute(TimeoutAttribute) ne null))
+ def suspended: Boolean = _continuation match {
+ case None ⇒ false
+ case Some(continuation) ⇒ (continuation.isSuspended || (continuation.getAttribute(TimeoutAttribute) ne null))
}
- def timeout(ms:Long):Boolean = _continuation match {
- case None => false
- case Some(continuation) =>
+ def timeout(ms: Long): Boolean = _continuation match {
+ case None ⇒ false
+ case Some(continuation) ⇒
continuation.setAttribute(TimeoutAttribute, ms)
continuation.resume
true
@@ -108,13 +107,12 @@ trait JettyContinuation extends ContinuationListener {
}
object JettyContinuationMethodFactory extends RequestMethodFactory {
- def Delete(f: () => tAsyncRequestContext): RequestMethod = new Delete(f) with JettyContinuation
- def Get(f: () => tAsyncRequestContext): RequestMethod = new Get(f) with JettyContinuation
- def Head(f: () => tAsyncRequestContext): RequestMethod = new Head(f) with JettyContinuation
- def Options(f: () => tAsyncRequestContext): RequestMethod = new Options(f) with JettyContinuation
- def Post(f: () => tAsyncRequestContext): RequestMethod = new Post(f) with JettyContinuation
- def Put(f: () => tAsyncRequestContext): RequestMethod = new Put(f) with JettyContinuation
- def Trace(f: () => tAsyncRequestContext): RequestMethod = new Trace(f) with JettyContinuation
+ def Delete(f: () ⇒ tAsyncRequestContext): RequestMethod = new Delete(f) with JettyContinuation
+ def Get(f: () ⇒ tAsyncRequestContext): RequestMethod = new Get(f) with JettyContinuation
+ def Head(f: () ⇒ tAsyncRequestContext): RequestMethod = new Head(f) with JettyContinuation
+ def Options(f: () ⇒ tAsyncRequestContext): RequestMethod = new Options(f) with JettyContinuation
+ def Post(f: () ⇒ tAsyncRequestContext): RequestMethod = new Post(f) with JettyContinuation
+ def Put(f: () ⇒ tAsyncRequestContext): RequestMethod = new Put(f) with JettyContinuation
+ def Trace(f: () ⇒ tAsyncRequestContext): RequestMethod = new Trace(f) with JettyContinuation
}
-
diff --git a/akka-http/src/main/scala/akka/http/Mist.scala b/akka-http/src/main/scala/akka/http/Mist.scala
index 1425a8ac81..d2771e8e4c 100644
--- a/akka-http/src/main/scala/akka/http/Mist.scala
+++ b/akka-http/src/main/scala/akka/http/Mist.scala
@@ -4,11 +4,11 @@
package akka.http
-import akka.actor.{ActorRef, Actor}
+import akka.actor.{ ActorRef, Actor }
import akka.event.EventHandler
import akka.config.ConfigurationException
-import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
+import javax.servlet.http.{ HttpServletResponse, HttpServletRequest }
import javax.servlet.http.HttpServlet
import javax.servlet.Filter
@@ -18,14 +18,14 @@ import javax.servlet.Filter
object MistSettings {
import akka.config.Config._
- val JettyServer = "jetty"
+ val JettyServer = "jetty"
val TimeoutAttribute = "timeout"
- val ConnectionClose = config.getBool("akka.http.connection-close", true)
- val RootActorBuiltin = config.getBool("akka.http.root-actor-builtin", true)
- val RootActorID = config.getString("akka.http.root-actor-id", "_httproot")
- val DefaultTimeout = config.getLong("akka.http.timeout", 1000)
- val ExpiredHeaderName = config.getString("akka.http.expired-header-name", "Async-Timeout")
+ val ConnectionClose = config.getBool("akka.http.connection-close", true)
+ val RootActorBuiltin = config.getBool("akka.http.root-actor-builtin", true)
+ val RootActorID = config.getString("akka.http.root-actor-id", "_httproot")
+ val DefaultTimeout = config.getLong("akka.http.timeout", 1000)
+ val ExpiredHeaderName = config.getString("akka.http.expired-header-name", "Async-Timeout")
val ExpiredHeaderValue = config.getString("akka.http.expired-header-value", "expired")
}
@@ -35,7 +35,7 @@ object MistSettings {
* @author Garrick Evans
*/
object Types {
- import javax.servlet. {ServletRequest, ServletResponse}
+ import javax.servlet.{ ServletRequest, ServletResponse }
/**
* Represents an asynchronous request
@@ -53,7 +53,7 @@ object Types {
def getResponse: ServletResponse
}
- type Header = Tuple2[String,String]
+ type Header = Tuple2[String, String]
type Headers = List[Header]
def Headers(): Headers = Nil
@@ -83,8 +83,7 @@ trait Mist {
* Handles all servlet requests
*/
protected def mistify(request: HttpServletRequest,
- response: HttpServletResponse)
- (builder: (() => tAsyncRequestContext) => RequestMethod) = {
+ response: HttpServletResponse)(builder: (() ⇒ tAsyncRequestContext) ⇒ RequestMethod) = {
def suspend: tAsyncRequestContext = {
// set to right now, which is effectively "already expired"
@@ -92,15 +91,15 @@ trait Mist {
response.setHeader("Cache-Control", "no-cache, must-revalidate")
// no keep-alive?
- if (ConnectionClose) response.setHeader("Connection","close")
+ if (ConnectionClose) response.setHeader("Connection", "close")
// suspend the request
// TODO: move this out to the specialized support if jetty asyncstart doesnt let us update TOs
request.asInstanceOf[tAsyncRequest].startAsync.asInstanceOf[tAsyncRequestContext]
}
- // shoot the message to the root endpoint for processing
- // IMPORTANT: the suspend method is invoked on the server thread not in the actor
+ // shoot the message to the root endpoint for processing
+ // IMPORTANT: the suspend method is invoked on the server thread not in the actor
val method = builder(suspend _)
if (method.go) _root ! method
}
@@ -127,7 +126,7 @@ trait Mist {
* Async impls currently supported: Servlet3.0, Jetty Continuations
*/
class AkkaMistServlet extends HttpServlet with Mist {
- import javax.servlet.{ServletConfig}
+ import javax.servlet.{ ServletConfig }
/**
* Initializes Mist
@@ -137,13 +136,13 @@ class AkkaMistServlet extends HttpServlet with Mist {
initMist(config.getServletContext)
}
- protected override def doDelete(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res)(_factory.get.Delete)
- protected override def doGet(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res)(_factory.get.Get)
- protected override def doHead(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res)(_factory.get.Head)
+ protected override def doDelete(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res)(_factory.get.Delete)
+ protected override def doGet(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res)(_factory.get.Get)
+ protected override def doHead(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res)(_factory.get.Head)
protected override def doOptions(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res)(_factory.get.Options)
- protected override def doPost(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res)(_factory.get.Post)
- protected override def doPut(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res)(_factory.get.Put)
- protected override def doTrace(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res)(_factory.get.Trace)
+ protected override def doPost(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res)(_factory.get.Post)
+ protected override def doPut(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res)(_factory.get.Put)
+ protected override def doTrace(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res)(_factory.get.Trace)
}
/**
@@ -151,7 +150,7 @@ class AkkaMistServlet extends HttpServlet with Mist {
* Will be officially supported in a later release
*/
class AkkaMistFilter extends Filter with Mist {
- import javax.servlet.{ServletRequest, ServletResponse, FilterConfig, FilterChain}
+ import javax.servlet.{ ServletRequest, ServletResponse, FilterConfig, FilterChain }
/**
* Initializes Mist
@@ -164,20 +163,20 @@ class AkkaMistFilter extends Filter with Mist {
* Decide how/if to handle the request
*/
override def doFilter(req: ServletRequest, res: ServletResponse, chain: FilterChain) {
- (req,res) match {
- case (hreq: HttpServletRequest, hres: HttpServletResponse) =>
+ (req, res) match {
+ case (hreq: HttpServletRequest, hres: HttpServletResponse) ⇒
hreq.getMethod.toUpperCase match {
- case "DELETE" => mistify(hreq, hres)(_factory.get.Delete)
- case "GET" => mistify(hreq, hres)(_factory.get.Get)
- case "HEAD" => mistify(hreq, hres)(_factory.get.Head)
- case "OPTIONS" => mistify(hreq, hres)(_factory.get.Options)
- case "POST" => mistify(hreq, hres)(_factory.get.Post)
- case "PUT" => mistify(hreq, hres)(_factory.get.Put)
- case "TRACE" => mistify(hreq, hres)(_factory.get.Trace)
- case unknown => {}
+ case "DELETE" ⇒ mistify(hreq, hres)(_factory.get.Delete)
+ case "GET" ⇒ mistify(hreq, hres)(_factory.get.Get)
+ case "HEAD" ⇒ mistify(hreq, hres)(_factory.get.Head)
+ case "OPTIONS" ⇒ mistify(hreq, hres)(_factory.get.Options)
+ case "POST" ⇒ mistify(hreq, hres)(_factory.get.Post)
+ case "PUT" ⇒ mistify(hreq, hres)(_factory.get.Put)
+ case "TRACE" ⇒ mistify(hreq, hres)(_factory.get.Trace)
+ case unknown ⇒ {}
}
- chain.doFilter(req,res)
- case _ => chain.doFilter(req,res)
+ chain.doFilter(req, res)
+ case _ ⇒ chain.doFilter(req, res)
}
}
@@ -196,7 +195,7 @@ object Endpoint {
*/
val Dispatcher = Dispatchers.fromConfig("akka.http.mist-dispatcher")
- type Hook = Function[String, Boolean]
+ type Hook = Function[String, Boolean]
type Provider = Function[String, ActorRef]
case class Attach(hook: Hook, provider: Provider)
@@ -206,7 +205,7 @@ object Endpoint {
/**
* @author Garrick Evans
*/
-trait Endpoint { this: Actor =>
+trait Endpoint { this: Actor ⇒
import Endpoint._
@@ -224,7 +223,7 @@ trait Endpoint { this: Actor =>
/**
*
*/
- protected def _attach(hook:Hook, provider:Provider) = _attachments = (hook, provider) :: _attachments
+ protected def _attach(hook: Hook, provider: Provider) = _attachments = (hook, provider) :: _attachments
/**
* Message handling common to all endpoints, must be chained
@@ -233,18 +232,18 @@ trait Endpoint { this: Actor =>
// add the endpoint - the if the uri hook matches,
// the message will be sent to the actor returned by the provider func
- case Attach(hook, provider) => _attach(hook, provider)
+ case Attach(hook, provider) ⇒ _attach(hook, provider)
// dispatch the suspended requests
- case req: RequestMethod => {
+ case req: RequestMethod ⇒ {
val uri = req.request.getPathInfo
val endpoints = _attachments.filter { _._1(uri) }
if (!endpoints.isEmpty) endpoints.foreach { _._2(uri) ! req }
else {
self.sender match {
- case Some(s) => s reply NoneAvailable(uri, req)
- case None => _na(uri, req)
+ case Some(s) ⇒ s reply NoneAvailable(uri, req)
+ case None ⇒ _na(uri, req)
}
}
}
@@ -258,7 +257,6 @@ trait Endpoint { this: Actor =>
}
}
-
class RootEndpoint extends Actor with Endpoint {
import Endpoint._
import MistSettings._
@@ -269,11 +267,11 @@ class RootEndpoint extends Actor with Endpoint {
self.dispatcher = Endpoint.Dispatcher
override def preStart() =
- _attachments = Tuple2((uri: String) => {uri eq Root}, (uri: String) => this.actor) :: _attachments
+ _attachments = Tuple2((uri: String) ⇒ { uri eq Root }, (uri: String) ⇒ this.actor) :: _attachments
def recv: Receive = {
- case NoneAvailable(uri, req) => _na(uri, req)
- case unknown => {}
+ case NoneAvailable(uri, req) ⇒ _na(uri, req)
+ case unknown ⇒ {}
}
/**
@@ -294,10 +292,10 @@ class RootEndpoint extends Actor with Endpoint {
*/
trait RequestMethod {
import java.io.IOException
- import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
+ import javax.servlet.http.{ HttpServletResponse, HttpServletRequest }
// required implementations
- val builder: () => tAsyncRequestContext
+ val builder: () ⇒ tAsyncRequestContext
/**
* Provides a general type for the underlying context
@@ -305,7 +303,7 @@ trait RequestMethod {
* @return a completable request context
*/
val context: Option[tAsyncRequestContext]
- def go:Boolean
+ def go: Boolean
/**
* Updates (resets) the timeout
@@ -328,30 +326,30 @@ trait RequestMethod {
def getHeaderOrElse(name: String, default: Function[Any, String]): String =
request.getHeader(name) match {
- case null => default(null)
- case s => s
+ case null ⇒ default(null)
+ case s ⇒ s
}
def getParameterOrElse(name: String, default: Function[Any, String]): String =
request.getParameter(name) match {
- case null => default(null)
- case s => s
+ case null ⇒ default(null)
+ case s ⇒ s
}
def complete(status: Int, body: String): Boolean = complete(status, body, Headers())
def complete(status: Int, body: String, headers: Headers): Boolean =
- rawComplete { res =>
+ rawComplete { res ⇒
res.setStatus(status)
- headers foreach {h => response.setHeader(h._1, h._2)}
+ headers foreach { h ⇒ response.setHeader(h._1, h._2) }
res.getWriter.write(body)
res.getWriter.close
res.flushBuffer
}
- def rawComplete(completion: HttpServletResponse => Unit): Boolean =
+ def rawComplete(completion: HttpServletResponse ⇒ Unit): Boolean =
context match {
- case Some(pipe) =>
+ case Some(pipe) ⇒
try {
if (!suspended) false
else {
@@ -360,64 +358,64 @@ trait RequestMethod {
true
}
} catch {
- case io: Exception =>
+ case io: Exception ⇒
EventHandler.error(io, this, io.getMessage)
false
}
- case None => false
- }
+ case None ⇒ false
+ }
def complete(t: Throwable) {
context match {
- case Some(pipe) =>
+ case Some(pipe) ⇒
try {
if (suspended) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to write data to connection on resume")
pipe.complete
}
} catch {
- case io: IOException =>
+ case io: IOException ⇒
EventHandler.error(io, this, io.getMessage)
}
- case None => {}
+ case None ⇒ {}
}
}
/*
* Utility methods to send responses back
*/
- def OK(body: String): Boolean = complete(HttpServletResponse.SC_OK, body)
- def OK(body: String, headers:Headers): Boolean = complete(HttpServletResponse.SC_OK, body, headers)
- def Created(body: String): Boolean = complete(HttpServletResponse.SC_CREATED, body)
- def Accepted(body: String): Boolean = complete(HttpServletResponse.SC_ACCEPTED, body)
- def NotModified(body:String): Boolean = complete(HttpServletResponse.SC_NOT_MODIFIED, body)
- def BadRequest(body: String): Boolean = complete(HttpServletResponse.SC_BAD_REQUEST, body)
- def Unauthorized(body: String): Boolean = complete(HttpServletResponse.SC_UNAUTHORIZED, body)
- def Forbidden(body: String): Boolean = complete(HttpServletResponse.SC_FORBIDDEN, body)
- def NotAllowed(body: String): Boolean = complete(HttpServletResponse.SC_METHOD_NOT_ALLOWED, body)
- def NotFound(body: String): Boolean = complete(HttpServletResponse.SC_NOT_FOUND, body)
- def Timeout(body: String): Boolean = complete(HttpServletResponse.SC_REQUEST_TIMEOUT, body)
- def Conflict(body: String): Boolean = complete(HttpServletResponse.SC_CONFLICT, body)
- def UnsupportedMediaType(body: String): Boolean = complete(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, body)
- def Error(body: String): Boolean = complete(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, body)
- def NotImplemented(body: String): Boolean = complete(HttpServletResponse.SC_NOT_IMPLEMENTED, body)
+ def OK(body: String): Boolean = complete(HttpServletResponse.SC_OK, body)
+ def OK(body: String, headers: Headers): Boolean = complete(HttpServletResponse.SC_OK, body, headers)
+ def Created(body: String): Boolean = complete(HttpServletResponse.SC_CREATED, body)
+ def Accepted(body: String): Boolean = complete(HttpServletResponse.SC_ACCEPTED, body)
+ def NotModified(body: String): Boolean = complete(HttpServletResponse.SC_NOT_MODIFIED, body)
+ def BadRequest(body: String): Boolean = complete(HttpServletResponse.SC_BAD_REQUEST, body)
+ def Unauthorized(body: String): Boolean = complete(HttpServletResponse.SC_UNAUTHORIZED, body)
+ def Forbidden(body: String): Boolean = complete(HttpServletResponse.SC_FORBIDDEN, body)
+ def NotAllowed(body: String): Boolean = complete(HttpServletResponse.SC_METHOD_NOT_ALLOWED, body)
+ def NotFound(body: String): Boolean = complete(HttpServletResponse.SC_NOT_FOUND, body)
+ def Timeout(body: String): Boolean = complete(HttpServletResponse.SC_REQUEST_TIMEOUT, body)
+ def Conflict(body: String): Boolean = complete(HttpServletResponse.SC_CONFLICT, body)
+ def UnsupportedMediaType(body: String): Boolean = complete(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, body)
+ def Error(body: String): Boolean = complete(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, body)
+ def NotImplemented(body: String): Boolean = complete(HttpServletResponse.SC_NOT_IMPLEMENTED, body)
def Unavailable(body: String, retry: Int): Boolean = complete(HttpServletResponse.SC_SERVICE_UNAVAILABLE, body, List(("Retry-After", retry.toString)))
}
-abstract class Delete(val builder: () => tAsyncRequestContext) extends RequestMethod
-abstract class Get(val builder: () => tAsyncRequestContext) extends RequestMethod
-abstract class Head(val builder: () => tAsyncRequestContext) extends RequestMethod
-abstract class Options(val builder: () => tAsyncRequestContext) extends RequestMethod
-abstract class Post(val builder: () => tAsyncRequestContext) extends RequestMethod
-abstract class Put(val builder: () => tAsyncRequestContext) extends RequestMethod
-abstract class Trace(val builder: () => tAsyncRequestContext) extends RequestMethod
+abstract class Delete(val builder: () ⇒ tAsyncRequestContext) extends RequestMethod
+abstract class Get(val builder: () ⇒ tAsyncRequestContext) extends RequestMethod
+abstract class Head(val builder: () ⇒ tAsyncRequestContext) extends RequestMethod
+abstract class Options(val builder: () ⇒ tAsyncRequestContext) extends RequestMethod
+abstract class Post(val builder: () ⇒ tAsyncRequestContext) extends RequestMethod
+abstract class Put(val builder: () ⇒ tAsyncRequestContext) extends RequestMethod
+abstract class Trace(val builder: () ⇒ tAsyncRequestContext) extends RequestMethod
trait RequestMethodFactory {
- def Delete(f: () => tAsyncRequestContext): RequestMethod
- def Get(f: () => tAsyncRequestContext): RequestMethod
- def Head(f: () => tAsyncRequestContext): RequestMethod
- def Options(f: () => tAsyncRequestContext): RequestMethod
- def Post(f: () => tAsyncRequestContext): RequestMethod
- def Put(f: () => tAsyncRequestContext): RequestMethod
- def Trace(f: () => tAsyncRequestContext): RequestMethod
+ def Delete(f: () ⇒ tAsyncRequestContext): RequestMethod
+ def Get(f: () ⇒ tAsyncRequestContext): RequestMethod
+ def Head(f: () ⇒ tAsyncRequestContext): RequestMethod
+ def Options(f: () ⇒ tAsyncRequestContext): RequestMethod
+ def Post(f: () ⇒ tAsyncRequestContext): RequestMethod
+ def Put(f: () ⇒ tAsyncRequestContext): RequestMethod
+ def Trace(f: () ⇒ tAsyncRequestContext): RequestMethod
}
diff --git a/akka-http/src/main/scala/akka/http/Servlet30Context.scala b/akka-http/src/main/scala/akka/http/Servlet30Context.scala
index 19a29f46cc..2d354d9a10 100644
--- a/akka-http/src/main/scala/akka/http/Servlet30Context.scala
+++ b/akka-http/src/main/scala/akka/http/Servlet30Context.scala
@@ -4,7 +4,7 @@
package akka.http
-import javax.servlet. {AsyncContext, AsyncListener, AsyncEvent};
+import javax.servlet.{ AsyncContext, AsyncListener, AsyncEvent };
import Types._
import akka.event.EventHandler
@@ -16,7 +16,7 @@ trait Servlet30Context extends AsyncListener {
import javax.servlet.http.HttpServletResponse
import MistSettings._
- val builder: () => tAsyncRequestContext
+ val builder: () ⇒ tAsyncRequestContext
val context: Option[tAsyncRequestContext] = Some(builder())
def go = context.isDefined
@@ -33,9 +33,8 @@ trait Servlet30Context extends AsyncListener {
try {
_ac setTimeout ms
true
- }
- catch {
- case e: IllegalStateException =>
+ } catch {
+ case e: IllegalStateException ⇒
EventHandler.error(e, this, e.getMessage)
false
}
@@ -46,8 +45,8 @@ trait Servlet30Context extends AsyncListener {
//
def onComplete(e: AsyncEvent) {}
def onError(e: AsyncEvent) = e.getThrowable match {
- case null => {}
- case t => {}
+ case null ⇒ {}
+ case t ⇒ {}
}
def onStartAsync(e: AsyncEvent) {}
def onTimeout(e: AsyncEvent) = {
@@ -57,13 +56,12 @@ trait Servlet30Context extends AsyncListener {
}
object Servlet30ContextMethodFactory extends RequestMethodFactory {
- def Delete(f: () => tAsyncRequestContext): RequestMethod = new Delete(f) with Servlet30Context
- def Get(f: () => tAsyncRequestContext): RequestMethod = new Get(f) with Servlet30Context
- def Head(f: () => tAsyncRequestContext): RequestMethod = new Head(f) with Servlet30Context
- def Options(f: () => tAsyncRequestContext): RequestMethod = new Options(f) with Servlet30Context
- def Post(f: () => tAsyncRequestContext): RequestMethod = new Post(f) with Servlet30Context
- def Put(f: () => tAsyncRequestContext): RequestMethod = new Put(f) with Servlet30Context
- def Trace(f: () => tAsyncRequestContext): RequestMethod = new Trace(f) with Servlet30Context
+ def Delete(f: () ⇒ tAsyncRequestContext): RequestMethod = new Delete(f) with Servlet30Context
+ def Get(f: () ⇒ tAsyncRequestContext): RequestMethod = new Get(f) with Servlet30Context
+ def Head(f: () ⇒ tAsyncRequestContext): RequestMethod = new Head(f) with Servlet30Context
+ def Options(f: () ⇒ tAsyncRequestContext): RequestMethod = new Options(f) with Servlet30Context
+ def Post(f: () ⇒ tAsyncRequestContext): RequestMethod = new Post(f) with Servlet30Context
+ def Put(f: () ⇒ tAsyncRequestContext): RequestMethod = new Put(f) with Servlet30Context
+ def Trace(f: () ⇒ tAsyncRequestContext): RequestMethod = new Trace(f) with Servlet30Context
}
-
diff --git a/akka-http/src/main/scala/akka/security/Security.scala b/akka-http/src/main/scala/akka/security/Security.scala
index fe2033cf4f..969ddeabc2 100644
--- a/akka-http/src/main/scala/akka/security/Security.scala
+++ b/akka-http/src/main/scala/akka/security/Security.scala
@@ -22,18 +22,18 @@
package akka.security
-import akka.actor.{Scheduler, Actor, ActorRef, IllegalActorStateException}
+import akka.actor.{ Scheduler, Actor, ActorRef, IllegalActorStateException }
import akka.event.EventHandler
import akka.actor.Actor._
-import akka.config.{Config, ConfigurationException}
+import akka.config.{ Config, ConfigurationException }
import com.sun.jersey.api.model.AbstractMethod
-import com.sun.jersey.spi.container.{ResourceFilterFactory, ContainerRequest, ContainerRequestFilter, ContainerResponse, ContainerResponseFilter, ResourceFilter}
+import com.sun.jersey.spi.container.{ ResourceFilterFactory, ContainerRequest, ContainerRequestFilter, ContainerResponse, ContainerResponseFilter, ResourceFilter }
import com.sun.jersey.core.util.Base64
-import javax.ws.rs.core.{SecurityContext, Context, Response}
+import javax.ws.rs.core.{ SecurityContext, Context, Response }
import javax.ws.rs.WebApplicationException
-import javax.annotation.security.{DenyAll, PermitAll, RolesAllowed}
+import javax.annotation.security.{ DenyAll, PermitAll, RolesAllowed }
import java.security.Principal
import java.util.concurrent.TimeUnit
@@ -71,7 +71,7 @@ case class SpnegoCredentials(token: Array[Byte]) extends Credentials
*/
class AkkaSecurityFilterFactory extends ResourceFilterFactory {
class Filter(actor: ActorRef, rolesAllowed: Option[List[String]])
- extends ResourceFilter with ContainerRequestFilter {
+ extends ResourceFilter with ContainerRequestFilter {
override def getRequestFilter: ContainerRequestFilter = this
@@ -83,19 +83,19 @@ class AkkaSecurityFilterFactory extends ResourceFilterFactory {
*/
override def filter(request: ContainerRequest): ContainerRequest =
rolesAllowed match {
- case Some(roles) => {
+ case Some(roles) ⇒ {
val result = (authenticator !! Authenticate(request, roles)).as[AnyRef]
result match {
- case Some(OK) => request
- case Some(r) if r.isInstanceOf[Response] =>
+ case Some(OK) ⇒ request
+ case Some(r) if r.isInstanceOf[Response] ⇒
throw new WebApplicationException(r.asInstanceOf[Response])
- case None => throw new WebApplicationException(408)
- case unknown => {
+ case None ⇒ throw new WebApplicationException(408)
+ case unknown ⇒ {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR)
}
}
}
- case None => throw new WebApplicationException(Response.Status.FORBIDDEN)
+ case None ⇒ throw new WebApplicationException(Response.Status.FORBIDDEN)
}
}
@@ -110,8 +110,8 @@ class AkkaSecurityFilterFactory extends ResourceFilterFactory {
* strategy could be implemented in the future
*/
def authenticator: ActorRef = Actor.registry.actorFor(authenticatorFQN)
- .getOrElse(throw new ConfigurationException(
- "akka.http.authenticator configuration option does not have a valid actor address [" + authenticatorFQN + "]"))
+ .getOrElse(throw new ConfigurationException(
+ "akka.http.authenticator configuration option does not have a valid actor address [" + authenticatorFQN + "]"))
def mkFilter(roles: Option[List[String]]): java.util.List[ResourceFilter] =
java.util.Collections.singletonList(new Filter(authenticator, roles))
@@ -170,7 +170,7 @@ trait AuthenticationActor[C <: Credentials] extends Actor {
//This is the default security context factory
def mkDefaultSecurityContext(r: Req, u: UserInfo, scheme: String): SecurityContext = {
val n = u.username
- val p = new Principal {def getName = n}
+ val p = new Principal { def getName = n }
new SecurityContext {
def getAuthenticationScheme = scheme
@@ -188,14 +188,14 @@ trait AuthenticationActor[C <: Credentials] extends Actor {
* this should ensure good integration with current Jersey security
*/
protected val authenticate: Receive = {
- case Authenticate(req, roles) => {
+ case Authenticate(req, roles) ⇒ {
verify(extractCredentials(req)) match {
- case Some(u: UserInfo) => {
+ case Some(u: UserInfo) ⇒ {
req.setSecurityContext(mkSecurityContext(req, u))
if (roles.exists(req.isUserInRole(_))) self.reply(OK)
else self.reply(Response.status(Response.Status.FORBIDDEN).build)
}
- case _ => self.reply(unauthorized)
+ case _ ⇒ self.reply(unauthorized)
}
}
}
@@ -225,14 +225,14 @@ trait BasicAuthenticationActor extends AuthenticationActor[BasicCredentials] {
val Authorization = """(.*):(.*)""".r
authOption(r) match {
- case Some(token) => {
+ case Some(token) ⇒ {
val authResponse = new String(Base64.decode(token.substring(6).getBytes))
authResponse match {
- case Authorization(username, password) => Some(BasicCredentials(username, password))
- case _ => None
+ case Authorization(username, password) ⇒ Some(BasicCredentials(username, password))
+ case _ ⇒ None
}
}
- case _ => None
+ case _ ⇒ None
}
}
@@ -255,10 +255,10 @@ trait DigestAuthenticationActor extends AuthenticationActor[DigestCredentials] {
//Discards old nonces
protected val invalidateNonces: Receive = {
- case InvalidateNonces =>
+ case InvalidateNonces ⇒
val ts = System.currentTimeMillis
- nonceMap.filter(tuple => (ts - tuple._2) < nonceValidityPeriod)
- case unknown => {}
+ nonceMap.filter(tuple ⇒ (ts - tuple._2) < nonceValidityPeriod)
+ case unknown ⇒ {}
}
//Schedule the invalidation of nonces
@@ -277,9 +277,9 @@ trait DigestAuthenticationActor extends AuthenticationActor[DigestCredentials] {
Response.status(401).header(
"WWW-Authenticate",
"Digest realm=\"" + realm + "\", " +
- "qop=\"" + qop + "\", " +
- "nonce=\"" + nonce + "\", " +
- "opaque=\"" + opaque + "\"").build
+ "qop=\"" + qop + "\", " +
+ "nonce=\"" + nonce + "\", " +
+ "opaque=\"" + opaque + "\"").build
}
//Tests wether the specified credentials are valid
@@ -291,25 +291,25 @@ trait DigestAuthenticationActor extends AuthenticationActor[DigestCredentials] {
val response = h(
ha1 + ":" + auth.nonce + ":" +
- auth.nc + ":" + auth.cnonce + ":" +
- auth.qop + ":" + ha2)
+ auth.nc + ":" + auth.cnonce + ":" +
+ auth.qop + ":" + ha2)
(response == auth.response) && (nonceMap.getOrElse(auth.nonce, -1) != -1)
}
override def verify(odc: Option[DigestCredentials]): Option[UserInfo] = odc match {
- case Some(dc) => {
+ case Some(dc) ⇒ {
userInfo(dc.userName) match {
- case Some(u) if validate(dc, u) =>
- nonceMap.get(dc.nonce).map(t => (System.currentTimeMillis - t) < nonceValidityPeriod).map(_ => u)
- case _ => None
+ case Some(u) if validate(dc, u) ⇒
+ nonceMap.get(dc.nonce).map(t ⇒ (System.currentTimeMillis - t) < nonceValidityPeriod).map(_ ⇒ u)
+ case _ ⇒ None
}
}
- case _ => None
+ case _ ⇒ None
}
override def extractCredentials(r: Req): Option[DigestCredentials] = {
- authOption(r).map(s => {
+ authOption(r).map(s ⇒ {
val ? = splitNameValuePairs(s.substring(7, s.length))
DigestCredentials(r.getMethod.toUpperCase,
?("username"), ?("realm"), ?("nonce"),
@@ -356,27 +356,26 @@ trait SpnegoAuthenticationActor extends AuthenticationActor[SpnegoCredentials] {
val AuthHeader = """Negotiate\s(.*)""".r
authOption(r) match {
- case Some(AuthHeader(token)) =>
+ case Some(AuthHeader(token)) ⇒
Some(SpnegoCredentials(Base64.decodeBase64(token.trim.getBytes)))
- case _ => None
+ case _ ⇒ None
}
}
-
override def verify(odc: Option[SpnegoCredentials]): Option[UserInfo] = odc match {
- case Some(dc) => {
+ case Some(dc) ⇒ {
try {
val principal = Subject.doAs(this.serviceSubject, new KerberosValidateAction(dc.token));
val user = stripRealmFrom(principal)
Some(UserInfo(user, null, rolesFor(user)))
} catch {
- case e: PrivilegedActionException => {
+ case e: PrivilegedActionException ⇒ {
EventHandler.error(e, this, e.getMessage)
None
}
}
}
- case _ => None
+ case _ ⇒ None
}
override def mkSecurityContext(r: Req, u: UserInfo): SecurityContext =
@@ -496,24 +495,24 @@ trait SpnegoAuthenticationActor extends AuthenticationActor[SpnegoCredentials] {
* limitations under the License.
*/
object LiftUtils {
- import java.security.{MessageDigest,SecureRandom}
+ import java.security.{ MessageDigest, SecureRandom }
val random = new SecureRandom()
def md5(in: Array[Byte]): Array[Byte] = (MessageDigest.getInstance("MD5")).digest(in)
/**
- * Create a random string of a given size
- * @param size size of the string to create. Must be a positive or nul integer
- * @return the generated string
- */
+ * Create a random string of a given size
+ * @param size size of the string to create. Must be a positive or nul integer
+ * @return the generated string
+ */
def randomString(size: Int): String = {
def addChar(pos: Int, lastRand: Int, sb: StringBuilder): StringBuilder = {
if (pos >= size) sb
else {
val randNum = if ((pos % 6) == 0) random.nextInt else lastRand
sb.append((randNum & 0x1f) match {
- case n if n < 26 => ('A' + n).toChar
- case n => ('0' + (n - 26)).toChar
+ case n if n < 26 ⇒ ('A' + n).toChar
+ case n ⇒ ('0' + (n - 26)).toChar
})
addChar(pos + 1, randNum >> 5, sb)
}
@@ -521,7 +520,7 @@ object LiftUtils {
addChar(0, 0, new StringBuilder(size)).toString
}
-/** encode a Byte array as hexadecimal characters */
+ /** encode a Byte array as hexadecimal characters */
def hexEncode(in: Array[Byte]): String = {
val sb = new StringBuilder
val len = in.length
@@ -539,15 +538,14 @@ object LiftUtils {
sb.toString
}
-
- /**
- * Splits a string of the form <name1=value1, name2=value2, ... > and unquotes the quoted values.
- * The result is a Map[String, String]
- */
+ /**
+ * Splits a string of the form <name1=value1, name2=value2, ... > and unquotes the quoted values.
+ * The result is a Map[String, String]
+ */
def splitNameValuePairs(props: String): Map[String, String] = {
- /**
- * If str is surrounded by quotes it return the content between the quotes
- */
+ /**
+ * If str is surrounded by quotes it return the content between the quotes
+ */
def unquote(str: String) = {
if ((str ne null) && str.length >= 2 && str.charAt(0) == '\"' && str.charAt(str.length - 1) == '\"')
str.substring(1, str.length - 1)
@@ -555,11 +553,11 @@ object LiftUtils {
str
}
- val list = props.split(",").toList.map(in => {
- val pair = in match { case null => Nil case s => s.split("=").toList.map(_.trim).filter(_.length > 0) }
- (pair(0), unquote(pair(1)))
+ val list = props.split(",").toList.map(in ⇒ {
+ val pair = in match { case null ⇒ Nil case s ⇒ s.split("=").toList.map(_.trim).filter(_.length > 0) }
+ (pair(0), unquote(pair(1)))
})
val map: Map[String, String] = Map.empty
- (map /: list)((m, next) => m + (next))
+ (map /: list)((m, next) ⇒ m + (next))
}
}
diff --git a/akka-http/src/test/scala/SecuritySpec.scala b/akka-http/src/test/scala/SecuritySpec.scala
index 4b7c7767be..edf7b2bac0 100644
--- a/akka-http/src/test/scala/SecuritySpec.scala
+++ b/akka-http/src/test/scala/SecuritySpec.scala
@@ -13,30 +13,31 @@ import org.scalatest.matchers.MustMatchers
import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito._
import org.mockito.Matchers._
-import org.junit.{Before, After, Test}
+import org.junit.{ Before, After, Test }
-import javax.ws.rs.core.{SecurityContext, Context, Response}
-import com.sun.jersey.spi.container.{ResourceFilterFactory, ContainerRequest, ContainerRequestFilter, ContainerResponse, ContainerResponseFilter, ResourceFilter}
+import javax.ws.rs.core.{ SecurityContext, Context, Response }
+import com.sun.jersey.spi.container.{ ResourceFilterFactory, ContainerRequest, ContainerRequestFilter, ContainerResponse, ContainerResponseFilter, ResourceFilter }
import com.sun.jersey.core.util.Base64
object BasicAuthenticatorSpec {
class BasicAuthenticator extends BasicAuthenticationActor {
def verify(odc: Option[BasicCredentials]): Option[UserInfo] = odc match {
- case Some(dc) => Some(UserInfo("foo", "bar", "ninja" :: "chef" :: Nil))
- case _ => None
+ case Some(dc) ⇒ Some(UserInfo("foo", "bar", "ninja" :: "chef" :: Nil))
+ case _ ⇒ None
}
override def realm = "test"
}
}
class BasicAuthenticatorSpec extends junit.framework.TestCase
- with Suite with MockitoSugar with MustMatchers {
+ with Suite with MockitoSugar with MustMatchers {
import BasicAuthenticatorSpec._
val authenticator = actorOf[BasicAuthenticator]
authenticator.start()
- @Test def testChallenge = {
+ @Test
+ def testChallenge = {
val req = mock[ContainerRequest]
val result = (authenticator !! (Authenticate(req, List("foo")), 10000)).as[Response].get
@@ -46,7 +47,8 @@ class BasicAuthenticatorSpec extends junit.framework.TestCase
result.getMetadata.get("WWW-Authenticate").get(0).toString must startWith("Basic")
}
- @Test def testAuthenticationSuccess = {
+ @Test
+ def testAuthenticationSuccess = {
val req = mock[ContainerRequest]
// fake a basic auth header -> this will authenticate the user
when(req.getHeaderValue("Authorization")).thenReturn("Basic " + new String(Base64.encode("foo:bar")))
@@ -61,7 +63,8 @@ class BasicAuthenticatorSpec extends junit.framework.TestCase
verify(req).setSecurityContext(any[SecurityContext])
}
- @Test def testUnauthorized = {
+ @Test
+ def testUnauthorized = {
val req = mock[ContainerRequest]
// fake a basic auth header -> this will authenticate the user
diff --git a/akka-remote/src/main/scala/akka/remote/BootableRemoteActorService.scala b/akka-remote/src/main/scala/akka/remote/BootableRemoteActorService.scala
index 04662ca8af..1faf71bffc 100644
--- a/akka-remote/src/main/scala/akka/remote/BootableRemoteActorService.scala
+++ b/akka-remote/src/main/scala/akka/remote/BootableRemoteActorService.scala
@@ -4,8 +4,8 @@
package akka.remote
-import akka.actor. {Actor, BootableActorLoaderService}
-import akka.util. {ReflectiveAccess, Bootable}
+import akka.actor.{ Actor, BootableActorLoaderService }
+import akka.util.{ ReflectiveAccess, Bootable }
/**
* This bundle/service is responsible for booting up and shutting down the remote actors facility
@@ -13,7 +13,7 @@ import akka.util. {ReflectiveAccess, Bootable}
* It is used in Kernel
*/
trait BootableRemoteActorService extends Bootable {
- self: BootableActorLoaderService =>
+ self: BootableActorLoaderService ⇒
protected lazy val remoteServerThread = new Thread(new Runnable() {
def run = Actor.remote.start(self.applicationLoader.getOrElse(null)) //Use config host/port
diff --git a/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala b/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala
index 6da0004bab..98bf8400cf 100644
--- a/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala
+++ b/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala
@@ -4,40 +4,40 @@
package akka.remote
-import akka.serialization.{Serializers, Serializable}
+import akka.serialization.{ Serializers, Serializable }
import akka.remote.protocol.RemoteProtocol._
import akka.util._
-import com.google.protobuf.{Message, ByteString}
+import com.google.protobuf.{ Message, ByteString }
object MessageSerializer {
- private def SERIALIZER_JAVA: Serializers.Java = Serializers.Java
- private def SERIALIZER_JAVA_JSON: Serializers.JavaJSON = Serializers.JavaJSON
+ private def SERIALIZER_JAVA: Serializers.Java = Serializers.Java
+ private def SERIALIZER_JAVA_JSON: Serializers.JavaJSON = Serializers.JavaJSON
private def SERIALIZER_SCALA_JSON: Serializers.ScalaJSON = Serializers.ScalaJSON
- private def SERIALIZER_PROTOBUF: Serializers.Protobuf = Serializers.Protobuf
+ private def SERIALIZER_PROTOBUF: Serializers.Protobuf = Serializers.Protobuf
def setClassLoader(cl: ClassLoader) = {
val someCl = Some(cl)
- SERIALIZER_JAVA.classLoader = someCl
- SERIALIZER_JAVA_JSON.classLoader = someCl
+ SERIALIZER_JAVA.classLoader = someCl
+ SERIALIZER_JAVA_JSON.classLoader = someCl
SERIALIZER_SCALA_JSON.classLoader = someCl
}
def deserialize(messageProtocol: MessageProtocol): Any = {
messageProtocol.getSerializationScheme match {
- case SerializationSchemeType.JAVA =>
+ case SerializationSchemeType.JAVA ⇒
unbox(SERIALIZER_JAVA.fromBinary(messageProtocol.getMessage.toByteArray, None))
- case SerializationSchemeType.PROTOBUF =>
+ case SerializationSchemeType.PROTOBUF ⇒
val clazz = loadManifest(SERIALIZER_PROTOBUF.classLoader, messageProtocol)
SERIALIZER_PROTOBUF.fromBinary(messageProtocol.getMessage.toByteArray, Some(clazz))
- case SerializationSchemeType.SCALA_JSON =>
+ case SerializationSchemeType.SCALA_JSON ⇒
val clazz = loadManifest(SERIALIZER_SCALA_JSON.classLoader, messageProtocol)
val renderer = clazz.newInstance.asInstanceOf[Serializable.ScalaJSON[_]]
renderer.fromBytes(messageProtocol.getMessage.toByteArray)
- case SerializationSchemeType.JAVA_JSON =>
+ case SerializationSchemeType.JAVA_JSON ⇒
val clazz = loadManifest(SERIALIZER_JAVA_JSON.classLoader, messageProtocol)
SERIALIZER_JAVA_JSON.fromBinary(messageProtocol.getMessage.toByteArray, Some(clazz))
}
@@ -76,26 +76,26 @@ object MessageSerializer {
}
private def box(value: Any): AnyRef = value match {
- case value: Boolean => new java.lang.Boolean(value)
- case value: Char => new java.lang.Character(value)
- case value: Short => new java.lang.Short(value)
- case value: Int => new java.lang.Integer(value)
- case value: Long => new java.lang.Long(value)
- case value: Float => new java.lang.Float(value)
- case value: Double => new java.lang.Double(value)
- case value: Byte => new java.lang.Byte(value)
- case value => value.asInstanceOf[AnyRef]
+ case value: Boolean ⇒ new java.lang.Boolean(value)
+ case value: Char ⇒ new java.lang.Character(value)
+ case value: Short ⇒ new java.lang.Short(value)
+ case value: Int ⇒ new java.lang.Integer(value)
+ case value: Long ⇒ new java.lang.Long(value)
+ case value: Float ⇒ new java.lang.Float(value)
+ case value: Double ⇒ new java.lang.Double(value)
+ case value: Byte ⇒ new java.lang.Byte(value)
+ case value ⇒ value.asInstanceOf[AnyRef]
}
private def unbox(value: AnyRef): Any = value match {
- case value: java.lang.Boolean => value.booleanValue
- case value: java.lang.Character => value.charValue
- case value: java.lang.Short => value.shortValue
- case value: java.lang.Integer => value.intValue
- case value: java.lang.Long => value.longValue
- case value: java.lang.Float => value.floatValue
- case value: java.lang.Double => value.doubleValue
- case value: java.lang.Byte => value.byteValue
- case value => value
+ case value: java.lang.Boolean ⇒ value.booleanValue
+ case value: java.lang.Character ⇒ value.charValue
+ case value: java.lang.Short ⇒ value.shortValue
+ case value: java.lang.Integer ⇒ value.intValue
+ case value: java.lang.Long ⇒ value.longValue
+ case value: java.lang.Float ⇒ value.floatValue
+ case value: java.lang.Double ⇒ value.doubleValue
+ case value: java.lang.Byte ⇒ value.byteValue
+ case value ⇒ value
}
}
diff --git a/akka-remote/src/main/scala/akka/remote/RemoteShared.scala b/akka-remote/src/main/scala/akka/remote/RemoteShared.scala
index 9fa9d1b5c0..0708cffae7 100644
--- a/akka-remote/src/main/scala/akka/remote/RemoteShared.scala
+++ b/akka-remote/src/main/scala/akka/remote/RemoteShared.scala
@@ -10,12 +10,12 @@ import akka.config.ConfigurationException
object RemoteClientSettings {
val SECURE_COOKIE: Option[String] = config.getString("akka.remote.secure-cookie", "") match {
- case "" => None
- case cookie => Some(cookie)
+ case "" ⇒ None
+ case cookie ⇒ Some(cookie)
}
val RECONNECTION_TIME_WINDOW = Duration(config.getInt("akka.remote.client.reconnection-time-window", 600), TIME_UNIT).toMillis
- val READ_TIMEOUT = Duration(config.getInt("akka.remote.client.read-timeout", 10), TIME_UNIT)
- val RECONNECT_DELAY = Duration(config.getInt("akka.remote.client.reconnect-delay", 5), TIME_UNIT)
+ val READ_TIMEOUT = Duration(config.getInt("akka.remote.client.read-timeout", 10), TIME_UNIT)
+ val RECONNECT_DELAY = Duration(config.getInt("akka.remote.client.reconnect-delay", 5), TIME_UNIT)
val REAP_FUTURES_DELAY = Duration(config.getInt("akka.remote.client.reap-futures-delay", 5), TIME_UNIT)
val MESSAGE_FRAME_SIZE = config.getInt("akka.remote.client.message-frame-size", 1048576)
}
@@ -23,20 +23,20 @@ object RemoteClientSettings {
object RemoteServerSettings {
val isRemotingEnabled = config.getList("akka.enabled-modules").exists(_ == "remote")
val MESSAGE_FRAME_SIZE = config.getInt("akka.remote.server.message-frame-size", 1048576)
- val SECURE_COOKIE = config.getString("akka.remote.secure-cookie")
- val REQUIRE_COOKIE = {
+ val SECURE_COOKIE = config.getString("akka.remote.secure-cookie")
+ val REQUIRE_COOKIE = {
val requireCookie = config.getBool("akka.remote.server.require-cookie", false)
if (isRemotingEnabled && requireCookie && SECURE_COOKIE.isEmpty) throw new ConfigurationException(
"Configuration option 'akka.remote.server.require-cookie' is turned on but no secure cookie is defined in 'akka.remote.secure-cookie'.")
requireCookie
}
- val UNTRUSTED_MODE = config.getBool("akka.remote.server.untrusted-mode", false)
- val HOSTNAME = config.getString("akka.remote.server.hostname", "localhost")
- val PORT = config.getInt("akka.remote.server.port", 2552)
+ val UNTRUSTED_MODE = config.getBool("akka.remote.server.untrusted-mode", false)
+ val HOSTNAME = config.getString("akka.remote.server.hostname", "localhost")
+ val PORT = config.getInt("akka.remote.server.port", 2552)
val CONNECTION_TIMEOUT_MILLIS = Duration(config.getInt("akka.remote.server.connection-timeout", 1), TIME_UNIT)
- val COMPRESSION_SCHEME = config.getString("akka.remote.compression-scheme", "zlib")
- val ZLIB_COMPRESSION_LEVEL = {
+ val COMPRESSION_SCHEME = config.getString("akka.remote.compression-scheme", "zlib")
+ val ZLIB_COMPRESSION_LEVEL = {
val level = config.getInt("akka.remote.zlib-compression-level", 6)
if (level < 1 && level > 9) throw new IllegalArgumentException(
"zlib compression level has to be within 1-9, with 1 being fastest and 9 being the most compressed")
@@ -48,7 +48,7 @@ object RemoteServerSettings {
val EXECUTION_POOL_KEEPALIVE = Duration(config.getInt("akka.remote.server.execution-pool-keepalive", 60), TIME_UNIT)
val EXECUTION_POOL_SIZE = {
- val sz = config.getInt("akka.remote.server.execution-pool-size",16)
+ val sz = config.getInt("akka.remote.server.execution-pool-size", 16)
if (sz < 1) throw new IllegalArgumentException("akka.remote.server.execution-pool-size is less than 1")
sz
}
diff --git a/akka-remote/src/main/scala/akka/remote/netty/NettyRemoteSupport.scala b/akka-remote/src/main/scala/akka/remote/netty/NettyRemoteSupport.scala
index 982fd3b80b..33dc11382c 100644
--- a/akka-remote/src/main/scala/akka/remote/netty/NettyRemoteSupport.scala
+++ b/akka-remote/src/main/scala/akka/remote/netty/NettyRemoteSupport.scala
@@ -4,27 +4,39 @@
package akka.remote.netty
-import akka.dispatch.{DefaultCompletableFuture, CompletableFuture, Future}
-import akka.remote.{MessageSerializer, RemoteClientSettings, RemoteServerSettings}
+import akka.dispatch.{ DefaultCompletableFuture, CompletableFuture, Future }
+import akka.remote.{ MessageSerializer, RemoteClientSettings, RemoteServerSettings }
import akka.remote.protocol.RemoteProtocol._
import akka.remote.protocol.RemoteProtocol.ActorType._
import akka.serialization.RemoteActorSerialization
import akka.serialization.RemoteActorSerialization._
import akka.remoteinterface._
-import akka.actor.{PoisonPill, Index, LocalActorRef, Actor, RemoteActorRef,
- TypedActor, ActorRef, IllegalActorStateException,
- RemoteActorSystemMessage, uuidFrom, Uuid,
- Exit, LifeCycleMessage, ActorType => AkkaActorType}
+import akka.actor.{
+ PoisonPill,
+ Index,
+ LocalActorRef,
+ Actor,
+ RemoteActorRef,
+ TypedActor,
+ ActorRef,
+ IllegalActorStateException,
+ RemoteActorSystemMessage,
+ uuidFrom,
+ Uuid,
+ Exit,
+ LifeCycleMessage,
+ ActorType ⇒ AkkaActorType
+}
import akka.actor.Actor._
import akka.config.Config._
import akka.util._
import akka.event.EventHandler
import org.jboss.netty.channel._
-import org.jboss.netty.channel.group.{DefaultChannelGroup,ChannelGroup,ChannelGroupFuture}
+import org.jboss.netty.channel.group.{ DefaultChannelGroup, ChannelGroup, ChannelGroupFuture }
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory
-import org.jboss.netty.bootstrap.{ServerBootstrap, ClientBootstrap}
+import org.jboss.netty.bootstrap.{ ServerBootstrap, ClientBootstrap }
import org.jboss.netty.handler.codec.frame.{ LengthFieldBasedFrameDecoder, LengthFieldPrepender }
import org.jboss.netty.handler.codec.compression.{ ZlibDecoder, ZlibEncoder }
import org.jboss.netty.handler.codec.protobuf.{ ProtobufDecoder, ProtobufEncoder }
@@ -37,7 +49,7 @@ import scala.collection.JavaConversions._
import java.net.InetSocketAddress
import java.lang.reflect.InvocationTargetException
-import java.util.concurrent.atomic.{AtomicReference, AtomicBoolean}
+import java.util.concurrent.atomic.{ AtomicReference, AtomicBoolean }
import java.util.concurrent._
import akka.AkkaException
@@ -57,10 +69,10 @@ object RemoteEncoder {
}
}
-trait NettyRemoteClientModule extends RemoteClientModule { self: ListenerManagement =>
+trait NettyRemoteClientModule extends RemoteClientModule { self: ListenerManagement ⇒
private val remoteClients = new HashMap[Address, RemoteClient]
- private val remoteActors = new Index[Address, Uuid]
- private val lock = new ReadWriteGuard
+ private val remoteActors = new Index[Address, Uuid]
+ private val lock = new ReadWriteGuard
protected[akka] def typedActorFor[T](intfClass: Class[T], serviceId: String, timeout: Long, hostname: String, port: Int, loader: Option[ClassLoader]): T =
TypedActor.createProxyForRemoteActorRef(intfClass, RemoteActorRef(serviceId, timeout, loader, AkkaActorType.TypedActor))
@@ -75,24 +87,24 @@ trait NettyRemoteClientModule extends RemoteClientModule { self: ListenerManagem
typedActorInfo: Option[Tuple2[String, String]],
actorType: AkkaActorType,
loader: Option[ClassLoader]): Option[CompletableFuture[T]] =
- withClientFor(remoteAddress, loader)(_.send[T](message, senderOption, senderFuture, remoteAddress, timeout, isOneWay, actorRef, typedActorInfo, actorType))
+ withClientFor(remoteAddress, loader)(_.send[T](message, senderOption, senderFuture, remoteAddress, timeout, isOneWay, actorRef, typedActorInfo, actorType))
private[akka] def withClientFor[T](
- address: InetSocketAddress, loader: Option[ClassLoader])(fun: RemoteClient => T): T = {
+ address: InetSocketAddress, loader: Option[ClassLoader])(fun: RemoteClient ⇒ T): T = {
loader.foreach(MessageSerializer.setClassLoader(_))
val key = Address(address)
lock.readLock.lock
try {
val c = remoteClients.get(key) match {
- case s: Some[RemoteClient] => s.get
- case None =>
+ case s: Some[RemoteClient] ⇒ s.get
+ case None ⇒
lock.readLock.unlock
lock.writeLock.lock //Lock upgrade, not supported natively
try {
try {
remoteClients.get(key) match { //Recheck for addition, race between upgrades
- case s: Some[RemoteClient] => s.get //If already populated by other writer
- case None => //Populate map
+ case s: Some[RemoteClient] ⇒ s.get //If already populated by other writer
+ case None ⇒ //Populate map
val client = new ActiveRemoteClient(this, address, loader, self.notifyListeners _)
client.connect()
remoteClients += key -> client
@@ -107,15 +119,15 @@ trait NettyRemoteClientModule extends RemoteClientModule { self: ListenerManagem
def shutdownClientConnection(address: InetSocketAddress): Boolean = lock withWriteGuard {
remoteClients.remove(Address(address)) match {
- case s: Some[RemoteClient] => s.get.shutdown()
- case None => false
+ case s: Some[RemoteClient] ⇒ s.get.shutdown()
+ case None ⇒ false
}
}
def restartClientConnection(address: InetSocketAddress): Boolean = lock withReadGuard {
remoteClients.get(Address(address)) match {
- case s: Some[RemoteClient] => s.get.connect(reconnectIfAlreadyConnected = true)
- case None => false
+ case s: Some[RemoteClient] ⇒ s.get.connect(reconnectIfAlreadyConnected = true)
+ case None ⇒ false
}
}
@@ -129,7 +141,7 @@ trait NettyRemoteClientModule extends RemoteClientModule { self: ListenerManagem
}
def shutdownRemoteClients() = lock withWriteGuard {
- remoteClients.foreach({ case (addr, client) => client.shutdown() })
+ remoteClients.foreach({ case (addr, client) ⇒ client.shutdown() })
remoteClients.clear()
}
}
@@ -143,25 +155,25 @@ abstract class RemoteClient private[akka] (
val module: NettyRemoteClientModule,
val remoteAddress: InetSocketAddress) {
- val useTransactionLog = config.getBool("akka.remote.client.buffering.retry-message-send-on-failure", true)
+ val useTransactionLog = config.getBool("akka.remote.client.buffering.retry-message-send-on-failure", true)
val transactionLogCapacity = config.getInt("akka.remote.client.buffering.capacity", -1)
val name = this.getClass.getSimpleName + "@" +
- remoteAddress.getAddress.getHostAddress + "::" +
- remoteAddress.getPort
+ remoteAddress.getAddress.getHostAddress + "::" +
+ remoteAddress.getPort
- protected val futures = new ConcurrentHashMap[Uuid, CompletableFuture[_]]
+ protected val futures = new ConcurrentHashMap[Uuid, CompletableFuture[_]]
protected val pendingRequests = {
if (transactionLogCapacity < 0) new ConcurrentLinkedQueue[(Boolean, Uuid, RemoteMessageProtocol)]
- else new LinkedBlockingQueue[(Boolean, Uuid, RemoteMessageProtocol)](transactionLogCapacity)
+ else new LinkedBlockingQueue[(Boolean, Uuid, RemoteMessageProtocol)](transactionLogCapacity)
}
- private[remote] val runSwitch = new Switch()
+ private[remote] val runSwitch = new Switch()
private[remote] val isAuthenticated = new AtomicBoolean(false)
private[remote] def isRunning = runSwitch.isOn
- protected def notifyListeners(msg: => Any): Unit
+ protected def notifyListeners(msg: ⇒ Any): Unit
protected def currentChannel: Channel
@@ -197,17 +209,16 @@ abstract class RemoteClient private[akka] (
actorType: AkkaActorType): Option[CompletableFuture[T]] = synchronized { // FIXME: find better strategy to prevent race
send(createRemoteMessageProtocolBuilder(
- Some(actorRef),
- Left(actorRef.uuid),
- actorRef.address,
- timeout,
- Right(message),
- isOneWay,
- senderOption,
- typedActorInfo,
- actorType,
- if (isAuthenticated.compareAndSet(false, true)) RemoteClientSettings.SECURE_COOKIE else None
- ).build, senderFuture)
+ Some(actorRef),
+ Left(actorRef.uuid),
+ actorRef.address,
+ timeout,
+ Right(message),
+ isOneWay,
+ senderOption,
+ typedActorInfo,
+ actorType,
+ if (isAuthenticated.compareAndSet(false, true)) RemoteClientSettings.SECURE_COOKIE else None).build, senderFuture)
}
/**
@@ -226,19 +237,18 @@ abstract class RemoteClient private[akka] (
throw future.getCause
}
} catch {
- case e: Throwable =>
+ case e: Throwable ⇒
// add the request to the tx log after a failing send
notifyListeners(RemoteClientError(e, module, remoteAddress))
if (useTransactionLog) {
if (!pendingRequests.offer((true, null, request)))
throw new RemoteClientMessageBufferException("Buffer limit [" + transactionLogCapacity + "] reached")
- }
- else throw e
+ } else throw e
}
None
} else {
val futureResult = if (senderFuture.isDefined) senderFuture.get
- else new DefaultCompletableFuture[T](request.getActorInfo.getTimeout)
+ else new DefaultCompletableFuture[T](request.getActorInfo.getTimeout)
val futureUuid = uuidFrom(request.getUuid.getHigh, request.getUuid.getLow)
futures.put(futureUuid, futureResult) // Add future prematurely, remove it if write fails
@@ -248,7 +258,7 @@ abstract class RemoteClient private[akka] (
if (!pendingRequests.offer((false, futureUuid, request))) // Add the request to the tx log after a failing send
throw new RemoteClientMessageBufferException("Buffer limit [" + transactionLogCapacity + "] reached")
} else {
- val f = futures.remove(futureUuid) // Clean up future
+ val f = futures.remove(futureUuid) // Clean up future
if (f ne null) f.completeWithException(future.getCause)
}
}
@@ -258,10 +268,10 @@ abstract class RemoteClient private[akka] (
// try to send the original one
future = currentChannel.write(RemoteEncoder.encode(request))
future.awaitUninterruptibly()
- if (future.isCancelled) futures.remove(futureUuid) // Clean up future
+ if (future.isCancelled) futures.remove(futureUuid) // Clean up future
else if (!future.isSuccess) handleRequestReplyError(future)
} catch {
- case e: Exception => handleRequestReplyError(future)
+ case e: Exception ⇒ handleRequestReplyError(future)
}
Some(futureResult)
}
@@ -296,7 +306,7 @@ abstract class RemoteClient private[akka] (
}
}
pendingRequests.remove(pendingRequest)
- pendingRequest = pendingRequests.peek // try to grab next message
+ pendingRequest = pendingRequests.peek // try to grab next message
}
}
}
@@ -308,17 +318,22 @@ abstract class RemoteClient private[akka] (
*/
class ActiveRemoteClient private[akka] (
module: NettyRemoteClientModule, remoteAddress: InetSocketAddress,
- val loader: Option[ClassLoader] = None, notifyListenersFun: (=> Any) => Unit) extends RemoteClient(module, remoteAddress) {
+ val loader: Option[ClassLoader] = None, notifyListenersFun: (⇒ Any) ⇒ Unit) extends RemoteClient(module, remoteAddress) {
import RemoteClientSettings._
//FIXME rewrite to a wrapper object (minimize volatile access and maximize encapsulation)
- @volatile private var bootstrap: ClientBootstrap = _
- @volatile private[remote] var connection: ChannelFuture = _
- @volatile private[remote] var openChannels: DefaultChannelGroup = _
- @volatile private var timer: HashedWheelTimer = _
- @volatile private var reconnectionTimeWindowStart = 0L
+ @volatile
+ private var bootstrap: ClientBootstrap = _
+ @volatile
+ private[remote] var connection: ChannelFuture = _
+ @volatile
+ private[remote] var openChannels: DefaultChannelGroup = _
+ @volatile
+ private var timer: HashedWheelTimer = _
+ @volatile
+ private var reconnectionTimeWindowStart = 0L
- def notifyListeners(msg: => Any): Unit = notifyListenersFun(msg)
+ def notifyListeners(msg: ⇒ Any): Unit = notifyListenersFun(msg)
def currentChannel = connection.getChannel
def connect(reconnectIfAlreadyConnected: Boolean = false): Boolean = {
@@ -342,9 +357,9 @@ class ActiveRemoteClient private[akka] (
//Add a task that does GCing of expired Futures
timer.newTimeout(new TimerTask() {
def run(timeout: Timeout) = {
- if(isRunning) {
+ if (isRunning) {
val i = futures.entrySet.iterator
- while(i.hasNext) {
+ while (i.hasNext) {
val e = i.next
if (e.getValue.isExpired)
futures.remove(e.getKey)
@@ -356,8 +371,8 @@ class ActiveRemoteClient private[akka] (
true
}
} match {
- case true => true
- case false if reconnectIfAlreadyConnected =>
+ case true ⇒ true
+ case false if reconnectIfAlreadyConnected ⇒
isAuthenticated.set(false)
openChannels.remove(connection.getChannel)
connection.getChannel.close
@@ -367,7 +382,7 @@ class ActiveRemoteClient private[akka] (
notifyListeners(RemoteClientError(connection.getCause, module, remoteAddress))
false
} else true
- case false => false
+ case false ⇒ false
}
}
@@ -408,14 +423,14 @@ class ActiveRemoteClientPipelineFactory(
client: ActiveRemoteClient) extends ChannelPipelineFactory {
def getPipeline: ChannelPipeline = {
- val timeout = new ReadTimeoutHandler(timer, RemoteClientSettings.READ_TIMEOUT.length, RemoteClientSettings.READ_TIMEOUT.unit)
- val lenDec = new LengthFieldBasedFrameDecoder(RemoteClientSettings.MESSAGE_FRAME_SIZE, 0, 4, 0, 4)
- val lenPrep = new LengthFieldPrepender(4)
+ val timeout = new ReadTimeoutHandler(timer, RemoteClientSettings.READ_TIMEOUT.length, RemoteClientSettings.READ_TIMEOUT.unit)
+ val lenDec = new LengthFieldBasedFrameDecoder(RemoteClientSettings.MESSAGE_FRAME_SIZE, 0, 4, 0, 4)
+ val lenPrep = new LengthFieldPrepender(4)
val protobufDec = new ProtobufDecoder(AkkaRemoteProtocol.getDefaultInstance)
val protobufEnc = new ProtobufEncoder
- val (enc, dec) = RemoteServerSettings.COMPRESSION_SCHEME match {
- case "zlib" => (new ZlibEncoder(RemoteServerSettings.ZLIB_COMPRESSION_LEVEL) :: Nil, new ZlibDecoder :: Nil)
- case _ => (Nil,Nil)
+ val (enc, dec) = RemoteServerSettings.COMPRESSION_SCHEME match {
+ case "zlib" ⇒ (new ZlibEncoder(RemoteServerSettings.ZLIB_COMPRESSION_LEVEL) :: Nil, new ZlibDecoder :: Nil)
+ case _ ⇒ (Nil, Nil)
}
val remoteClient = new ActiveRemoteClientHandler(name, futures, bootstrap, remoteAddress, timer, client)
@@ -440,12 +455,12 @@ class ActiveRemoteClientHandler(
override def messageReceived(ctx: ChannelHandlerContext, event: MessageEvent) {
try {
event.getMessage match {
- case arp: AkkaRemoteProtocol if arp.hasInstruction =>
+ case arp: AkkaRemoteProtocol if arp.hasInstruction ⇒
val rcp = arp.getInstruction
rcp.getCommandType match {
- case CommandType.SHUTDOWN => spawn { client.module.shutdownClientConnection(remoteAddress) }
+ case CommandType.SHUTDOWN ⇒ spawn { client.module.shutdownClientConnection(remoteAddress) }
}
- case arp: AkkaRemoteProtocol if arp.hasMessage =>
+ case arp: AkkaRemoteProtocol if arp.hasMessage ⇒
val reply = arp.getMessage
val replyUuid = uuidFrom(reply.getActorInfo.getUuid.getHigh, reply.getActorInfo.getUuid.getLow)
val future = futures.remove(replyUuid).asInstanceOf[CompletableFuture[Any]]
@@ -457,11 +472,11 @@ class ActiveRemoteClientHandler(
} else {
future.completeWithException(parseException(reply, client.loader))
}
- case other =>
+ case other ⇒
throw new RemoteClientException("Unknown message received in remote client handler: " + other, client.module, client.remoteAddress)
}
} catch {
- case e: Throwable =>
+ case e: Throwable ⇒
EventHandler.error(e, this, e.getMessage)
client.notifyListeners(RemoteClientError(e, client.module, client.remoteAddress))
throw e
@@ -487,7 +502,7 @@ class ActiveRemoteClientHandler(
client.notifyListeners(RemoteClientConnected(client.module, client.remoteAddress))
client.resetReconnectionTimeWindow
} catch {
- case e: Throwable =>
+ case e: Throwable ⇒
EventHandler.error(e, this, e.getMessage)
client.notifyListeners(RemoteClientError(e, client.module, client.remoteAddress))
throw e
@@ -500,9 +515,9 @@ class ActiveRemoteClientHandler(
override def exceptionCaught(ctx: ChannelHandlerContext, event: ExceptionEvent) = {
event.getCause match {
- case e: ReadTimeoutException =>
+ case e: ReadTimeoutException ⇒
spawn { client.module.shutdownClientConnection(remoteAddress) }
- case e =>
+ case e ⇒
client.notifyListeners(RemoteClientError(e, client.module, client.remoteAddress))
event.getChannel.close //FIXME Is this the correct behavior?
}
@@ -513,12 +528,12 @@ class ActiveRemoteClientHandler(
val classname = exception.getClassname
try {
val exceptionClass = if (loader.isDefined) loader.get.loadClass(classname)
- else Class.forName(classname)
+ else Class.forName(classname)
exceptionClass
.getConstructor(Array[Class[_]](classOf[String]): _*)
.newInstance(exception.getMessage).asInstanceOf[Throwable]
} catch {
- case problem: Throwable =>
+ case problem: Throwable ⇒
EventHandler.error(problem, this, problem.getMessage)
CannotInstantiateRemoteExceptionDueToRemoteProtocolParsingErrorException(problem, classname, exception.getMessage)
}
@@ -538,8 +553,8 @@ class NettyRemoteSupport extends RemoteSupport with NettyRemoteServerModule with
protected[akka] def actorFor(address: String, timeout: Long, host: String, port: Int, loader: Option[ClassLoader]): ActorRef = {
if (optimizeLocalScoped_?) {
val home = this.address
- if ((host == home.getAddress.getHostAddress || host == home.getHostName) && port == home.getPort) {//TODO: switch to InetSocketAddress.equals?
- val localRef = findActorByAddressOrUuid(address,address)
+ if ((host == home.getAddress.getHostAddress || host == home.getHostName) && port == home.getPort) { //TODO: switch to InetSocketAddress.equals?
+ val localRef = findActorByAddressOrUuid(address, address)
if (localRef ne null) return localRef //Code significantly simpler with the return statement
}
}
@@ -551,9 +566,9 @@ class NettyRemoteSupport extends RemoteSupport with NettyRemoteServerModule with
class NettyRemoteServer(serverModule: NettyRemoteServerModule, val host: String, val port: Int, val loader: Option[ClassLoader]) {
val name = "NettyRemoteServer@" + host + ":" + port
- val address = new InetSocketAddress(host,port)
+ val address = new InetSocketAddress(host, port)
- private val factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool,Executors.newCachedThreadPool)
+ private val factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool, Executors.newCachedThreadPool)
private val bootstrap = new ServerBootstrap(factory)
@@ -586,26 +601,26 @@ class NettyRemoteServer(serverModule: NettyRemoteServerModule, val host: String,
bootstrap.releaseExternalResources()
serverModule.notifyListeners(RemoteServerShutdown(serverModule))
} catch {
- case e: Exception =>
+ case e: Exception ⇒
EventHandler.error(e, this, e.getMessage)
}
}
}
-trait NettyRemoteServerModule extends RemoteServerModule { self: RemoteModule =>
+trait NettyRemoteServerModule extends RemoteServerModule { self: RemoteModule ⇒
import RemoteServerSettings._
private[akka] val currentServer = new AtomicReference[Option[NettyRemoteServer]](None)
def address = currentServer.get match {
- case s: Some[NettyRemoteServer] => s.get.address
- case None => ReflectiveAccess.RemoteModule.configDefaultAddress
+ case s: Some[NettyRemoteServer] ⇒ s.get.address
+ case None ⇒ ReflectiveAccess.RemoteModule.configDefaultAddress
}
def name = currentServer.get match {
- case s: Some[NettyRemoteServer] => s.get.name
- case None =>
- val a = ReflectiveAccess.RemoteModule.configDefaultAddress
+ case s: Some[NettyRemoteServer] ⇒ s.get.name
+ case None ⇒
+ val a = ReflectiveAccess.RemoteModule.configDefaultAddress
"NettyRemoteServer@" + a.getAddress.getHostAddress + ":" + a.getPort
}
@@ -619,7 +634,7 @@ trait NettyRemoteServerModule extends RemoteServerModule { self: RemoteModule =>
currentServer.set(Some(new NettyRemoteServer(this, _hostname, _port, loader)))
}
} catch {
- case e: Exception =>
+ case e: Exception ⇒
EventHandler.error(e, this, e.getMessage)
notifyListeners(RemoteServerError(e, this))
}
@@ -628,8 +643,7 @@ trait NettyRemoteServerModule extends RemoteServerModule { self: RemoteModule =>
def shutdownServerModule() = guard withGuard {
_isRunning switchOff {
- currentServer.getAndSet(None) foreach {
- instance =>
+ currentServer.getAndSet(None) foreach { instance ⇒
instance.shutdown()
}
}
@@ -650,8 +664,8 @@ trait NettyRemoteServerModule extends RemoteServerModule { self: RemoteModule =>
* @param id custom actor id
* @param typedActor typed actor to register
*/
- def registerTypedPerSessionActor(id: String, factory: => AnyRef): Unit = guard withGuard {
- registerTypedPerSessionActor(id, () => factory, typedActorsFactories)
+ def registerTypedPerSessionActor(id: String, factory: ⇒ AnyRef): Unit = guard withGuard {
+ registerTypedPerSessionActor(id, () ⇒ factory, typedActorsFactories)
}
/**
@@ -680,11 +694,11 @@ trait NettyRemoteServerModule extends RemoteServerModule { self: RemoteModule =>
*
* NOTE: If you use this method to register your remote actor then you must unregister the actor by this ID yourself.
*/
- def registerPerSession(id: String, factory: => ActorRef): Unit = synchronized {
- registerPerSession(id, () => factory, actorsFactories)
+ def registerPerSession(id: String, factory: ⇒ ActorRef): Unit = synchronized {
+ registerPerSession(id, () ⇒ factory, actorsFactories)
}
- private def registerPerSession[Key](id: Key, factory: () => ActorRef, registry: ConcurrentHashMap[Key,() => ActorRef]) {
+ private def registerPerSession[Key](id: Key, factory: () ⇒ ActorRef, registry: ConcurrentHashMap[Key, () ⇒ ActorRef]) {
if (_isRunning.isOn)
registry.put(id, factory) //TODO change to putIfAbsent
}
@@ -694,7 +708,7 @@ trait NettyRemoteServerModule extends RemoteServerModule { self: RemoteModule =>
registry.put(id, typedActor) //TODO change to putIfAbsent
}
- private def registerTypedPerSessionActor[Key](id: Key, factory: () => AnyRef, registry: ConcurrentHashMap[Key,() => AnyRef]) {
+ private def registerTypedPerSessionActor[Key](id: Key, factory: () ⇒ AnyRef, registry: ConcurrentHashMap[Key, () ⇒ AnyRef]) {
if (_isRunning.isOn)
registry.put(id, factory) //TODO change to putIfAbsent
}
@@ -720,7 +734,7 @@ trait NettyRemoteServerModule extends RemoteServerModule { self: RemoteModule =>
else {
val actorRef = actors get id
actorsByUuid.remove(actorRef.uuid, actorRef)
- actors.remove(id,actorRef)
+ actors.remove(id, actorRef)
}
}
}
@@ -741,7 +755,7 @@ trait NettyRemoteServerModule extends RemoteServerModule { self: RemoteModule =>
*
* NOTE: You need to call this method if you have registered an actor by a custom ID.
*/
- def unregisterTypedActor(id: String):Unit = guard withGuard {
+ def unregisterTypedActor(id: String): Unit = guard withGuard {
if (_isRunning.isOn) {
if (id.startsWith(UUID_PREFIX)) typedActorsByUuid.remove(id.substring(UUID_PREFIX.length))
else typedActors.remove(id)
@@ -749,10 +763,10 @@ trait NettyRemoteServerModule extends RemoteServerModule { self: RemoteModule =>
}
/**
- * Unregister RemoteModule Typed Actor by specific 'id'.
- *
- * NOTE: You need to call this method if you have registered an actor by a custom ID.
- */
+ * Unregister RemoteModule Typed Actor by specific 'id'.
+ *
+ * NOTE: You need to call this method if you have registered an actor by a custom ID.
+ */
def unregisterTypedPerSessionActor(id: String): Unit =
if (_isRunning.isOn) typedActorsFactories.remove(id)
}
@@ -761,20 +775,20 @@ trait NettyRemoteServerModule extends RemoteServerModule { self: RemoteModule =>
* @author Jonas Bonér
*/
class RemoteServerPipelineFactory(
- val name: String,
- val openChannels: ChannelGroup,
- val loader: Option[ClassLoader],
- val server: NettyRemoteServerModule) extends ChannelPipelineFactory {
+ val name: String,
+ val openChannels: ChannelGroup,
+ val loader: Option[ClassLoader],
+ val server: NettyRemoteServerModule) extends ChannelPipelineFactory {
import RemoteServerSettings._
def getPipeline: ChannelPipeline = {
- val lenDec = new LengthFieldBasedFrameDecoder(MESSAGE_FRAME_SIZE, 0, 4, 0, 4)
- val lenPrep = new LengthFieldPrepender(4)
+ val lenDec = new LengthFieldBasedFrameDecoder(MESSAGE_FRAME_SIZE, 0, 4, 0, 4)
+ val lenPrep = new LengthFieldPrepender(4)
val protobufDec = new ProtobufDecoder(AkkaRemoteProtocol.getDefaultInstance)
val protobufEnc = new ProtobufEncoder
- val (enc, dec) = COMPRESSION_SCHEME match {
- case "zlib" => (new ZlibEncoder(ZLIB_COMPRESSION_LEVEL) :: Nil, new ZlibDecoder :: Nil)
- case _ => (Nil, Nil)
+ val (enc, dec) = COMPRESSION_SCHEME match {
+ case "zlib" ⇒ (new ZlibEncoder(ZLIB_COMPRESSION_LEVEL) :: Nil, new ZlibDecoder :: Nil)
+ case _ ⇒ (Nil, Nil)
}
val execution = new ExecutionHandler(
new OrderedMemoryAwareThreadPoolExecutor(
@@ -782,9 +796,7 @@ class RemoteServerPipelineFactory(
MAX_CHANNEL_MEMORY_SIZE,
MAX_TOTAL_MEMORY_SIZE,
EXECUTION_POOL_KEEPALIVE.length,
- EXECUTION_POOL_KEEPALIVE.unit
- )
- )
+ EXECUTION_POOL_KEEPALIVE.unit))
val remoteServer = new RemoteServerHandler(name, openChannels, loader, server)
val stages: List[ChannelHandler] = dec ::: lenDec :: protobufDec :: enc ::: lenPrep :: protobufEnc :: execution :: remoteServer :: Nil
new StaticChannelPipeline(stages: _*)
@@ -796,12 +808,12 @@ class RemoteServerPipelineFactory(
*/
@ChannelHandler.Sharable
class RemoteServerHandler(
- val name: String,
- val openChannels: ChannelGroup,
- val applicationLoader: Option[ClassLoader],
- val server: NettyRemoteServerModule) extends SimpleChannelUpstreamHandler {
+ val name: String,
+ val openChannels: ChannelGroup,
+ val applicationLoader: Option[ClassLoader],
+ val server: NettyRemoteServerModule) extends SimpleChannelUpstreamHandler {
import RemoteServerSettings._
- val CHANNEL_INIT = "channel-init".intern
+ val CHANNEL_INIT = "channel-init".intern
applicationLoader.foreach(MessageSerializer.setClassLoader(_)) //TODO: REVISIT: THIS FEELS A BIT DODGY
@@ -817,8 +829,8 @@ class RemoteServerHandler(
//Not interesting at the moment
} else if (!future.isSuccess) {
val socketAddress = future.getChannel.getRemoteAddress match {
- case i: InetSocketAddress => Some(i)
- case _ => None
+ case i: InetSocketAddress ⇒ Some(i)
+ case _ ⇒ None
}
server.notifyListeners(RemoteServerWriteFailed(payload, future.getCause, server, socketAddress))
}
@@ -844,16 +856,20 @@ class RemoteServerHandler(
val clientAddress = getClientAddress(ctx)
// stop all session actors
- for (map <- Option(sessionActors.remove(event.getChannel));
- actor <- collectionAsScalaIterable(map.values)) {
- try { actor ! PoisonPill } catch { case e: Exception => }
+ for (
+ map ← Option(sessionActors.remove(event.getChannel));
+ actor ← collectionAsScalaIterable(map.values)
+ ) {
+ try { actor ! PoisonPill } catch { case e: Exception ⇒ }
}
//FIXME switch approach or use other thread to execute this
// stop all typed session actors
- for (map <- Option(typedSessionActors.remove(event.getChannel));
- actor <- collectionAsScalaIterable(map.values)) {
- try { TypedActor.stop(actor) } catch { case e: Exception => }
+ for (
+ map ← Option(typedSessionActors.remove(event.getChannel));
+ actor ← collectionAsScalaIterable(map.values)
+ ) {
+ try { TypedActor.stop(actor) } catch { case e: Exception ⇒ }
}
server.notifyListeners(RemoteServerClientDisconnected(server, clientAddress))
@@ -865,13 +881,13 @@ class RemoteServerHandler(
}
override def messageReceived(ctx: ChannelHandlerContext, event: MessageEvent) = event.getMessage match {
- case null => throw new IllegalActorStateException("Message in remote MessageEvent is null: " + event)
+ case null ⇒ throw new IllegalActorStateException("Message in remote MessageEvent is null: " + event)
//case remoteProtocol: AkkaRemoteProtocol if remoteProtocol.hasInstruction => RemoteServer cannot receive control messages (yet)
- case remoteProtocol: AkkaRemoteProtocol if remoteProtocol.hasMessage =>
+ case remoteProtocol: AkkaRemoteProtocol if remoteProtocol.hasMessage ⇒
val requestProtocol = remoteProtocol.getMessage
if (REQUIRE_COOKIE) authenticateRemoteClient(requestProtocol, ctx)
handleRemoteMessageProtocol(requestProtocol, event.getChannel)
- case _ => //ignore
+ case _ ⇒ //ignore
}
override def exceptionCaught(ctx: ChannelHandlerContext, event: ExceptionEvent) = {
@@ -881,16 +897,16 @@ class RemoteServerHandler(
private def getClientAddress(ctx: ChannelHandlerContext): Option[InetSocketAddress] =
ctx.getChannel.getRemoteAddress match {
- case inet: InetSocketAddress => Some(inet)
- case _ => None
+ case inet: InetSocketAddress ⇒ Some(inet)
+ case _ ⇒ None
}
private def handleRemoteMessageProtocol(request: RemoteMessageProtocol, channel: Channel) = {
request.getActorInfo.getActorType match {
- case SCALA_ACTOR => dispatchToActor(request, channel)
- case TYPED_ACTOR => dispatchToTypedActor(request, channel)
- case JAVA_ACTOR => throw new IllegalActorStateException("ActorType JAVA_ACTOR is currently not supported")
- case other => throw new IllegalActorStateException("Unknown ActorType [" + other + "]")
+ case SCALA_ACTOR ⇒ dispatchToActor(request, channel)
+ case TYPED_ACTOR ⇒ dispatchToTypedActor(request, channel)
+ case JAVA_ACTOR ⇒ throw new IllegalActorStateException("ActorType JAVA_ACTOR is currently not supported")
+ case other ⇒ throw new IllegalActorStateException("Unknown ActorType [" + other + "]")
}
}
@@ -899,7 +915,7 @@ class RemoteServerHandler(
val actorRef =
try { createActor(actorInfo, channel) } catch {
- case e: SecurityException =>
+ case e: SecurityException ⇒
EventHandler.error(e, this, e.getMessage)
write(channel, createErrorReplyMessage(e, request, AkkaActorType.ScalaActor))
server.notifyListeners(RemoteServerError(e, server))
@@ -912,14 +928,14 @@ class RemoteServerHandler(
else None
message match { // first match on system messages
- case RemoteActorSystemMessage.Stop =>
+ case RemoteActorSystemMessage.Stop ⇒
if (UNTRUSTED_MODE) throw new SecurityException("RemoteModule server is operating is untrusted mode, can not stop the actor")
else actorRef.stop()
- case _: LifeCycleMessage if (UNTRUSTED_MODE) =>
+ case _: LifeCycleMessage if (UNTRUSTED_MODE) ⇒
throw new SecurityException("RemoteModule server is operating is untrusted mode, can not pass on a LifeCycleMessage to the remote actor")
- case _ => // then match on user defined messages
+ case _ ⇒ // then match on user defined messages
if (request.getOneWay) actorRef.!(message)(sender)
else actorRef.postMessageToMailboxAndCreateFutureResultWithTimeout(
message,
@@ -927,9 +943,9 @@ class RemoteServerHandler(
None,
Some(new DefaultCompletableFuture[Any](request.getActorInfo.getTimeout).
onComplete(_.value.get match {
- case l: Left[Throwable, Any] => write(channel, createErrorReplyMessage(l.a, request, AkkaActorType.ScalaActor))
- case r: Right[Throwable, Any] =>
- val messageBuilder = RemoteActorSerialization.createRemoteMessageProtocolBuilder(
+ case l: Left[Throwable, Any] ⇒ write(channel, createErrorReplyMessage(l.a, request, AkkaActorType.ScalaActor))
+ case r: Right[Throwable, Any] ⇒
+ val messageBuilder = RemoteActorSerialization.createRemoteMessageProtocolBuilder(
Some(actorRef),
Right(request.getUuid),
actorInfo.getAddress,
@@ -945,9 +961,7 @@ class RemoteServerHandler(
if (request.hasSupervisorUuid) messageBuilder.setSupervisorUuid(request.getSupervisorUuid)
write(channel, RemoteEncoder.encode(messageBuilder.build))
- }
- )
- ))
+ })))
}
}
@@ -967,8 +981,8 @@ class RemoteServerHandler(
//FIXME: Add ownerTypeHint and parameter types to the TypedActorInfo?
val (ownerTypeHint, argClasses, args) =
MessageSerializer
- .deserialize(request.getMessage)
- .asInstanceOf[Tuple3[String,Array[Class[_]],Array[AnyRef]]]
+ .deserialize(request.getMessage)
+ .asInstanceOf[Tuple3[String, Array[Class[_]], Array[AnyRef]]]
def resolveMethod(bottomType: Class[_],
typeHint: String,
@@ -977,14 +991,14 @@ class RemoteServerHandler(
var typeToResolve = bottomType
var targetMethod: java.lang.reflect.Method = null
var firstException: NoSuchMethodException = null
- while((typeToResolve ne null) && (targetMethod eq null)) {
+ while ((typeToResolve ne null) && (targetMethod eq null)) {
if ((typeHint eq null) || typeToResolve.getName.startsWith(typeHint)) {
try {
- targetMethod = typeToResolve.getDeclaredMethod(methodName, methodSignature:_*)
+ targetMethod = typeToResolve.getDeclaredMethod(methodName, methodSignature: _*)
targetMethod.setAccessible(true)
} catch {
- case e: NoSuchMethodException =>
+ case e: NoSuchMethodException ⇒
if (firstException eq null)
firstException = e
@@ -994,7 +1008,7 @@ class RemoteServerHandler(
typeToResolve = typeToResolve.getSuperclass
}
- if((targetMethod eq null) && (firstException ne null))
+ if ((targetMethod eq null) && (firstException ne null))
throw firstException
targetMethod
@@ -1007,7 +1021,7 @@ class RemoteServerHandler(
if (request.getOneWay) messageReceiver.invoke(typedActor, args: _*) //FIXME execute in non-IO thread
else {
//Sends the response
- def sendResponse(result: Either[Throwable,Any]): Unit = try {
+ def sendResponse(result: Either[Throwable, Any]): Unit = try {
val messageBuilder = RemoteActorSerialization.createRemoteMessageProtocolBuilder(
None,
Right(request.getUuid),
@@ -1023,41 +1037,42 @@ class RemoteServerHandler(
write(channel, RemoteEncoder.encode(messageBuilder.build))
} catch {
- case e: Exception =>
+ case e: Exception ⇒
EventHandler.error(e, this, e.getMessage)
server.notifyListeners(RemoteServerError(e, server))
}
messageReceiver.invoke(typedActor, args: _*) match { //TODO execute in non-IO thread
//If it's a future, we can lift on that to defer the send to when the future is completed
- case f: Future[_] => f.onComplete( future => sendResponse(future.value.get) )
- case other => sendResponse(Right(other))
+ case f: Future[_] ⇒ f.onComplete(future ⇒ sendResponse(future.value.get))
+ case other ⇒ sendResponse(Right(other))
}
}
} catch {
- case e: Exception =>
+ case e: Exception ⇒
EventHandler.error(e, this, e.getMessage)
write(channel, createErrorReplyMessage(e match {
- case e: InvocationTargetException => e.getCause
- case e => e
+ case e: InvocationTargetException ⇒ e.getCause
+ case e ⇒ e
}, request, AkkaActorType.TypedActor))
server.notifyListeners(RemoteServerError(e, server))
- } finally {
+ }
+ finally {
//TODO SenderContextInfo.senderActorRef.value = None ?
//TODO SenderContextInfo.senderProxy.value = None ?
}
}
- private def findSessionActor(id: String, channel: Channel) : ActorRef =
+ private def findSessionActor(id: String, channel: Channel): ActorRef =
sessionActors.get(channel) match {
- case null => null
- case map => map get id
+ case null ⇒ null
+ case map ⇒ map get id
}
- private def findTypedSessionActor(id: String, channel: Channel) : AnyRef =
+ private def findTypedSessionActor(id: String, channel: Channel): AnyRef =
typedSessionActors.get(channel) match {
- case null => null
- case map => map get id
+ case null ⇒ null
+ case map ⇒ map get id
}
/**
@@ -1068,16 +1083,16 @@ class RemoteServerHandler(
val address = actorInfo.getAddress
findSessionActor(address, channel) match {
- case null => // we dont have it in the session either, see if we have a factory for it
+ case null ⇒ // we dont have it in the session either, see if we have a factory for it
server.findActorFactory(address) match {
- case null => null
- case factory =>
+ case null ⇒ null
+ case factory ⇒
val actorRef = factory()
actorRef.uuid = parseUuid(uuid) //FIXME is this sensible?
sessionActors.get(channel).put(address, actorRef)
actorRef.start() //Start it where's it's created
}
- case sessionActor => sessionActor
+ case sessionActor ⇒ sessionActor
}
}
@@ -1093,36 +1108,36 @@ class RemoteServerHandler(
val address = actorInfo.getAddress
server.findActorByAddressOrUuid(address, parseUuid(uuid).toString) match {
- // the actor has not been registered globally. See if we have it in the session
- case null => createSessionActor(actorInfo, channel)
- case actorRef => actorRef
+ // the actor has not been registered globally. See if we have it in the session
+ case null ⇒ createSessionActor(actorInfo, channel)
+ case actorRef ⇒ actorRef
}
}
/**
* gets the actor from the session, or creates one if there is a factory for it
*/
- private def createTypedSessionActor(actorInfo: ActorInfoProtocol, channel: Channel):AnyRef ={
+ private def createTypedSessionActor(actorInfo: ActorInfoProtocol, channel: Channel): AnyRef = {
val address = actorInfo.getAddress
findTypedSessionActor(address, channel) match {
- case null =>
+ case null ⇒
server.findTypedActorFactory(address) match {
- case null => null
- case factory =>
+ case null ⇒ null
+ case factory ⇒
val newInstance = factory()
typedSessionActors.get(channel).put(address, newInstance)
newInstance
}
- case sessionActor => sessionActor
+ case sessionActor ⇒ sessionActor
}
}
private def createTypedActor(actorInfo: ActorInfoProtocol, channel: Channel): AnyRef = {
val uuid = actorInfo.getUuid
server.findTypedActorByAddressOrUuid(actorInfo.getAddress, parseUuid(uuid).toString) match {
- // the actor has not been registered globally. See if we have it in the session
- case null => createTypedSessionActor(actorInfo, channel)
- case typedActor => typedActor
+ // the actor has not been registered globally. See if we have it in the session
+ case null ⇒ createTypedSessionActor(actorInfo, channel)
+ case typedActor ⇒ typedActor
}
}
@@ -1146,8 +1161,8 @@ class RemoteServerHandler(
private def authenticateRemoteClient(request: RemoteMessageProtocol, ctx: ChannelHandlerContext) = {
val attachment = ctx.getAttachment
if ((attachment ne null) &&
- attachment.isInstanceOf[String] &&
- attachment.asInstanceOf[String] == CHANNEL_INIT) { // is first time around, channel initialization
+ attachment.isInstanceOf[String] &&
+ attachment.asInstanceOf[String] == CHANNEL_INIT) { // is first time around, channel initialization
ctx.setAttachment(null)
val clientAddress = ctx.getChannel.getRemoteAddress.toString
if (!request.hasCookie) throw new SecurityException(
@@ -1157,12 +1172,12 @@ class RemoteServerHandler(
}
}
- protected def parseUuid(protocol: UuidProtocol): Uuid = uuidFrom(protocol.getHigh,protocol.getLow)
+ protected def parseUuid(protocol: UuidProtocol): Uuid = uuidFrom(protocol.getHigh, protocol.getLow)
}
class DefaultDisposableChannelGroup(name: String) extends DefaultChannelGroup(name) {
protected val guard = new ReadWriteGuard
- protected val open = new AtomicBoolean(true)
+ protected val open = new AtomicBoolean(true)
override def add(channel: Channel): Boolean = guard withReadGuard {
if (open.get) {
diff --git a/akka-remote/src/main/scala/akka/serialization/Compression.scala b/akka-remote/src/main/scala/akka/serialization/Compression.scala
index d0478cc62b..48287adc2c 100644
--- a/akka-remote/src/main/scala/akka/serialization/Compression.scala
+++ b/akka-remote/src/main/scala/akka/serialization/Compression.scala
@@ -14,7 +14,7 @@ object Compression {
*/
object LZF {
import voldemort.store.compress.lzf._
- def compress(bytes: Array[Byte]): Array[Byte] = LZFEncoder encode bytes
+ def compress(bytes: Array[Byte]): Array[Byte] = LZFEncoder encode bytes
def uncompress(bytes: Array[Byte]): Array[Byte] = LZFDecoder decode bytes
}
}
diff --git a/akka-remote/src/main/scala/akka/serialization/Serializable.scala b/akka-remote/src/main/scala/akka/serialization/Serializable.scala
index 4b368078ae..3f3296d608 100644
--- a/akka-remote/src/main/scala/akka/serialization/Serializable.scala
+++ b/akka-remote/src/main/scala/akka/serialization/Serializable.scala
@@ -10,9 +10,9 @@ import com.google.protobuf.Message
import reflect.Manifest
-import java.io.{StringWriter, ByteArrayOutputStream, ObjectOutputStream}
+import java.io.{ StringWriter, ByteArrayOutputStream, ObjectOutputStream }
-import sjson.json.{Serializer=>SJSONSerializer}
+import sjson.json.{ Serializer ⇒ SJSONSerializer }
/**
* @author Jonas Bonér
diff --git a/akka-remote/src/main/scala/akka/serialization/SerializationProtocol.scala b/akka-remote/src/main/scala/akka/serialization/SerializationProtocol.scala
index 640884b761..4e65120b58 100644
--- a/akka-remote/src/main/scala/akka/serialization/SerializationProtocol.scala
+++ b/akka-remote/src/main/scala/akka/serialization/SerializationProtocol.scala
@@ -5,11 +5,11 @@
package akka.serialization
import akka.dispatch.MessageInvocation
-import akka.remote.protocol.RemoteProtocol.{ActorType => ActorTypeProtocol, _}
+import akka.remote.protocol.RemoteProtocol.{ ActorType ⇒ ActorTypeProtocol, _ }
import ActorTypeProtocol._
import akka.config.Supervision._
-import akka.actor.{uuidFrom,newUuid}
+import akka.actor.{ uuidFrom, newUuid }
import akka.actor._
import scala.collection.immutable.Stack
@@ -17,8 +17,7 @@ import scala.collection.immutable.Stack
import com.google.protobuf.ByteString
import akka.util.ReflectiveAccess
import java.net.InetSocketAddress
-import akka.remote. {RemoteClientSettings, MessageSerializer}
-
+import akka.remote.{ RemoteClientSettings, MessageSerializer }
/**
* Module for local actor serialization.
@@ -45,9 +44,9 @@ object ActorSerialization {
actorRef: ActorRef, format: Format[T], serializeMailBox: Boolean = true): SerializedActorRefProtocol = {
val lifeCycleProtocol: Option[LifeCycleProtocol] = {
actorRef.lifeCycle match {
- case Permanent => Some(LifeCycleProtocol.newBuilder.setLifeCycle(LifeCycleType.PERMANENT).build)
- case Temporary => Some(LifeCycleProtocol.newBuilder.setLifeCycle(LifeCycleType.TEMPORARY).build)
- case UndefinedLifeCycle => None//No need to send the undefined lifecycle over the wire //builder.setLifeCycle(LifeCycleType.UNDEFINED)
+ case Permanent ⇒ Some(LifeCycleProtocol.newBuilder.setLifeCycle(LifeCycleType.PERMANENT).build)
+ case Temporary ⇒ Some(LifeCycleProtocol.newBuilder.setLifeCycle(LifeCycleType.TEMPORARY).build)
+ case UndefinedLifeCycle ⇒ None //No need to send the undefined lifecycle over the wire //builder.setLifeCycle(LifeCycleType.UNDEFINED)
}
}
@@ -60,7 +59,7 @@ object ActorSerialization {
if (serializeMailBox == true) {
val messages =
actorRef.mailbox match {
- case q: java.util.Queue[MessageInvocation] =>
+ case q: java.util.Queue[MessageInvocation] ⇒
val l = new scala.collection.mutable.ListBuffer[MessageInvocation]
val it = q.iterator
while (it.hasNext == true) l += it.next
@@ -68,7 +67,7 @@ object ActorSerialization {
}
val requestProtocols =
- messages.map(m =>
+ messages.map(m ⇒
RemoteActorSerialization.createRemoteMessageProtocolBuilder(
Some(actorRef),
Left(actorRef.uuid),
@@ -81,13 +80,13 @@ object ActorSerialization {
ActorType.ScalaActor,
RemoteClientSettings.SECURE_COOKIE).build)
- requestProtocols.foreach(rp => builder.addMessages(rp))
+ requestProtocols.foreach(rp ⇒ builder.addMessages(rp))
}
actorRef.receiveTimeout.foreach(builder.setReceiveTimeout(_))
builder.setActorInstance(ByteString.copyFrom(format.toBinary(actorRef.actor.asInstanceOf[T])))
lifeCycleProtocol.foreach(builder.setLifeCycle(_))
- actorRef.supervisor.foreach(s => builder.setSupervisor(RemoteActorSerialization.toRemoteActorRefProtocol(s)))
+ actorRef.supervisor.foreach(s ⇒ builder.setSupervisor(RemoteActorSerialization.toRemoteActorRefProtocol(s)))
if (!actorRef.hotswap.isEmpty) builder.setHotswapStack(ByteString.copyFrom(Serializers.Java.toBinary(actorRef.hotswap)))
builder.build
}
@@ -101,21 +100,21 @@ object ActorSerialization {
}
private[akka] def fromProtobufToLocalActorRef[T <: Actor](
- protocol: SerializedActorRefProtocol, format: Format[T], loader: Option[ClassLoader]): ActorRef = {
+ protocol: SerializedActorRefProtocol, format: Format[T], loader: Option[ClassLoader]): ActorRef = {
val serializer =
- if (format.isInstanceOf[SerializerBasedActorFormat[_]])
- Some(format.asInstanceOf[SerializerBasedActorFormat[_]].serializer)
- else None
+ if (format.isInstanceOf[SerializerBasedActorFormat[_]])
+ Some(format.asInstanceOf[SerializerBasedActorFormat[_]].serializer)
+ else None
val lifeCycle =
- if (protocol.hasLifeCycle) {
- protocol.getLifeCycle.getLifeCycle match {
- case LifeCycleType.PERMANENT => Permanent
- case LifeCycleType.TEMPORARY => Temporary
- case unknown => throw new IllegalActorStateException("LifeCycle type is not valid [" + unknown + "]")
- }
- } else UndefinedLifeCycle
+ if (protocol.hasLifeCycle) {
+ protocol.getLifeCycle.getLifeCycle match {
+ case LifeCycleType.PERMANENT ⇒ Permanent
+ case LifeCycleType.TEMPORARY ⇒ Temporary
+ case unknown ⇒ throw new IllegalActorStateException("LifeCycle type is not valid [" + unknown + "]")
+ }
+ } else UndefinedLifeCycle
val supervisor =
if (protocol.hasSupervisor) Some(RemoteActorSerialization.fromProtobufToRemoteActorRef(protocol.getSupervisor, loader))
@@ -129,7 +128,7 @@ object ActorSerialization {
val classLoader = loader.getOrElse(getClass.getClassLoader)
- val factory = () => {
+ val factory = () ⇒ {
val actorClass = classLoader.loadClass(protocol.getActorClassname)
if (format.isInstanceOf[SerializerBasedActorFormat[_]])
format.asInstanceOf[SerializerBasedActorFormat[_]].serializer.fromBinary(
@@ -148,7 +147,7 @@ object ActorSerialization {
factory)
val messages = protocol.getMessagesList.toArray.toList.asInstanceOf[List[RemoteMessageProtocol]]
- messages.foreach(message => ar ! MessageSerializer.deserialize(message.getMessage))
+ messages.foreach(message ⇒ ar ! MessageSerializer.deserialize(message.getMessage))
if (format.isInstanceOf[SerializerBasedActorFormat[_]] == false)
format.fromBinary(protocol.getActorInstance.toByteArray, ar.actor.asInstanceOf[T])
@@ -185,8 +184,8 @@ object RemoteActorSerialization {
*/
def toRemoteActorRefProtocol(actor: ActorRef): RemoteActorRefProtocol = {
actor match {
- case ar: LocalActorRef => Actor.remote.registerByUuid(ar)
- case _ => {}
+ case ar: LocalActorRef ⇒ Actor.remote.registerByUuid(ar)
+ case _ ⇒ {}
}
RemoteActorRefProtocol.newBuilder
.setAddress("uuid:" + actor.uuid.toString)
@@ -195,61 +194,61 @@ object RemoteActorSerialization {
}
def createRemoteMessageProtocolBuilder(
- actorRef: Option[ActorRef],
- replyUuid: Either[Uuid, UuidProtocol],
- actorAddress: String,
- timeout: Long,
- message: Either[Throwable, Any],
- isOneWay: Boolean,
- senderOption: Option[ActorRef],
- typedActorInfo: Option[Tuple2[String, String]],
- actorType: ActorType,
- secureCookie: Option[String]): RemoteMessageProtocol.Builder = {
+ actorRef: Option[ActorRef],
+ replyUuid: Either[Uuid, UuidProtocol],
+ actorAddress: String,
+ timeout: Long,
+ message: Either[Throwable, Any],
+ isOneWay: Boolean,
+ senderOption: Option[ActorRef],
+ typedActorInfo: Option[Tuple2[String, String]],
+ actorType: ActorType,
+ secureCookie: Option[String]): RemoteMessageProtocol.Builder = {
val uuidProtocol = replyUuid match {
- case Left(uid) => UuidProtocol.newBuilder.setHigh(uid.getTime).setLow(uid.getClockSeqAndNode).build
- case Right(protocol) => protocol
+ case Left(uid) ⇒ UuidProtocol.newBuilder.setHigh(uid.getTime).setLow(uid.getClockSeqAndNode).build
+ case Right(protocol) ⇒ protocol
}
val actorInfoBuilder = ActorInfoProtocol.newBuilder
- .setUuid(uuidProtocol)
- .setAddress(actorAddress)
- .setTimeout(timeout)
+ .setUuid(uuidProtocol)
+ .setAddress(actorAddress)
+ .setTimeout(timeout)
- typedActorInfo.foreach { typedActor =>
+ typedActorInfo.foreach { typedActor ⇒
actorInfoBuilder.setTypedActorInfo(
TypedActorInfoProtocol.newBuilder
- .setInterface(typedActor._1)
- .setMethod(typedActor._2)
- .build)
+ .setInterface(typedActor._1)
+ .setMethod(typedActor._2)
+ .build)
}
actorType match {
- case ActorType.ScalaActor => actorInfoBuilder.setActorType(SCALA_ACTOR)
- case ActorType.TypedActor => actorInfoBuilder.setActorType(TYPED_ACTOR)
+ case ActorType.ScalaActor ⇒ actorInfoBuilder.setActorType(SCALA_ACTOR)
+ case ActorType.TypedActor ⇒ actorInfoBuilder.setActorType(TYPED_ACTOR)
}
val actorInfo = actorInfoBuilder.build
val messageBuilder = RemoteMessageProtocol.newBuilder
- .setUuid({
- val messageUuid = newUuid
- UuidProtocol.newBuilder.setHigh(messageUuid.getTime).setLow(messageUuid.getClockSeqAndNode).build
- })
- .setActorInfo(actorInfo)
- .setOneWay(isOneWay)
+ .setUuid({
+ val messageUuid = newUuid
+ UuidProtocol.newBuilder.setHigh(messageUuid.getTime).setLow(messageUuid.getClockSeqAndNode).build
+ })
+ .setActorInfo(actorInfo)
+ .setOneWay(isOneWay)
message match {
- case Right(message) =>
+ case Right(message) ⇒
messageBuilder.setMessage(MessageSerializer.serialize(message))
- case Left(exception) =>
+ case Left(exception) ⇒
messageBuilder.setException(ExceptionProtocol.newBuilder
- .setClassname(exception.getClass.getName)
- .setMessage(empty(exception.getMessage))
- .build)
+ .setClassname(exception.getClass.getName)
+ .setMessage(empty(exception.getMessage))
+ .build)
}
def empty(s: String): String = s match {
- case null => ""
- case s => s
+ case null ⇒ ""
+ case s ⇒ s
}
secureCookie.foreach(messageBuilder.setCookie(_))
@@ -265,14 +264,13 @@ object RemoteActorSerialization {
}
} */
- if( senderOption.isDefined)
+ if (senderOption.isDefined)
messageBuilder.setSender(toRemoteActorRefProtocol(senderOption.get))
messageBuilder
}
}
-
/**
* Module for local typed actor serialization.
*/
@@ -294,22 +292,22 @@ object TypedActorSerialization {
toBinary(a)(format)
private def toSerializedTypedActorRefProtocol[T <: Actor](
- proxy: AnyRef, format: Format[T]): SerializedTypedActorRefProtocol = {
+ proxy: AnyRef, format: Format[T]): SerializedTypedActorRefProtocol = {
val init = AspectInitRegistry.initFor(proxy)
if (init eq null) throw new IllegalArgumentException("Proxy for typed actor could not be found in AspectInitRegistry.")
SerializedTypedActorRefProtocol.newBuilder
- .setActorRef(ActorSerialization.toSerializedActorRefProtocol(init.actorRef, format))
- .setInterfaceName(init.interfaceClass.getName)
- .build
+ .setActorRef(ActorSerialization.toSerializedActorRefProtocol(init.actorRef, format))
+ .setInterfaceName(init.interfaceClass.getName)
+ .build
}
private def fromBinaryToLocalTypedActorRef[T <: Actor, U <: AnyRef](bytes: Array[Byte], format: Format[T]): U =
fromProtobufToLocalTypedActorRef(SerializedTypedActorRefProtocol.newBuilder.mergeFrom(bytes).build, format, None)
private def fromProtobufToLocalTypedActorRef[T <: Actor, U <: AnyRef](
- protocol: SerializedTypedActorRefProtocol, format: Format[T], loader: Option[ClassLoader]): U = {
+ protocol: SerializedTypedActorRefProtocol, format: Format[T], loader: Option[ClassLoader]): U = {
val actorRef = ActorSerialization.fromProtobufToLocalActorRef(protocol.getActorRef, format, loader)
val intfClass = toClass(loader, protocol.getInterfaceName)
TypedActor.newInstance(intfClass, actorRef).asInstanceOf[U]
@@ -360,8 +358,8 @@ object RemoteTypedActorSerialization {
def toRemoteTypedActorRefProtocol(proxy: AnyRef): RemoteTypedActorRefProtocol = {
val init = AspectInitRegistry.initFor(proxy)
RemoteTypedActorRefProtocol.newBuilder
- .setActorRef(RemoteActorSerialization.toRemoteActorRefProtocol(init.actorRef))
- .setInterfaceName(init.interfaceClass.getName)
- .build
+ .setActorRef(RemoteActorSerialization.toRemoteActorRefProtocol(init.actorRef))
+ .setInterfaceName(init.interfaceClass.getName)
+ .build
}
}
diff --git a/akka-remote/src/main/scala/akka/serialization/Serializer.scala b/akka-remote/src/main/scala/akka/serialization/Serializer.scala
index 2b58d05f87..9c387503d3 100644
--- a/akka-remote/src/main/scala/akka/serialization/Serializer.scala
+++ b/akka-remote/src/main/scala/akka/serialization/Serializer.scala
@@ -4,7 +4,7 @@
package akka.serialization
-import java.io.{ObjectOutputStream, ByteArrayOutputStream, ObjectInputStream, ByteArrayInputStream}
+import java.io.{ ObjectOutputStream, ByteArrayOutputStream, ObjectInputStream, ByteArrayInputStream }
import org.apache.commons.io.input.ClassLoaderObjectInputStream
@@ -12,7 +12,7 @@ import com.google.protobuf.Message
import org.codehaus.jackson.map.ObjectMapper
-import sjson.json.{Serializer => SJSONSerializer}
+import sjson.json.{ Serializer ⇒ SJSONSerializer }
// For Java API
class SerializerFactory {
diff --git a/akka-remote/src/test/scala/Issue855Spec.scala b/akka-remote/src/test/scala/Issue855Spec.scala
index 27ee5e1051..53606f6e8c 100644
--- a/akka-remote/src/test/scala/Issue855Spec.scala
+++ b/akka-remote/src/test/scala/Issue855Spec.scala
@@ -9,29 +9,25 @@ import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import akka.config.TypedActorConfigurator
import akka.dispatch.Dispatchers
-import ticket855.{Ticket855ServiceImpl, Ticket855Service}
+import ticket855.{ Ticket855ServiceImpl, Ticket855Service }
import akka.routing.CyclicIterator
-import org.scalatest.{BeforeAndAfterAll, WordSpec, BeforeAndAfterEach}
+import org.scalatest.{ BeforeAndAfterAll, WordSpec, BeforeAndAfterEach }
import akka.util.Duration
@RunWith(classOf[JUnitRunner])
-class Issue855Spec extends
- WordSpec with
- MustMatchers with
- BeforeAndAfterEach with
- BeforeAndAfterAll {
+class Issue855Spec extends WordSpec with MustMatchers with BeforeAndAfterEach with BeforeAndAfterAll {
import akka.actor.Actor._
override def afterEach {
-// registry.local.shutdownAll()
-// remote.shutdown
+ // registry.local.shutdownAll()
+ // remote.shutdown
}
"TypedActors with Future return types" must {
"must work for Remote Typed Actors" in {
-/* remote.start
+ /* remote.start
Thread.sleep(500)
val configuration = new TypedActorConfiguration
diff --git a/akka-remote/src/test/scala/remote/AkkaRemoteTest.scala b/akka-remote/src/test/scala/remote/AkkaRemoteTest.scala
index 7ad4584a08..96189a5dce 100644
--- a/akka-remote/src/test/scala/remote/AkkaRemoteTest.scala
+++ b/akka-remote/src/test/scala/remote/AkkaRemoteTest.scala
@@ -4,25 +4,21 @@ import org.scalatest.matchers.MustMatchers
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import akka.remote.netty.NettyRemoteSupport
-import akka.actor. {Actor, ActorRegistry}
-import java.util.concurrent. {TimeUnit, CountDownLatch}
-import org.scalatest.{Spec, WordSpec, BeforeAndAfterAll, BeforeAndAfterEach}
+import akka.actor.{ Actor, ActorRegistry }
+import java.util.concurrent.{ TimeUnit, CountDownLatch }
+import org.scalatest.{ Spec, WordSpec, BeforeAndAfterAll, BeforeAndAfterEach }
import java.util.concurrent.atomic.AtomicBoolean
object AkkaRemoteTest {
class ReplyHandlerActor(latch: CountDownLatch, expect: String) extends Actor {
def receive = {
- case x: String if x == expect => latch.countDown()
+ case x: String if x == expect ⇒ latch.countDown()
}
}
}
@RunWith(classOf[JUnitRunner])
-class AkkaRemoteTest extends
- WordSpec with
- MustMatchers with
- BeforeAndAfterAll with
- BeforeAndAfterEach {
+class AkkaRemoteTest extends WordSpec with MustMatchers with BeforeAndAfterAll with BeforeAndAfterEach {
import AkkaRemoteTest._
val remote = Actor.remote
@@ -46,7 +42,7 @@ class AkkaRemoteTest extends
}
override def beforeEach() {
- remote.start(host,port)
+ remote.start(host, port)
super.beforeEach
}
@@ -61,14 +57,14 @@ class AkkaRemoteTest extends
def replyHandler(latch: CountDownLatch, expect: String) = Some(Actor.actorOf(new ReplyHandlerActor(latch, expect)).start())
}
-trait NetworkFailureTest { self: WordSpec =>
+trait NetworkFailureTest { self: WordSpec ⇒
import akka.actor.Actor._
import akka.util.Duration
// override is subclass if needed
val BYTES_PER_SECOND = "60KByte/s"
- val DELAY_MILLIS = "350ms"
- val PORT_RANGE = "1024-65535"
+ val DELAY_MILLIS = "350ms"
+ val PORT_RANGE = "1024-65535"
// FIXME add support for TCP FIN by hooking into Netty and do socket.close
@@ -80,7 +76,7 @@ trait NetworkFailureTest { self: WordSpec =>
Thread.sleep(duration.toMillis)
restoreIP
} catch {
- case e =>
+ case e ⇒
dead.set(true)
e.printStackTrace
}
@@ -95,7 +91,7 @@ trait NetworkFailureTest { self: WordSpec =>
Thread.sleep(duration.toMillis)
restoreIP
} catch {
- case e =>
+ case e ⇒
dead.set(true)
e.printStackTrace
}
@@ -110,7 +106,7 @@ trait NetworkFailureTest { self: WordSpec =>
Thread.sleep(duration.toMillis)
restoreIP
} catch {
- case e =>
+ case e ⇒
dead.set(true)
e.printStackTrace
}
diff --git a/akka-remote/src/test/scala/remote/OptimizedLocalScopedSpec.scala b/akka-remote/src/test/scala/remote/OptimizedLocalScopedSpec.scala
index 4251b496d2..7338fe0dc1 100644
--- a/akka-remote/src/test/scala/remote/OptimizedLocalScopedSpec.scala
+++ b/akka-remote/src/test/scala/remote/OptimizedLocalScopedSpec.scala
@@ -1,10 +1,10 @@
package akka.actor.remote
-import akka.actor.{Actor}
+import akka.actor.{ Actor }
object OptimizedLocalScopedSpec {
class TestActor extends Actor {
- def receive = { case _ => }
+ def receive = { case _ ⇒ }
}
}
@@ -17,7 +17,7 @@ class OptimizedLocalScopedSpec extends AkkaRemoteTest {
val fooActor = Actor.actorOf[TestActor].start()
remote.register("foo", fooActor)
- remote.actorFor("foo", host, port) must be (fooActor)
+ remote.actorFor("foo", host, port) must be(fooActor)
}
}
}
\ No newline at end of file
diff --git a/akka-remote/src/test/scala/remote/RemoteErrorHandlingNetworkTest.scala b/akka-remote/src/test/scala/remote/RemoteErrorHandlingNetworkTest.scala
index 72a2d00ac1..4c6a8dd9f6 100644
--- a/akka-remote/src/test/scala/remote/RemoteErrorHandlingNetworkTest.scala
+++ b/akka-remote/src/test/scala/remote/RemoteErrorHandlingNetworkTest.scala
@@ -1,9 +1,9 @@
package akka.actor.remote
-import java.util.concurrent.{CountDownLatch, TimeUnit}
+import java.util.concurrent.{ CountDownLatch, TimeUnit }
import akka.actor.Actor._
-import akka.actor.{ActorRef, Actor}
+import akka.actor.{ ActorRef, Actor }
import akka.util.duration._
import java.util.concurrent.atomic.AtomicBoolean
@@ -13,20 +13,20 @@ object RemoteErrorHandlingNetworkTest {
class RemoteActorSpecActorUnidirectional extends Actor {
def receive = {
- case "Ping" => self.reply_?("Pong")
+ case "Ping" ⇒ self.reply_?("Pong")
}
}
class Decrementer extends Actor {
def receive = {
- case "done" => self.reply_?(false)
- case i: Int if i > 0 =>
+ case "done" ⇒ self.reply_?(false)
+ case i: Int if i > 0 ⇒
self.reply_?(i - 1)
- case i: Int =>
+ case i: Int ⇒
self.reply_?(0)
this become {
- case "done" => self.reply_?(true)
- case _ => //Do Nothing
+ case "done" ⇒ self.reply_?(true)
+ case _ ⇒ //Do Nothing
}
}
}
@@ -34,18 +34,18 @@ object RemoteErrorHandlingNetworkTest {
class RemoteActorSpecActorBidirectional extends Actor {
def receive = {
- case "Hello" =>
+ case "Hello" ⇒
self.reply("World")
- case "Failure" =>
+ case "Failure" ⇒
throw new RuntimeException("Expected exception; to test fault-tolerance")
}
}
class RemoteActorSpecActorAsyncSender(latch: CountDownLatch) extends Actor {
def receive = {
- case Send(actor: ActorRef) =>
+ case Send(actor: ActorRef) ⇒
actor ! "Hello"
- case "World" => latch.countDown()
+ case "World" ⇒ latch.countDown()
}
}
}
@@ -68,15 +68,15 @@ class RemoteErrorHandlingNetworkTest extends AkkaRemoteTest with NetworkFailureT
actor ! "Ping"
actor ! "Ping"
val dead = new AtomicBoolean(false)
- dropNetworkFor (10 seconds, dead) // drops the network - in another thread - so async
- sleepFor (2 seconds) // wait until network drop is done before sending the other messages
- try { actor ! "Ping" } catch { case e => () } // queue up messages
- try { actor ! "Ping" } catch { case e => () } // ...
- try { actor ! "Ping" } catch { case e => () } // ...
- try { actor ! "Ping" } catch { case e => () } // ...
- try { actor ! "Ping" } catch { case e => () } // ...
- latch.await(15, TimeUnit.SECONDS) must be (true) // network should be restored and the messages delivered
- dead.get must be (false)
+ dropNetworkFor(10 seconds, dead) // drops the network - in another thread - so async
+ sleepFor(2 seconds) // wait until network drop is done before sending the other messages
+ try { actor ! "Ping" } catch { case e ⇒ () } // queue up messages
+ try { actor ! "Ping" } catch { case e ⇒ () } // ...
+ try { actor ! "Ping" } catch { case e ⇒ () } // ...
+ try { actor ! "Ping" } catch { case e ⇒ () } // ...
+ try { actor ! "Ping" } catch { case e ⇒ () } // ...
+ latch.await(15, TimeUnit.SECONDS) must be(true) // network should be restored and the messages delivered
+ dead.get must be(false)
}
"be able to recover from TCP RESET without loosing any messages" in {
@@ -92,17 +92,17 @@ class RemoteErrorHandlingNetworkTest extends AkkaRemoteTest with NetworkFailureT
actor ! "Ping"
actor ! "Ping"
val dead = new AtomicBoolean(false)
- replyWithTcpResetFor (10 seconds, dead)
- sleepFor (2 seconds)
- try { actor ! "Ping" } catch { case e => () } // queue up messages
- try { actor ! "Ping" } catch { case e => () } // ...
- try { actor ! "Ping" } catch { case e => () } // ...
- try { actor ! "Ping" } catch { case e => () } // ...
- try { actor ! "Ping" } catch { case e => () } // ...
- latch.await(15, TimeUnit.SECONDS) must be (true)
- dead.get must be (false)
+ replyWithTcpResetFor(10 seconds, dead)
+ sleepFor(2 seconds)
+ try { actor ! "Ping" } catch { case e ⇒ () } // queue up messages
+ try { actor ! "Ping" } catch { case e ⇒ () } // ...
+ try { actor ! "Ping" } catch { case e ⇒ () } // ...
+ try { actor ! "Ping" } catch { case e ⇒ () } // ...
+ try { actor ! "Ping" } catch { case e ⇒ () } // ...
+ latch.await(15, TimeUnit.SECONDS) must be(true)
+ dead.get must be(false)
}
-/*
+ /*
"sendWithBangAndGetReplyThroughSenderRef" in {
remote.register(actorOf[RemoteActorSpecActorBidirectional])
implicit val timeout = 500000000L
diff --git a/akka-remote/src/test/scala/remote/RemoteSupervisorSpec.scala b/akka-remote/src/test/scala/remote/RemoteSupervisorSpec.scala
index 564bba9927..21a96db023 100644
--- a/akka-remote/src/test/scala/remote/RemoteSupervisorSpec.scala
+++ b/akka-remote/src/test/scala/remote/RemoteSupervisorSpec.scala
@@ -4,13 +4,13 @@
package akka.actor.remote
-import java.util.concurrent.{LinkedBlockingQueue, TimeUnit, BlockingQueue}
+import java.util.concurrent.{ LinkedBlockingQueue, TimeUnit, BlockingQueue }
import akka.config.Supervision._
import akka.OneWay
import org.scalatest._
import org.scalatest.WordSpec
import org.scalatest.matchers.MustMatchers
-import akka.actor.{SupervisorFactory, Supervisor, ActorRef, Actor}
+import akka.actor.{ SupervisorFactory, Supervisor, ActorRef, Actor }
import Actor._
object Log {
@@ -25,14 +25,14 @@ object Log {
class RemotePingPong1Actor extends Actor with scala.Serializable {
def receive = {
- case "Ping" =>
+ case "Ping" ⇒
Log.messageLog.put("ping")
self.reply("pong")
- case OneWay =>
+ case OneWay ⇒
Log.oneWayLog.put("oneway")
- case "Die" =>
+ case "Die" ⇒
throw new RuntimeException("Expected exception; to test fault-tolerance")
}
@@ -43,10 +43,10 @@ class RemotePingPong1Actor extends Actor with scala.Serializable {
class RemotePingPong2Actor extends Actor with scala.Serializable {
def receive = {
- case "Ping" =>
+ case "Ping" ⇒
Log.messageLog.put("ping")
self.reply("pong")
- case "Die" =>
+ case "Die" ⇒
throw new RuntimeException("Expected exception; to test fault-tolerance")
}
@@ -57,10 +57,10 @@ class RemotePingPong2Actor extends Actor with scala.Serializable {
class RemotePingPong3Actor extends Actor with scala.Serializable {
def receive = {
- case "Ping" =>
+ case "Ping" ⇒
Log.messageLog.put("ping")
self.reply("pong")
- case "Die" =>
+ case "Die" ⇒
throw new RuntimeException("Expected exception; to test fault-tolerance")
}
diff --git a/akka-remote/src/test/scala/remote/RemoteTypedActorSpec.scala b/akka-remote/src/test/scala/remote/RemoteTypedActorSpec.scala
index 34153fab02..ac61ee79d5 100644
--- a/akka-remote/src/test/scala/remote/RemoteTypedActorSpec.scala
+++ b/akka-remote/src/test/scala/remote/RemoteTypedActorSpec.scala
@@ -4,9 +4,8 @@
package akka.actor.remote
-import java.util.concurrent.{LinkedBlockingQueue, TimeUnit, BlockingQueue}
-import akka.config. {RemoteAddress, Config, TypedActorConfigurator}
-
+import java.util.concurrent.{ LinkedBlockingQueue, TimeUnit, BlockingQueue }
+import akka.config.{ RemoteAddress, Config, TypedActorConfigurator }
object RemoteTypedActorLog {
val messageLog: BlockingQueue[String] = new LinkedBlockingQueue[String]
diff --git a/akka-remote/src/test/scala/remote/ServerInitiatedRemoteActorSample.scala b/akka-remote/src/test/scala/remote/ServerInitiatedRemoteActorSample.scala
index 0c5a9565a6..83ed04ac8f 100644
--- a/akka-remote/src/test/scala/remote/ServerInitiatedRemoteActorSample.scala
+++ b/akka-remote/src/test/scala/remote/ServerInitiatedRemoteActorSample.scala
@@ -4,29 +4,31 @@ import akka.actor.Actor
import Actor._
import akka.event.EventHandler
-/*************************************
-Instructions how to run the sample:
-
-* Download Akka distribution.
-* Unzip and step into the Akka root dir
-* Set AKKA_HOME. For exampe 'export AKKA_HOME=`pwd`
-
-* Then open up two shells and in each run:
-* sbt
-* > project akka-remote
-* > console
-
-* Then paste in the code below into both shells.
-
-Then run:
-* ServerInitiatedRemoteActorServer.run() in one shell
-* ServerInitiatedRemoteActorClient.run() in the other shell
-Have fun.
-*************************************/
+/**
+ * ***********************************
+ * Instructions how to run the sample:
+ *
+ * Download Akka distribution.
+ * Unzip and step into the Akka root dir
+ * Set AKKA_HOME. For exampe 'export AKKA_HOME=`pwd`
+ *
+ * Then open up two shells and in each run:
+ * sbt
+ * > project akka-remote
+ * > console
+ *
+ * Then paste in the code below into both shells.
+ *
+ * Then run:
+ * ServerInitiatedRemoteActorServer.run() in one shell
+ * ServerInitiatedRemoteActorClient.run() in the other shell
+ * Have fun.
+ * ***********************************
+ */
class HelloWorldActor extends Actor {
def receive = {
- case "Hello" => self.reply("World")
+ case "Hello" ⇒ self.reply("World")
}
}
diff --git a/akka-remote/src/test/scala/remote/ServerInitiatedRemoteActorSpec.scala b/akka-remote/src/test/scala/remote/ServerInitiatedRemoteActorSpec.scala
index b83372a945..e04253ae0f 100644
--- a/akka-remote/src/test/scala/remote/ServerInitiatedRemoteActorSpec.scala
+++ b/akka-remote/src/test/scala/remote/ServerInitiatedRemoteActorSpec.scala
@@ -1,29 +1,29 @@
package akka.actor.remote
-import java.util.concurrent.{CountDownLatch, TimeUnit}
+import java.util.concurrent.{ CountDownLatch, TimeUnit }
import akka.actor.Actor._
-import akka.actor.{ActorRegistry, ActorRef, Actor}
+import akka.actor.{ ActorRegistry, ActorRef, Actor }
object ServerInitiatedRemoteActorSpec {
case class Send(actor: ActorRef)
class RemoteActorSpecActorUnidirectional extends Actor {
def receive = {
- case "Ping" => self.reply_?("Pong")
+ case "Ping" ⇒ self.reply_?("Pong")
}
}
class Decrementer extends Actor {
def receive = {
- case "done" => self.reply_?(false)
- case i: Int if i > 0 =>
+ case "done" ⇒ self.reply_?(false)
+ case i: Int if i > 0 ⇒
self.reply_?(i - 1)
- case i: Int =>
+ case i: Int ⇒
self.reply_?(0)
this become {
- case "done" => self.reply_?(true)
- case _ => //Do Nothing
+ case "done" ⇒ self.reply_?(true)
+ case _ ⇒ //Do Nothing
}
}
}
@@ -31,18 +31,18 @@ object ServerInitiatedRemoteActorSpec {
class RemoteActorSpecActorBidirectional extends Actor {
def receive = {
- case "Hello" =>
+ case "Hello" ⇒
self.reply("World")
- case "Failure" =>
+ case "Failure" ⇒
throw new RuntimeException("Expected exception; to test fault-tolerance")
}
}
class RemoteActorSpecActorAsyncSender(latch: CountDownLatch) extends Actor {
def receive = {
- case Send(actor: ActorRef) =>
+ case Send(actor: ActorRef) ⇒
actor ! "Hello"
- case "World" => latch.countDown()
+ case "World" ⇒ latch.countDown()
}
}
}
@@ -50,7 +50,7 @@ object ServerInitiatedRemoteActorSpec {
class ServerInitiatedRemoteActorSpec extends AkkaRemoteTest {
import ServerInitiatedRemoteActorSpec._
"Server-managed remote actors" should {
-/*
+ /*
"sendWithBang" in {
val latch = new CountDownLatch(1)
implicit val sender = replyHandler(latch, "Pong")
@@ -171,35 +171,36 @@ class ServerInitiatedRemoteActorSpec extends AkkaRemoteTest {
}
*/
- /** FIXME rewrite after new registry changes
- "should be able to remotely communicate between 2 server-managed actors" in {
- val localFoo = actorOf[Decrementer]
- val localBar = actorOf[Decrementer]
- remote.register("foo", localFoo)
- remote.register("bar", localBar)
-
- val remoteFoo = remote.actorFor("foo", host, port)
- val remoteBar = remote.actorFor("bar", host, port)
-
- //Seed the start
- remoteFoo.!(10)(Some(remoteBar))
-
- val latch = new CountDownLatch(100)
-
- def testDone() = (remoteFoo !! "done").as[Boolean].getOrElse(false) &&
- (remoteBar !! "done").as[Boolean].getOrElse(false)
-
- while(!testDone()) {
- if (latch.await(200, TimeUnit.MILLISECONDS))
- sys.error("Test didn't complete within 100 cycles")
- else
- latch.countDown()
- }
-
- val decrementer = Actor.registry.local.actorFor[Decrementer]
- decrementers.find( _ eq localFoo) must equal (Some(localFoo))
- decrementers.find( _ eq localBar) must equal (Some(localBar))
- }
+ /**
+ * FIXME rewrite after new registry changes
+ * "should be able to remotely communicate between 2 server-managed actors" in {
+ * val localFoo = actorOf[Decrementer]
+ * val localBar = actorOf[Decrementer]
+ * remote.register("foo", localFoo)
+ * remote.register("bar", localBar)
+ *
+ * val remoteFoo = remote.actorFor("foo", host, port)
+ * val remoteBar = remote.actorFor("bar", host, port)
+ *
+ * //Seed the start
+ * remoteFoo.!(10)(Some(remoteBar))
+ *
+ * val latch = new CountDownLatch(100)
+ *
+ * def testDone() = (remoteFoo !! "done").as[Boolean].getOrElse(false) &&
+ * (remoteBar !! "done").as[Boolean].getOrElse(false)
+ *
+ * while(!testDone()) {
+ * if (latch.await(200, TimeUnit.MILLISECONDS))
+ * sys.error("Test didn't complete within 100 cycles")
+ * else
+ * latch.countDown()
+ * }
+ *
+ * val decrementer = Actor.registry.local.actorFor[Decrementer]
+ * decrementers.find( _ eq localFoo) must equal (Some(localFoo))
+ * decrementers.find( _ eq localBar) must equal (Some(localBar))
+ * }
*/
}
}
diff --git a/akka-remote/src/test/scala/remote/ServerInitiatedRemoteSessionActorSpec.scala b/akka-remote/src/test/scala/remote/ServerInitiatedRemoteSessionActorSpec.scala
index a2b16828f3..248f5d9c88 100644
--- a/akka-remote/src/test/scala/remote/ServerInitiatedRemoteSessionActorSpec.scala
+++ b/akka-remote/src/test/scala/remote/ServerInitiatedRemoteSessionActorSpec.scala
@@ -6,12 +6,12 @@ package akka.actor.remote
import akka.actor._
import akka.actor.Actor._
-import java.util.concurrent. {ConcurrentSkipListSet, TimeUnit}
+import java.util.concurrent.{ ConcurrentSkipListSet, TimeUnit }
import akka.remote.netty.NettyRemoteSupport
object ServerInitiatedRemoteSessionActorSpec {
- case class Login(user:String)
+ case class Login(user: String)
case class GetUser()
case class DoSomethingFunny()
@@ -24,9 +24,9 @@ object ServerInitiatedRemoteSessionActorSpec {
var user: String = "anonymous"
def receive = {
- case Login(user) => this.user = user
- case GetUser() => self.reply(this.user)
- case DoSomethingFunny() => throw new Exception("Bad boy")
+ case Login(user) ⇒ this.user = user
+ case GetUser() ⇒ self.reply(this.user)
+ case DoSomethingFunny() ⇒ throw new Exception("Bad boy")
}
}
diff --git a/akka-remote/src/test/scala/remote/ServerInitiatedRemoteTypedActorSpec.scala b/akka-remote/src/test/scala/remote/ServerInitiatedRemoteTypedActorSpec.scala
index 09a8c530bc..642d69aa9a 100644
--- a/akka-remote/src/test/scala/remote/ServerInitiatedRemoteTypedActorSpec.scala
+++ b/akka-remote/src/test/scala/remote/ServerInitiatedRemoteTypedActorSpec.scala
@@ -25,7 +25,7 @@ class ServerInitiatedRemoteTypedActorSpec extends AkkaRemoteTest {
def createRemoteActorRef = remote.typedActorFor(classOf[RemoteTypedActorOne], "typed-actor-service", 5000L, host, port)
"Server managed remote typed Actor " should {
-/*
+ /*
"receive one-way message" in {
val actor = createRemoteActorRef
actor.oneWay
diff --git a/akka-remote/src/test/scala/remote/ServerInitiatedRemoteTypedSessionActorSpec.scala b/akka-remote/src/test/scala/remote/ServerInitiatedRemoteTypedSessionActorSpec.scala
index 70968f65fd..4b48df60ef 100644
--- a/akka-remote/src/test/scala/remote/ServerInitiatedRemoteTypedSessionActorSpec.scala
+++ b/akka-remote/src/test/scala/remote/ServerInitiatedRemoteTypedSessionActorSpec.scala
@@ -9,7 +9,6 @@ import RemoteTypedActorLog._
class ServerInitiatedRemoteTypedSessionActorSpec extends AkkaRemoteTest {
-
override def beforeEach = {
super.beforeEach
diff --git a/akka-remote/src/test/scala/remote/UnOptimizedLocalScopedSpec.scala b/akka-remote/src/test/scala/remote/UnOptimizedLocalScopedSpec.scala
index 078a9559d0..d23d34081c 100644
--- a/akka-remote/src/test/scala/remote/UnOptimizedLocalScopedSpec.scala
+++ b/akka-remote/src/test/scala/remote/UnOptimizedLocalScopedSpec.scala
@@ -1,9 +1,9 @@
package akka.actor.remote
-import akka.actor. {ActorRegistry, Actor}
+import akka.actor.{ ActorRegistry, Actor }
object UnOptimizedLocalScopedSpec {
class TestActor extends Actor {
- def receive = { case _ => }
+ def receive = { case _ ⇒ }
}
}
diff --git a/akka-remote/src/test/scala/serialization/ProtobufActorMessageSerializationSpec.scala b/akka-remote/src/test/scala/serialization/ProtobufActorMessageSerializationSpec.scala
index 046f474f43..912a868bb6 100644
--- a/akka-remote/src/test/scala/serialization/ProtobufActorMessageSerializationSpec.scala
+++ b/akka-remote/src/test/scala/serialization/ProtobufActorMessageSerializationSpec.scala
@@ -1,6 +1,6 @@
package akka.actor.serialization
-import akka.actor.{ProtobufProtocol, Actor}
+import akka.actor.{ ProtobufProtocol, Actor }
import ProtobufProtocol.ProtobufPOJO
import Actor._
import akka.actor.remote.AkkaRemoteTest
@@ -18,10 +18,10 @@ message ProtobufPOJO {
object ProtobufActorMessageSerializationSpec {
class RemoteActorSpecActorBidirectional extends Actor {
def receive = {
- case pojo: ProtobufPOJO =>
+ case pojo: ProtobufPOJO ⇒
val id = pojo.getId
self.reply(id + 1)
- case msg =>
+ case msg ⇒
throw new RuntimeException("Expected a ProtobufPOJO message but got: " + msg)
}
}
diff --git a/akka-remote/src/test/scala/serialization/ScalaJSONSerializableSpec.scala b/akka-remote/src/test/scala/serialization/ScalaJSONSerializableSpec.scala
index 435f94db1c..c83b1ed02a 100644
--- a/akka-remote/src/test/scala/serialization/ScalaJSONSerializableSpec.scala
+++ b/akka-remote/src/test/scala/serialization/ScalaJSONSerializableSpec.scala
@@ -12,8 +12,7 @@ object Serializables {
import DefaultProtocol._
import JsonSerialization._
- case class Shop(store: String, item: String, price: Int) extends
- ScalaJSON[Shop] {
+ case class Shop(store: String, item: String, price: Int) extends ScalaJSON[Shop] {
implicit val ShopFormat: sjson.json.Format[Shop] =
asProduct3("store", "item", "price")(Shop)(Shop.unapply(_).get)
@@ -28,7 +27,7 @@ object Serializables {
asProduct2("id", "value")(MyMessage)(MyMessage.unapply(_).get)
case class MyJsonObject(val key: String, val map: Map[String, Int],
- val standAloneInt: Int) extends ScalaJSON[MyJsonObject] {
+ val standAloneInt: Int) extends ScalaJSON[MyJsonObject] {
implicit val MyJsonObjectFormat: sjson.json.Format[MyJsonObject] =
asProduct3("key", "map", "standAloneInt")(MyJsonObject)(MyJsonObject.unapply(_).get)
@@ -40,10 +39,7 @@ object Serializables {
}
@RunWith(classOf[JUnitRunner])
-class ScalaJSONSerializableSpec extends
- Spec with
- ShouldMatchers with
- BeforeAndAfterAll {
+class ScalaJSONSerializableSpec extends Spec with ShouldMatchers with BeforeAndAfterAll {
import Serializables._
describe("Serialization of case classes") {
diff --git a/akka-remote/src/test/scala/serialization/ScalaJSONSerializerSpec.scala b/akka-remote/src/test/scala/serialization/ScalaJSONSerializerSpec.scala
index a17db38342..d973922c45 100644
--- a/akka-remote/src/test/scala/serialization/ScalaJSONSerializerSpec.scala
+++ b/akka-remote/src/test/scala/serialization/ScalaJSONSerializerSpec.scala
@@ -20,16 +20,13 @@ object Protocols {
asProduct2("id", "value")(MyMessage)(MyMessage.unapply(_).get)
case class MyJsonObject(val key: String, val map: Map[String, Int],
- val standAloneInt: Int)
+ val standAloneInt: Int)
implicit val MyJsonObjectFormat: sjson.json.Format[MyJsonObject] =
asProduct3("key", "map", "standAloneInt")(MyJsonObject)(MyJsonObject.unapply(_).get)
}
@RunWith(classOf[JUnitRunner])
-class ScalaJSONSerializerSpec extends
- Spec with
- ShouldMatchers with
- BeforeAndAfterAll {
+class ScalaJSONSerializerSpec extends Spec with ShouldMatchers with BeforeAndAfterAll {
import Protocols._
import ScalaJSON._
diff --git a/akka-remote/src/test/scala/serialization/SerializableTypeClassActorSpec.scala b/akka-remote/src/test/scala/serialization/SerializableTypeClassActorSpec.scala
index d30c62fb07..82d2df9c2c 100644
--- a/akka-remote/src/test/scala/serialization/SerializableTypeClassActorSpec.scala
+++ b/akka-remote/src/test/scala/serialization/SerializableTypeClassActorSpec.scala
@@ -1,6 +1,5 @@
package akka.actor.serialization
-
import org.scalatest.Spec
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.BeforeAndAfterAll
@@ -14,10 +13,7 @@ import ActorSerialization._
import Actor._
@RunWith(classOf[JUnitRunner])
-class SerializableTypeClassActorSpec extends
- Spec with
- ShouldMatchers with
- BeforeAndAfterAll {
+class SerializableTypeClassActorSpec extends Spec with ShouldMatchers with BeforeAndAfterAll {
object BinaryFormatMyActor {
implicit object MyActorFormat extends Format[MyActor] {
@@ -164,7 +160,7 @@ class SerializableTypeClassActorSpec extends
(actor2 !! "hello").getOrElse("_") should equal("world 3")
}
*/
-/*
+ /*
it("should be able to serialize and de-serialize an hotswapped actor") {
import BinaryFormatMyActor._
@@ -189,7 +185,7 @@ class SerializableTypeClassActorSpec extends
*/
}
-/*
+ /*
describe("Custom serializable actors") {
it("should serialize and de-serialize") {
import BinaryFormatMyActorWithSerializableMessages._
@@ -240,7 +236,7 @@ class MyActorWithDualCounter extends Actor {
var count1 = 0
var count2 = 0
def receive = {
- case "hello" =>
+ case "hello" ⇒
count1 = count1 + 1
count2 = count2 + 1
self.reply("world " + count1 + " " + count2)
@@ -251,27 +247,27 @@ class MyActor extends Actor with scala.Serializable {
var count = 0
def receive = {
- case "hello" =>
+ case "hello" ⇒
count = count + 1
self.reply("world " + count)
- case "swap" =>
- become { case "hello" => self.reply("swapped") }
+ case "swap" ⇒
+ become { case "hello" ⇒ self.reply("swapped") }
}
}
class MyStatelessActor extends Actor {
def receive = {
- case "hello" =>
+ case "hello" ⇒
self.reply("world")
}
}
class MyStatelessActorWithMessagesInMailbox extends Actor {
def receive = {
- case "hello" =>
+ case "hello" ⇒
//println("# messages in mailbox " + self.mailboxSize)
Thread.sleep(500)
- case "hello-reply" => self.reply("world")
+ case "hello-reply" ⇒ self.reply("world")
}
}
@@ -280,7 +276,7 @@ class MyJavaSerializableActor extends Actor with scala.Serializable {
self.receiveTimeout = Some(1000)
def receive = {
- case "hello" =>
+ case "hello" ⇒
count = count + 1
self.reply("world " + count)
}
@@ -288,10 +284,10 @@ class MyJavaSerializableActor extends Actor with scala.Serializable {
class MyActorWithSerializableMessages extends Actor {
def receive = {
- case MyMessage(s, t) =>
+ case MyMessage(s, t) ⇒
//println("# messages in mailbox " + self.mailboxSize)
Thread.sleep(500)
- case "hello-reply" => self.reply("world")
+ case "hello-reply" ⇒ self.reply("world")
}
}
diff --git a/akka-remote/src/test/scala/serialization/SerializerSpec.scala b/akka-remote/src/test/scala/serialization/SerializerSpec.scala
index 349c772f59..bd78a46366 100644
--- a/akka-remote/src/test/scala/serialization/SerializerSpec.scala
+++ b/akka-remote/src/test/scala/serialization/SerializerSpec.scala
@@ -15,7 +15,6 @@ case class MyMessage(val id: String, val value: Tuple2[String, Int]) {
private def this() = this(null, null)
}
-
class SerializerSpec extends JUnitSuite {
@Test
def shouldSerializeString = {
diff --git a/akka-remote/src/test/scala/serialization/Ticket435Spec.scala b/akka-remote/src/test/scala/serialization/Ticket435Spec.scala
index f1308e3f0e..8b0dbbb06f 100644
--- a/akka-remote/src/test/scala/serialization/Ticket435Spec.scala
+++ b/akka-remote/src/test/scala/serialization/Ticket435Spec.scala
@@ -1,6 +1,5 @@
package akka.actor.serialization
-
import org.scalatest.Spec
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.BeforeAndAfterAll
@@ -13,10 +12,7 @@ import ActorSerialization._
import Actor._
@RunWith(classOf[JUnitRunner])
-class Ticket435Spec extends
- Spec with
- ShouldMatchers with
- BeforeAndAfterAll {
+class Ticket435Spec extends Spec with ShouldMatchers with BeforeAndAfterAll {
object BinaryFormatMyStatefulActor {
implicit object MyStatefulActorFormat extends Format[MyStatefulActor] {
@@ -116,10 +112,10 @@ class MyStatefulActor extends Actor {
var count = 0
def receive = {
- case "hi" =>
+ case "hi" ⇒
//println("# messages in mailbox " + self.mailboxSize)
Thread.sleep(500)
- case "hello" =>
+ case "hello" ⇒
count = count + 1
self.reply("world " + count)
}
diff --git a/akka-remote/src/test/scala/serialization/TypedActorSerializationSpec.scala b/akka-remote/src/test/scala/serialization/TypedActorSerializationSpec.scala
index adac6be14e..b241d9976f 100644
--- a/akka-remote/src/test/scala/serialization/TypedActorSerializationSpec.scala
+++ b/akka-remote/src/test/scala/serialization/TypedActorSerializationSpec.scala
@@ -2,7 +2,6 @@
* Copyright (C) 2009-2011 Scalable Solutions AB
*/
-
package akka.actor.serialization
import akka.serialization._
@@ -37,9 +36,8 @@ class TypedActorSerializationSpec extends AkkaRemoteTest {
ProtobufProtocol.DualCounter.newBuilder.setCount1(ac.count1).setCount2(ac.count2).build.toByteArray
}
-
"Serializable typed actor" should {
-/*
+ /*
"should be able to serialize and de-serialize a stateless typed actor" in {
val typedActor1 = TypedActor.newInstance(classOf[MyTypedActor], classOf[MyStatelessTypedActorImpl], 1000)
typedActor1.requestReply("hello") must equal("world")
@@ -85,10 +83,9 @@ class TypedActorSerializationSpec extends AkkaRemoteTest {
}
}
-
trait MyTypedActor {
- def requestReply(s: String) : String
- def oneWay() : Unit
+ def requestReply(s: String): String
+ def oneWay(): Unit
}
class MyTypedActorImpl extends TypedActor with MyTypedActor {
@@ -98,7 +95,7 @@ class MyTypedActorImpl extends TypedActor with MyTypedActor {
println("got oneWay message")
}
- override def requestReply(message: String) : String = {
+ override def requestReply(message: String): String = {
count = count + 1
if (message == "hello") {
"world " + count
@@ -114,7 +111,7 @@ class MyTypedActorWithDualCounter extends TypedActor with MyTypedActor {
println("got oneWay message")
}
- override def requestReply(message: String) : String = {
+ override def requestReply(message: String): String = {
count1 = count1 + 1
count2 = count2 + 1
@@ -130,7 +127,7 @@ class MyStatelessTypedActorImpl extends TypedActor with MyTypedActor {
println("got oneWay message")
}
- override def requestReply(message: String) : String = {
+ override def requestReply(message: String): String = {
if (message == "hello") "world" else ("hello " + message)
}
}
diff --git a/akka-remote/src/test/scala/serialization/UntypedActorSerializationSpec.scala b/akka-remote/src/test/scala/serialization/UntypedActorSerializationSpec.scala
index b62ebc1863..e16bb44322 100644
--- a/akka-remote/src/test/scala/serialization/UntypedActorSerializationSpec.scala
+++ b/akka-remote/src/test/scala/serialization/UntypedActorSerializationSpec.scala
@@ -1,6 +1,5 @@
package akka.actor.serialization
-
import org.scalatest.Spec
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.BeforeAndAfterAll
@@ -13,10 +12,7 @@ import ActorSerialization._
import Actor._
@RunWith(classOf[JUnitRunner])
-class UntypedActorSerializationSpec extends
- Spec with
- ShouldMatchers with
- BeforeAndAfterAll {
+class UntypedActorSerializationSpec extends Spec with ShouldMatchers with BeforeAndAfterAll {
class MyUntypedActorFormat extends Format[MyUntypedActor] {
def fromBinary(bytes: Array[Byte], act: MyUntypedActor) = {
@@ -82,13 +78,13 @@ class UntypedActorSerializationSpec extends
class MyUntypedActor extends UntypedActor {
var count = 0
def onReceive(message: Any): Unit = message match {
- case m: String if m == "hello" =>
+ case m: String if m == "hello" ⇒
count = count + 1
getContext.replyUnsafe("world " + count)
- case m: String =>
+ case m: String ⇒
count = count + 1
getContext.replyUnsafe("hello " + m + " " + count)
- case _ =>
+ case _ ⇒
throw new Exception("invalid message type")
}
}
@@ -98,26 +94,26 @@ class MyUntypedActorWithDualCounter extends UntypedActor {
var count2 = 0
def onReceive(message: Any): Unit = message match {
- case m: String if m == "hello" =>
+ case m: String if m == "hello" ⇒
count1 = count1 + 1
count2 = count2 + 1
getContext.replyUnsafe("world " + count1 + " " + count2)
- case m: String =>
+ case m: String ⇒
count1 = count1 + 1
count2 = count2 + 1
getContext.replyUnsafe("hello " + m + " " + count1 + " " + count2)
- case _ =>
+ case _ ⇒
throw new Exception("invalid message type")
}
}
class MyUntypedStatelessActor extends UntypedActor {
def onReceive(message: Any): Unit = message match {
- case m: String if m == "hello" =>
+ case m: String if m == "hello" ⇒
getContext.replyUnsafe("world")
- case m: String =>
+ case m: String ⇒
getContext.replyUnsafe("hello " + m)
- case _ =>
+ case _ ⇒
throw new Exception("invalid message type")
}
}
diff --git a/akka-remote/src/test/scala/ticket/Ticket001Spec.scala b/akka-remote/src/test/scala/ticket/Ticket001Spec.scala
index d4de2675fb..78e20bf80d 100644
--- a/akka-remote/src/test/scala/ticket/Ticket001Spec.scala
+++ b/akka-remote/src/test/scala/ticket/Ticket001Spec.scala
@@ -7,7 +7,7 @@ class Ticket001Spec extends WordSpec with MustMatchers {
"An XXX" should {
"do YYY" in {
- 1 must be (1)
+ 1 must be(1)
}
}
}
diff --git a/akka-remote/src/test/scala/ticket/Ticket434Spec.scala b/akka-remote/src/test/scala/ticket/Ticket434Spec.scala
index dbeaa15362..c6bf83738f 100644
--- a/akka-remote/src/test/scala/ticket/Ticket434Spec.scala
+++ b/akka-remote/src/test/scala/ticket/Ticket434Spec.scala
@@ -3,9 +3,8 @@
*/
package akka.actor.ticket
-
import akka.actor.Actor._
-import akka.actor.{Uuid,newUuid,uuidFrom}
+import akka.actor.{ Uuid, newUuid, uuidFrom }
import akka.actor.remote.ServerInitiatedRemoteActorSpec.RemoteActorSpecActorUnidirectional
import akka.remote.protocol.RemoteProtocol._
import akka.actor.remote.AkkaRemoteTest
diff --git a/akka-remote/src/test/scala/ticket/Ticket506Spec.scala b/akka-remote/src/test/scala/ticket/Ticket506Spec.scala
index 89d31517c5..d2aa49bc90 100644
--- a/akka-remote/src/test/scala/ticket/Ticket506Spec.scala
+++ b/akka-remote/src/test/scala/ticket/Ticket506Spec.scala
@@ -1,22 +1,22 @@
package ticket
-import akka.actor.{Actor, ActorRef}
+import akka.actor.{ Actor, ActorRef }
import akka.serialization.RemoteActorSerialization
import akka.actor.Actor.actorOf
-import java.util.concurrent.{CountDownLatch, TimeUnit}
+import java.util.concurrent.{ CountDownLatch, TimeUnit }
import akka.actor.remote.AkkaRemoteTest
-case class RecvActorRef(bytes:Array[Byte])
+case class RecvActorRef(bytes: Array[Byte])
class ActorRefService(latch: CountDownLatch) extends Actor {
import self._
- def receive:Receive = {
- case RecvActorRef(bytes) =>
+ def receive: Receive = {
+ case RecvActorRef(bytes) ⇒
val ref = RemoteActorSerialization.fromBinaryToRemoteActorRef(bytes)
ref ! "hello"
- case "hello" => latch.countDown()
+ case "hello" ⇒ latch.countDown()
}
}
diff --git a/akka-slf4j/src/main/scala/akka/event/slf4j/SLF4J.scala b/akka-slf4j/src/main/scala/akka/event/slf4j/SLF4J.scala
index 77ca1f69be..7a1f9d2c5d 100644
--- a/akka-slf4j/src/main/scala/akka/event/slf4j/SLF4J.scala
+++ b/akka-slf4j/src/main/scala/akka/event/slf4j/SLF4J.scala
@@ -4,7 +4,7 @@
package akka.event.slf4j
-import org.slf4j.{Logger => SLFLogger, LoggerFactory => SLFLoggerFactory}
+import org.slf4j.{ Logger ⇒ SLFLogger, LoggerFactory ⇒ SLFLoggerFactory }
import akka.event.EventHandler
import akka.actor._
@@ -16,13 +16,14 @@ import Actor._
* @author Jonas Bonér
*/
trait Logging {
- @transient lazy val log = Logger(this.getClass.getName)
+ @transient
+ lazy val log = Logger(this.getClass.getName)
}
object Logger {
- def apply(logger: String) : SLFLogger = SLFLoggerFactory getLogger logger
+ def apply(logger: String): SLFLogger = SLFLoggerFactory getLogger logger
def apply(clazz: Class[_]): SLFLogger = apply(clazz.getName)
- def root : SLFLogger = apply(SLFLogger.ROOT_LOGGER_NAME)
+ def root: SLFLogger = apply(SLFLogger.ROOT_LOGGER_NAME)
}
/**
@@ -36,21 +37,20 @@ class Slf4jEventHandler extends Actor with Logging {
self.dispatcher = EventHandlerDispatcher
def receive = {
- case Error(cause, instance, message) =>
+ case Error(cause, instance, message) ⇒
log.error("\n\t[{}]\n\t[{}]\n\t[{}]",
- Array[Any](instance.getClass.getName, message, stackTraceFor(cause)))
+ Array[Any](instance.getClass.getName, message, stackTraceFor(cause)))
- case Warning(instance, message) =>
+ case Warning(instance, message) ⇒
log.warn("\n\t[{}]\n\t[{}]", instance.getClass.getName, message)
- case Info(instance, message) =>
+ case Info(instance, message) ⇒
log.info("\n\t[{}]\n\t[{}]", instance.getClass.getName, message)
- case Debug(instance, message) =>
+ case Debug(instance, message) ⇒
log.debug("\n\t[{}]\n\t[{}]", instance.getClass.getName, message)
- case event => log.debug("\n\t[{}]", event.toString)
+ case event ⇒ log.debug("\n\t[{}]", event.toString)
}
}
-
diff --git a/akka-stm/src/main/scala/akka/agent/Agent.scala b/akka-stm/src/main/scala/akka/agent/Agent.scala
index 378ee2995e..0f371ea168 100644
--- a/akka-stm/src/main/scala/akka/agent/Agent.scala
+++ b/akka-stm/src/main/scala/akka/agent/Agent.scala
@@ -6,13 +6,13 @@ package akka.agent
import akka.stm._
import akka.actor.Actor
-import akka.japi.{Function => JFunc, Procedure => JProc}
-import akka.dispatch.{DefaultCompletableFuture, Dispatchers, Future}
+import akka.japi.{ Function ⇒ JFunc, Procedure ⇒ JProc }
+import akka.dispatch.{ DefaultCompletableFuture, Dispatchers, Future }
/**
* Used internally to send functions.
*/
-private[akka] case class Update[T](function: T => T)
+private[akka] case class Update[T](function: T ⇒ T)
private[akka] case object Get
/**
@@ -109,7 +109,7 @@ class Agent[T](initialValue: T) {
/**
* Dispatch a function to update the internal state.
*/
- def send(f: T => T): Unit = {
+ def send(f: T ⇒ T): Unit = {
def dispatch = updater ! Update(f)
if (Stm.activeTransaction) { get; deferred(dispatch) }
else dispatch
@@ -119,8 +119,8 @@ class Agent[T](initialValue: T) {
* Dispatch a function to update the internal state, and return a Future where that new state can be obtained
* within the given timeout
*/
- def alter(f: T => T)(timeout: Long): Future[T] = {
- def dispatch = updater.!!!(Update(f),timeout)
+ def alter(f: T ⇒ T)(timeout: Long): Future[T] = {
+ def dispatch = updater.!!!(Update(f), timeout)
if (Stm.activeTransaction) {
val result = new DefaultCompletableFuture[T](timeout)
get //Join xa
@@ -128,15 +128,14 @@ class Agent[T](initialValue: T) {
result completeWith dispatch
} //Attach deferred-block to current transaction
result
- }
- else dispatch
+ } else dispatch
}
/**
* Dispatch a new value for the internal state. Behaves the same
* as sending a function (x => newValue).
*/
- def send(newValue: T): Unit = send(x => newValue)
+ def send(newValue: T): Unit = send(x ⇒ newValue)
/**
* Dispatch a new value for the internal state. Behaves the same
@@ -150,7 +149,7 @@ class Agent[T](initialValue: T) {
* or blocking operations. Dispatches using either `sendOff` or `send` will
* still be executed in order.
*/
- def sendOff(f: T => T): Unit = send((value: T) => {
+ def sendOff(f: T ⇒ T): Unit = send((value: T) ⇒ {
suspend
val threadBased = Actor.actorOf(new ThreadBasedAgentUpdater(this)).start()
threadBased ! Update(f)
@@ -164,9 +163,9 @@ class Agent[T](initialValue: T) {
* or blocking operations. Dispatches using either `alterOff` or `alter` will
* still be executed in order.
*/
- def alterOff(f: T => T)(timeout: Long): Future[T] = {
+ def alterOff(f: T ⇒ T)(timeout: Long): Future[T] = {
val result = new DefaultCompletableFuture[T](timeout)
- send((value: T) => {
+ send((value: T) ⇒ {
suspend
val threadBased = Actor.actorOf(new ThreadBasedAgentUpdater(this)).start()
result completeWith threadBased.!!!(Update(f), timeout)
@@ -190,18 +189,18 @@ class Agent[T](initialValue: T) {
* Map this agent to a new agent, applying the function to the internal state.
* Does not change the value of this agent.
*/
- def map[B](f: T => B): Agent[B] = Agent(f(get))
+ def map[B](f: T ⇒ B): Agent[B] = Agent(f(get))
/**
* Flatmap this agent to a new agent, applying the function to the internal state.
* Does not change the value of this agent.
*/
- def flatMap[B](f: T => Agent[B]): Agent[B] = f(get)
+ def flatMap[B](f: T ⇒ Agent[B]): Agent[B] = f(get)
/**
* Applies the function to the internal state. Does not change the value of this agent.
*/
- def foreach[U](f: T => U): Unit = f(get)
+ def foreach[U](f: T ⇒ U): Unit = f(get)
/**
* Suspends processing of `send` actions for the agent.
@@ -227,14 +226,14 @@ class Agent[T](initialValue: T) {
* Java API:
* Dispatch a function to update the internal state.
*/
- def send(f: JFunc[T, T]): Unit = send(x => f(x))
+ def send(f: JFunc[T, T]): Unit = send(x ⇒ f(x))
/**
* Java API
* Dispatch a function to update the internal state, and return a Future where that new state can be obtained
* within the given timeout
*/
- def alter(f: JFunc[T, T], timeout: Long): Future[T] = alter(x => f(x))(timeout)
+ def alter(f: JFunc[T, T], timeout: Long): Future[T] = alter(x ⇒ f(x))(timeout)
/**
* Java API:
@@ -243,7 +242,7 @@ class Agent[T](initialValue: T) {
* or blocking operations. Dispatches using either `sendOff` or `send` will
* still be executed in order.
*/
- def sendOff(f: JFunc[T, T]): Unit = sendOff(x => f(x))
+ def sendOff(f: JFunc[T, T]): Unit = sendOff(x ⇒ f(x))
/**
* Java API:
@@ -253,7 +252,7 @@ class Agent[T](initialValue: T) {
* or blocking operations. Dispatches using either `alterOff` or `alter` will
* still be executed in order.
*/
- def alterOff(f: JFunc[T, T], timeout: Long): Unit = alterOff(x => f(x))(timeout)
+ def alterOff(f: JFunc[T, T], timeout: Long): Unit = alterOff(x ⇒ f(x))(timeout)
/**
* Java API:
@@ -283,10 +282,10 @@ class AgentUpdater[T](agent: Agent[T]) extends Actor {
val txFactory = TransactionFactory(familyName = "AgentUpdater", readonly = false)
def receive = {
- case update: Update[T] =>
+ case update: Update[T] ⇒
self.reply_?(atomic(txFactory) { agent.ref alter update.function })
- case Get => self reply agent.get
- case _ => ()
+ case Get ⇒ self reply agent.get
+ case _ ⇒ ()
}
}
@@ -299,12 +298,12 @@ class ThreadBasedAgentUpdater[T](agent: Agent[T]) extends Actor {
val txFactory = TransactionFactory(familyName = "ThreadBasedAgentUpdater", readonly = false)
def receive = {
- case update: Update[T] => try {
+ case update: Update[T] ⇒ try {
self.reply_?(atomic(txFactory) { agent.ref alter update.function })
} finally {
agent.resume
self.stop()
}
- case _ => self.stop()
+ case _ ⇒ self.stop()
}
}
diff --git a/akka-stm/src/main/scala/akka/stm/Ref.scala b/akka-stm/src/main/scala/akka/stm/Ref.scala
index 5d1aa9dc96..285edcc4be 100644
--- a/akka-stm/src/main/scala/akka/stm/Ref.scala
+++ b/akka-stm/src/main/scala/akka/stm/Ref.scala
@@ -4,7 +4,7 @@
package akka.stm
-import akka.actor.{newUuid, Uuid}
+import akka.actor.{ newUuid, Uuid }
import org.multiverse.transactional.refs.BasicRef
@@ -64,7 +64,7 @@ object Ref {
* }}}
*/
class Ref[T](initialValue: T) extends BasicRef[T](initialValue) with Transactional {
- self =>
+ self ⇒
def this() = this(null.asInstanceOf[T])
@@ -76,7 +76,7 @@ class Ref[T](initialValue: T) extends BasicRef[T](initialValue) with Transaction
def swap(newValue: T) = set(newValue)
- def alter(f: T => T): T = {
+ def alter(f: T ⇒ T): T = {
val value = f(get)
set(value)
value
@@ -86,35 +86,35 @@ class Ref[T](initialValue: T) extends BasicRef[T](initialValue) with Transaction
def getOrWait: T = getOrAwait
- def getOrElse(default: => T): T =
+ def getOrElse(default: ⇒ T): T =
if (isNull) default else get
def isDefined: Boolean = !isNull
def isEmpty: Boolean = isNull
- def map[B](f: T => B): Ref[B] =
+ def map[B](f: T ⇒ B): Ref[B] =
if (isEmpty) Ref[B] else Ref(f(get))
- def flatMap[B](f: T => Ref[B]): Ref[B] =
+ def flatMap[B](f: T ⇒ Ref[B]): Ref[B] =
if (isEmpty) Ref[B] else f(get)
- def filter(p: T => Boolean): Ref[T] =
+ def filter(p: T ⇒ Boolean): Ref[T] =
if (isDefined && p(get)) Ref(get) else Ref[T]
/**
* Necessary to keep from being implicitly converted to Iterable in for comprehensions.
*/
- def withFilter(p: T => Boolean): WithFilter = new WithFilter(p)
+ def withFilter(p: T ⇒ Boolean): WithFilter = new WithFilter(p)
- class WithFilter(p: T => Boolean) {
- def map[B](f: T => B): Ref[B] = self filter p map f
- def flatMap[B](f: T => Ref[B]): Ref[B] = self filter p flatMap f
- def foreach[U](f: T => U): Unit = self filter p foreach f
- def withFilter(q: T => Boolean): WithFilter = new WithFilter(x => p(x) && q(x))
+ class WithFilter(p: T ⇒ Boolean) {
+ def map[B](f: T ⇒ B): Ref[B] = self filter p map f
+ def flatMap[B](f: T ⇒ Ref[B]): Ref[B] = self filter p flatMap f
+ def foreach[U](f: T ⇒ U): Unit = self filter p foreach f
+ def withFilter(q: T ⇒ Boolean): WithFilter = new WithFilter(x ⇒ p(x) && q(x))
}
- def foreach[U](f: T => U): Unit =
+ def foreach[U](f: T ⇒ U): Unit =
if (isDefined) f(get)
def elements: Iterator[T] =
@@ -123,9 +123,9 @@ class Ref[T](initialValue: T) extends BasicRef[T](initialValue) with Transaction
def toList: List[T] =
if (isEmpty) List() else List(get)
- def toRight[X](left: => X) =
+ def toRight[X](left: ⇒ X) =
if (isEmpty) Left(left) else Right(get)
- def toLeft[X](right: => X) =
+ def toLeft[X](right: ⇒ X) =
if (isEmpty) Right(right) else Left(get)
}
diff --git a/akka-stm/src/main/scala/akka/stm/Stm.scala b/akka-stm/src/main/scala/akka/stm/Stm.scala
index 6e949b1ded..071ea66da6 100644
--- a/akka-stm/src/main/scala/akka/stm/Stm.scala
+++ b/akka-stm/src/main/scala/akka/stm/Stm.scala
@@ -4,9 +4,9 @@
package akka.stm
-import org.multiverse.api.{StmUtils => MultiverseStmUtils}
-import org.multiverse.api.{Transaction => MultiverseTransaction}
-import org.multiverse.templates.{TransactionalCallable, OrElseTemplate}
+import org.multiverse.api.{ StmUtils ⇒ MultiverseStmUtils }
+import org.multiverse.api.{ Transaction ⇒ MultiverseTransaction }
+import org.multiverse.templates.{ TransactionalCallable, OrElseTemplate }
object Stm {
/**
@@ -43,10 +43,10 @@ object Stm {
trait Stm {
val DefaultTransactionFactory = TransactionFactory(DefaultTransactionConfig, "DefaultTransaction")
- def atomic[T](body: => T)(implicit factory: TransactionFactory = DefaultTransactionFactory): T =
+ def atomic[T](body: ⇒ T)(implicit factory: TransactionFactory = DefaultTransactionFactory): T =
atomic(factory)(body)
- def atomic[T](factory: TransactionFactory)(body: => T): T = {
+ def atomic[T](factory: TransactionFactory)(body: ⇒ T): T = {
factory.boilerplate.execute(new TransactionalCallable[T]() {
def call(mtx: MultiverseTransaction): T = body
})
@@ -115,14 +115,14 @@ trait StmUtil {
* Schedule a deferred task on the thread local transaction (use within an atomic).
* This is executed when the transaction commits.
*/
- def deferred[T](body: => T): Unit =
+ def deferred[T](body: ⇒ T): Unit =
MultiverseStmUtils.scheduleDeferredTask(new Runnable { def run = body })
/**
* Schedule a compensating task on the thread local transaction (use within an atomic).
* This is executed when the transaction aborts.
*/
- def compensating[T](body: => T): Unit =
+ def compensating[T](body: ⇒ T): Unit =
MultiverseStmUtils.scheduleCompensatingTask(new Runnable { def run = body })
/**
@@ -134,8 +134,8 @@ trait StmUtil {
/**
* Use either-orElse to combine two blocking transactions.
*/
- def either[T](firstBody: => T) = new {
- def orElse(secondBody: => T) = new OrElseTemplate[T] {
+ def either[T](firstBody: ⇒ T) = new {
+ def orElse(secondBody: ⇒ T) = new OrElseTemplate[T] {
def either(mtx: MultiverseTransaction) = firstBody
def orelse(mtx: MultiverseTransaction) = secondBody
}.execute()
diff --git a/akka-stm/src/main/scala/akka/stm/TransactionFactory.scala b/akka-stm/src/main/scala/akka/stm/TransactionFactory.scala
index d04e017a6b..7ba747c6da 100644
--- a/akka-stm/src/main/scala/akka/stm/TransactionFactory.scala
+++ b/akka-stm/src/main/scala/akka/stm/TransactionFactory.scala
@@ -4,7 +4,7 @@
package akka.stm
-import java.lang.{Boolean => JBoolean}
+import java.lang.{ Boolean ⇒ JBoolean }
import akka.config.Config._
import akka.util.Duration
@@ -12,41 +12,41 @@ import akka.util.Duration
import org.multiverse.api.GlobalStmInstance.getGlobalStmInstance
import org.multiverse.stms.alpha.AlphaStm
import org.multiverse.templates.TransactionBoilerplate
-import org.multiverse.api.{PropagationLevel => MPropagation}
-import org.multiverse.api.{TraceLevel => MTraceLevel}
+import org.multiverse.api.{ PropagationLevel ⇒ MPropagation }
+import org.multiverse.api.{ TraceLevel ⇒ MTraceLevel }
/**
* For configuring multiverse transactions.
*/
object TransactionConfig {
// note: null values are so that we can default to Multiverse inference when not set
- val FAMILY_NAME = "DefaultTransaction"
- val READONLY = null.asInstanceOf[JBoolean]
- val MAX_RETRIES = config.getInt("akka.stm.max-retries", 1000)
- val TIMEOUT = config.getLong("akka.stm.timeout", 5)
- val TRACK_READS = null.asInstanceOf[JBoolean]
- val WRITE_SKEW = config.getBool("akka.stm.write-skew", true)
+ val FAMILY_NAME = "DefaultTransaction"
+ val READONLY = null.asInstanceOf[JBoolean]
+ val MAX_RETRIES = config.getInt("akka.stm.max-retries", 1000)
+ val TIMEOUT = config.getLong("akka.stm.timeout", 5)
+ val TRACK_READS = null.asInstanceOf[JBoolean]
+ val WRITE_SKEW = config.getBool("akka.stm.write-skew", true)
val BLOCKING_ALLOWED = config.getBool("akka.stm.blocking-allowed", false)
- val INTERRUPTIBLE = config.getBool("akka.stm.interruptible", false)
- val SPECULATIVE = config.getBool("akka.stm.speculative", true)
- val QUICK_RELEASE = config.getBool("akka.stm.quick-release", true)
- val PROPAGATION = propagation(config.getString("akka.stm.propagation", "requires"))
- val TRACE_LEVEL = traceLevel(config.getString("akka.stm.trace-level", "none"))
+ val INTERRUPTIBLE = config.getBool("akka.stm.interruptible", false)
+ val SPECULATIVE = config.getBool("akka.stm.speculative", true)
+ val QUICK_RELEASE = config.getBool("akka.stm.quick-release", true)
+ val PROPAGATION = propagation(config.getString("akka.stm.propagation", "requires"))
+ val TRACE_LEVEL = traceLevel(config.getString("akka.stm.trace-level", "none"))
val DefaultTimeout = Duration(TIMEOUT, TIME_UNIT)
def propagation(level: String) = level.toLowerCase match {
- case "requiresnew" => Propagation.RequiresNew
- case "fine" => Propagation.Mandatory
- case "supports" => Propagation.Supports
- case "never" => Propagation.Never
- case _ => Propagation.Requires
+ case "requiresnew" ⇒ Propagation.RequiresNew
+ case "fine" ⇒ Propagation.Mandatory
+ case "supports" ⇒ Propagation.Supports
+ case "never" ⇒ Propagation.Never
+ case _ ⇒ Propagation.Requires
}
def traceLevel(level: String) = level.toLowerCase match {
- case "coarse" | "course" => TraceLevel.Coarse
- case "fine" => TraceLevel.Fine
- case _ => TraceLevel.None
+ case "coarse" | "course" ⇒ TraceLevel.Coarse
+ case "fine" ⇒ TraceLevel.Fine
+ case _ ⇒ TraceLevel.None
}
/**
@@ -65,20 +65,20 @@ object TransactionConfig {
* @param propagation For controlling how nested transactions behave.
* @param traceLevel Transaction trace level.
*/
- def apply(familyName: String = FAMILY_NAME,
- readonly: JBoolean = READONLY,
- maxRetries: Int = MAX_RETRIES,
- timeout: Duration = DefaultTimeout,
- trackReads: JBoolean = TRACK_READS,
- writeSkew: Boolean = WRITE_SKEW,
- blockingAllowed: Boolean = BLOCKING_ALLOWED,
- interruptible: Boolean = INTERRUPTIBLE,
- speculative: Boolean = SPECULATIVE,
- quickRelease: Boolean = QUICK_RELEASE,
+ def apply(familyName: String = FAMILY_NAME,
+ readonly: JBoolean = READONLY,
+ maxRetries: Int = MAX_RETRIES,
+ timeout: Duration = DefaultTimeout,
+ trackReads: JBoolean = TRACK_READS,
+ writeSkew: Boolean = WRITE_SKEW,
+ blockingAllowed: Boolean = BLOCKING_ALLOWED,
+ interruptible: Boolean = INTERRUPTIBLE,
+ speculative: Boolean = SPECULATIVE,
+ quickRelease: Boolean = QUICK_RELEASE,
propagation: MPropagation = PROPAGATION,
- traceLevel: MTraceLevel = TRACE_LEVEL) = {
+ traceLevel: MTraceLevel = TRACE_LEVEL) = {
new TransactionConfig(familyName, readonly, maxRetries, timeout, trackReads, writeSkew, blockingAllowed,
- interruptible, speculative, quickRelease, propagation, traceLevel)
+ interruptible, speculative, quickRelease, propagation, traceLevel)
}
}
@@ -98,18 +98,18 @@ object TransactionConfig {
* propagation - For controlling how nested transactions behave.
*
traceLevel - Transaction trace level.
*/
-class TransactionConfig(val familyName: String = TransactionConfig.FAMILY_NAME,
- val readonly: JBoolean = TransactionConfig.READONLY,
- val maxRetries: Int = TransactionConfig.MAX_RETRIES,
- val timeout: Duration = TransactionConfig.DefaultTimeout,
- val trackReads: JBoolean = TransactionConfig.TRACK_READS,
- val writeSkew: Boolean = TransactionConfig.WRITE_SKEW,
- val blockingAllowed: Boolean = TransactionConfig.BLOCKING_ALLOWED,
- val interruptible: Boolean = TransactionConfig.INTERRUPTIBLE,
- val speculative: Boolean = TransactionConfig.SPECULATIVE,
- val quickRelease: Boolean = TransactionConfig.QUICK_RELEASE,
+class TransactionConfig(val familyName: String = TransactionConfig.FAMILY_NAME,
+ val readonly: JBoolean = TransactionConfig.READONLY,
+ val maxRetries: Int = TransactionConfig.MAX_RETRIES,
+ val timeout: Duration = TransactionConfig.DefaultTimeout,
+ val trackReads: JBoolean = TransactionConfig.TRACK_READS,
+ val writeSkew: Boolean = TransactionConfig.WRITE_SKEW,
+ val blockingAllowed: Boolean = TransactionConfig.BLOCKING_ALLOWED,
+ val interruptible: Boolean = TransactionConfig.INTERRUPTIBLE,
+ val speculative: Boolean = TransactionConfig.SPECULATIVE,
+ val quickRelease: Boolean = TransactionConfig.QUICK_RELEASE,
val propagation: MPropagation = TransactionConfig.PROPAGATION,
- val traceLevel: MTraceLevel = TransactionConfig.TRACE_LEVEL)
+ val traceLevel: MTraceLevel = TransactionConfig.TRACE_LEVEL)
object DefaultTransactionConfig extends TransactionConfig
@@ -121,18 +121,18 @@ object TransactionFactory {
def apply(config: TransactionConfig, defaultName: String) = new TransactionFactory(config, defaultName)
- def apply(familyName: String = TransactionConfig.FAMILY_NAME,
- readonly: JBoolean = TransactionConfig.READONLY,
- maxRetries: Int = TransactionConfig.MAX_RETRIES,
- timeout: Duration = TransactionConfig.DefaultTimeout,
- trackReads: JBoolean = TransactionConfig.TRACK_READS,
- writeSkew: Boolean = TransactionConfig.WRITE_SKEW,
- blockingAllowed: Boolean = TransactionConfig.BLOCKING_ALLOWED,
- interruptible: Boolean = TransactionConfig.INTERRUPTIBLE,
- speculative: Boolean = TransactionConfig.SPECULATIVE,
- quickRelease: Boolean = TransactionConfig.QUICK_RELEASE,
+ def apply(familyName: String = TransactionConfig.FAMILY_NAME,
+ readonly: JBoolean = TransactionConfig.READONLY,
+ maxRetries: Int = TransactionConfig.MAX_RETRIES,
+ timeout: Duration = TransactionConfig.DefaultTimeout,
+ trackReads: JBoolean = TransactionConfig.TRACK_READS,
+ writeSkew: Boolean = TransactionConfig.WRITE_SKEW,
+ blockingAllowed: Boolean = TransactionConfig.BLOCKING_ALLOWED,
+ interruptible: Boolean = TransactionConfig.INTERRUPTIBLE,
+ speculative: Boolean = TransactionConfig.SPECULATIVE,
+ quickRelease: Boolean = TransactionConfig.QUICK_RELEASE,
propagation: MPropagation = TransactionConfig.PROPAGATION,
- traceLevel: MTraceLevel = TransactionConfig.TRACE_LEVEL) = {
+ traceLevel: MTraceLevel = TransactionConfig.TRACE_LEVEL) = {
val config = new TransactionConfig(
familyName, readonly, maxRetries, timeout, trackReads, writeSkew, blockingAllowed,
interruptible, speculative, quickRelease, propagation, traceLevel)
@@ -163,23 +163,23 @@ object TransactionFactory {
*/
class TransactionFactory(
val config: TransactionConfig = DefaultTransactionConfig,
- defaultName: String = TransactionConfig.FAMILY_NAME) { self =>
+ defaultName: String = TransactionConfig.FAMILY_NAME) { self ⇒
// use the config family name if it's been set, otherwise defaultName - used by actors to set class name as default
val familyName = if (config.familyName != TransactionConfig.FAMILY_NAME) config.familyName else defaultName
val factory = {
var builder = (getGlobalStmInstance().asInstanceOf[AlphaStm].getTransactionFactoryBuilder()
- .setFamilyName(familyName)
- .setMaxRetries(config.maxRetries)
- .setTimeoutNs(config.timeout.toNanos)
- .setWriteSkewAllowed(config.writeSkew)
- .setExplicitRetryAllowed(config.blockingAllowed)
- .setInterruptible(config.interruptible)
- .setSpeculativeConfigurationEnabled(config.speculative)
- .setQuickReleaseEnabled(config.quickRelease)
- .setPropagationLevel(config.propagation)
- .setTraceLevel(config.traceLevel))
+ .setFamilyName(familyName)
+ .setMaxRetries(config.maxRetries)
+ .setTimeoutNs(config.timeout.toNanos)
+ .setWriteSkewAllowed(config.writeSkew)
+ .setExplicitRetryAllowed(config.blockingAllowed)
+ .setInterruptible(config.interruptible)
+ .setSpeculativeConfigurationEnabled(config.speculative)
+ .setQuickReleaseEnabled(config.quickRelease)
+ .setPropagationLevel(config.propagation)
+ .setTraceLevel(config.traceLevel))
if (config.readonly ne null) {
builder = builder.setReadonly(config.readonly.booleanValue)
@@ -200,18 +200,18 @@ class TransactionFactory(
*/
object Propagation {
val RequiresNew = MPropagation.RequiresNew
- val Mandatory = MPropagation.Mandatory
- val Requires = MPropagation.Requires
- val Supports = MPropagation.Supports
- val Never = MPropagation.Never
+ val Mandatory = MPropagation.Mandatory
+ val Requires = MPropagation.Requires
+ val Supports = MPropagation.Supports
+ val Never = MPropagation.Never
}
/**
* Mapping to Multiverse TraceLevel.
*/
object TraceLevel {
- val None = MTraceLevel.none
+ val None = MTraceLevel.none
val Coarse = MTraceLevel.course // mispelling?
val Course = MTraceLevel.course
- val Fine = MTraceLevel.fine
+ val Fine = MTraceLevel.fine
}
diff --git a/akka-stm/src/main/scala/akka/stm/TransactionFactoryBuilder.scala b/akka-stm/src/main/scala/akka/stm/TransactionFactoryBuilder.scala
index b71f68c375..147984b5e9 100644
--- a/akka-stm/src/main/scala/akka/stm/TransactionFactoryBuilder.scala
+++ b/akka-stm/src/main/scala/akka/stm/TransactionFactoryBuilder.scala
@@ -4,29 +4,29 @@
package akka.stm
-import java.lang.{Boolean => JBoolean}
+import java.lang.{ Boolean ⇒ JBoolean }
import akka.util.Duration
-import org.multiverse.api.{TraceLevel => MTraceLevel}
-import org.multiverse.api.{PropagationLevel => MPropagation}
+import org.multiverse.api.{ TraceLevel ⇒ MTraceLevel }
+import org.multiverse.api.{ PropagationLevel ⇒ MPropagation }
/**
* For more easily creating TransactionConfig from Java.
*/
class TransactionConfigBuilder {
- var familyName: String = TransactionConfig.FAMILY_NAME
- var readonly: JBoolean = TransactionConfig.READONLY
- var maxRetries: Int = TransactionConfig.MAX_RETRIES
- var timeout: Duration = TransactionConfig.DefaultTimeout
- var trackReads: JBoolean = TransactionConfig.TRACK_READS
- var writeSkew: Boolean = TransactionConfig.WRITE_SKEW
- var blockingAllowed: Boolean = TransactionConfig.BLOCKING_ALLOWED
- var interruptible: Boolean = TransactionConfig.INTERRUPTIBLE
- var speculative: Boolean = TransactionConfig.SPECULATIVE
- var quickRelease: Boolean = TransactionConfig.QUICK_RELEASE
+ var familyName: String = TransactionConfig.FAMILY_NAME
+ var readonly: JBoolean = TransactionConfig.READONLY
+ var maxRetries: Int = TransactionConfig.MAX_RETRIES
+ var timeout: Duration = TransactionConfig.DefaultTimeout
+ var trackReads: JBoolean = TransactionConfig.TRACK_READS
+ var writeSkew: Boolean = TransactionConfig.WRITE_SKEW
+ var blockingAllowed: Boolean = TransactionConfig.BLOCKING_ALLOWED
+ var interruptible: Boolean = TransactionConfig.INTERRUPTIBLE
+ var speculative: Boolean = TransactionConfig.SPECULATIVE
+ var quickRelease: Boolean = TransactionConfig.QUICK_RELEASE
var propagation: MPropagation = TransactionConfig.PROPAGATION
- var traceLevel: MTraceLevel = TransactionConfig.TRACE_LEVEL
+ var traceLevel: MTraceLevel = TransactionConfig.TRACE_LEVEL
def setFamilyName(familyName: String) = { this.familyName = familyName; this }
def setReadonly(readonly: JBoolean) = { this.readonly = readonly; this }
@@ -50,18 +50,18 @@ class TransactionConfigBuilder {
* For more easily creating TransactionFactory from Java.
*/
class TransactionFactoryBuilder {
- var familyName: String = TransactionConfig.FAMILY_NAME
- var readonly: JBoolean = TransactionConfig.READONLY
- var maxRetries: Int = TransactionConfig.MAX_RETRIES
- var timeout: Duration = TransactionConfig.DefaultTimeout
- var trackReads: JBoolean = TransactionConfig.TRACK_READS
- var writeSkew: Boolean = TransactionConfig.WRITE_SKEW
- var blockingAllowed: Boolean = TransactionConfig.BLOCKING_ALLOWED
- var interruptible: Boolean = TransactionConfig.INTERRUPTIBLE
- var speculative: Boolean = TransactionConfig.SPECULATIVE
- var quickRelease: Boolean = TransactionConfig.QUICK_RELEASE
+ var familyName: String = TransactionConfig.FAMILY_NAME
+ var readonly: JBoolean = TransactionConfig.READONLY
+ var maxRetries: Int = TransactionConfig.MAX_RETRIES
+ var timeout: Duration = TransactionConfig.DefaultTimeout
+ var trackReads: JBoolean = TransactionConfig.TRACK_READS
+ var writeSkew: Boolean = TransactionConfig.WRITE_SKEW
+ var blockingAllowed: Boolean = TransactionConfig.BLOCKING_ALLOWED
+ var interruptible: Boolean = TransactionConfig.INTERRUPTIBLE
+ var speculative: Boolean = TransactionConfig.SPECULATIVE
+ var quickRelease: Boolean = TransactionConfig.QUICK_RELEASE
var propagation: MPropagation = TransactionConfig.PROPAGATION
- var traceLevel: MTraceLevel = TransactionConfig.TRACE_LEVEL
+ var traceLevel: MTraceLevel = TransactionConfig.TRACE_LEVEL
def setFamilyName(familyName: String) = { this.familyName = familyName; this }
def setReadonly(readonly: JBoolean) = { this.readonly = readonly; this }
diff --git a/akka-stm/src/main/scala/akka/stm/TransactionalMap.scala b/akka-stm/src/main/scala/akka/stm/TransactionalMap.scala
index 61b131b211..1f833e9b06 100644
--- a/akka-stm/src/main/scala/akka/stm/TransactionalMap.scala
+++ b/akka-stm/src/main/scala/akka/stm/TransactionalMap.scala
@@ -6,7 +6,7 @@ package akka.stm
import scala.collection.immutable.HashMap
-import akka.actor.{newUuid}
+import akka.actor.{ newUuid }
/**
* Transactional map that implements the mutable Map interface with an underlying Ref and HashMap.
@@ -43,7 +43,7 @@ class TransactionalMap[K, V](initialValue: HashMap[K, V]) extends Transactional
def +=(key: K, value: V) = put(key, value)
def +=(kv: (K, V)) = {
- put(kv._1,kv._2)
+ put(kv._1, kv._2)
this
}
@@ -83,7 +83,7 @@ class TransactionalMap[K, V](initialValue: HashMap[K, V]) extends Transactional
override def equals(other: Any): Boolean =
other.isInstanceOf[TransactionalMap[_, _]] &&
- other.hashCode == hashCode
+ other.hashCode == hashCode
override def toString = if (Stm.activeTransaction) super.toString else ""
}
diff --git a/akka-stm/src/main/scala/akka/stm/TransactionalVector.scala b/akka-stm/src/main/scala/akka/stm/TransactionalVector.scala
index 488b56db78..42fcecfc34 100644
--- a/akka-stm/src/main/scala/akka/stm/TransactionalVector.scala
+++ b/akka-stm/src/main/scala/akka/stm/TransactionalVector.scala
@@ -8,7 +8,6 @@ import scala.collection.immutable.Vector
import akka.actor.newUuid
-
/**
* Transactional vector that implements the IndexedSeq interface with an underlying Ref and Vector.
*/
@@ -59,7 +58,7 @@ class TransactionalVector[T](initialValue: Vector[T]) extends Transactional with
override def equals(other: Any): Boolean =
other.isInstanceOf[TransactionalVector[_]] &&
- other.hashCode == hashCode
+ other.hashCode == hashCode
override def toString = if (Stm.activeTransaction) super.toString else ""
}
diff --git a/akka-stm/src/main/scala/akka/stm/package.scala b/akka-stm/src/main/scala/akka/stm/package.scala
index c7587ac24a..26f81f8f7a 100644
--- a/akka-stm/src/main/scala/akka/stm/package.scala
+++ b/akka-stm/src/main/scala/akka/stm/package.scala
@@ -20,13 +20,13 @@ package object stm extends akka.stm.Stm with akka.stm.StmUtil {
// Multiverse primitive refs
type BooleanRef = org.multiverse.transactional.refs.BooleanRef
- type ByteRef = org.multiverse.transactional.refs.ByteRef
- type CharRef = org.multiverse.transactional.refs.CharRef
- type DoubleRef = org.multiverse.transactional.refs.DoubleRef
- type FloatRef = org.multiverse.transactional.refs.FloatRef
- type IntRef = org.multiverse.transactional.refs.IntRef
- type LongRef = org.multiverse.transactional.refs.LongRef
- type ShortRef = org.multiverse.transactional.refs.ShortRef
+ type ByteRef = org.multiverse.transactional.refs.ByteRef
+ type CharRef = org.multiverse.transactional.refs.CharRef
+ type DoubleRef = org.multiverse.transactional.refs.DoubleRef
+ type FloatRef = org.multiverse.transactional.refs.FloatRef
+ type IntRef = org.multiverse.transactional.refs.IntRef
+ type LongRef = org.multiverse.transactional.refs.LongRef
+ type ShortRef = org.multiverse.transactional.refs.ShortRef
// Multiverse transactional datastructures
diff --git a/akka-stm/src/main/scala/akka/transactor/Coordinated.scala b/akka-stm/src/main/scala/akka/transactor/Coordinated.scala
index 8ce08cf624..2adec6098f 100644
--- a/akka-stm/src/main/scala/akka/transactor/Coordinated.scala
+++ b/akka-stm/src/main/scala/akka/transactor/Coordinated.scala
@@ -5,9 +5,9 @@
package akka.transactor
import akka.config.Config
-import akka.stm.{Atomic, DefaultTransactionConfig, TransactionFactory}
+import akka.stm.{ Atomic, DefaultTransactionConfig, TransactionFactory }
-import org.multiverse.api.{Transaction => MultiverseTransaction}
+import org.multiverse.api.{ Transaction ⇒ MultiverseTransaction }
import org.multiverse.commitbarriers.CountDownCommitBarrier
import org.multiverse.templates.TransactionalCallable
@@ -119,14 +119,14 @@ class Coordinated(val message: Any, barrier: CountDownCommitBarrier) {
* Delimits the coordinated transaction. The transaction will wait for all other transactions
* in this coordination before committing. The timeout is specified by the transaction factory.
*/
- def atomic[T](body: => T)(implicit factory: TransactionFactory = Coordinated.DefaultFactory): T =
+ def atomic[T](body: ⇒ T)(implicit factory: TransactionFactory = Coordinated.DefaultFactory): T =
atomic(factory)(body)
/**
* Delimits the coordinated transaction. The transaction will wait for all other transactions
* in this coordination before committing. The timeout is specified by the transaction factory.
*/
- def atomic[T](factory: TransactionFactory)(body: => T): T = {
+ def atomic[T](factory: TransactionFactory)(body: ⇒ T): T = {
factory.boilerplate.execute(new TransactionalCallable[T]() {
def call(mtx: MultiverseTransaction): T = {
val result = body
diff --git a/akka-stm/src/main/scala/akka/transactor/Transactor.scala b/akka-stm/src/main/scala/akka/transactor/Transactor.scala
index 57130dec07..e1bb115650 100644
--- a/akka-stm/src/main/scala/akka/transactor/Transactor.scala
+++ b/akka-stm/src/main/scala/akka/transactor/Transactor.scala
@@ -4,9 +4,8 @@
package akka.transactor
-import akka.actor.{Actor, ActorRef}
-import akka.stm.{DefaultTransactionConfig, TransactionFactory}
-
+import akka.actor.{ Actor, ActorRef }
+import akka.stm.{ DefaultTransactionConfig, TransactionFactory }
/**
* Used for specifying actor refs and messages to send to during coordination.
@@ -106,16 +105,16 @@ trait Transactor extends Actor {
* Implement a general pattern for using coordinated transactions.
*/
final def receive = {
- case coordinated @ Coordinated(message) => {
+ case coordinated@Coordinated(message) ⇒ {
val others = (coordinate orElse alone)(message)
- for (sendTo <- others) {
+ for (sendTo ← others) {
sendTo.actor ! coordinated(sendTo.message.getOrElse(message))
}
(before orElse doNothing)(message)
coordinated.atomic(txFactory) { (atomically orElse doNothing)(message) }
(after orElse doNothing)(message)
}
- case message => {
+ case message ⇒ {
if (normally.isDefinedAt(message)) normally(message)
else receive(Coordinated(message))
}
@@ -133,7 +132,7 @@ trait Transactor extends Actor {
/**
* Default coordination - no other transactors.
*/
- def alone: PartialFunction[Any, Set[SendTo]] = { case _ => nobody }
+ def alone: PartialFunction[Any, Set[SendTo]] = { case _ ⇒ nobody }
/**
* Empty set of transactors to send to.
@@ -150,7 +149,7 @@ trait Transactor extends Actor {
* Include other actors in this coordinated transaction and specify the message
* to send by providing ActorRef -> Message pairs. Use as the result in 'coordinated'.
*/
- def sendTo(pairs: (ActorRef, Any)*): Set[SendTo] = pairs map (p => SendTo(p._1, Some(p._2))) toSet
+ def sendTo(pairs: (ActorRef, Any)*): Set[SendTo] = pairs map (p ⇒ SendTo(p._1, Some(p._2))) toSet
/**
* A Receive block that runs before the coordinated transaction is entered.
diff --git a/akka-stm/src/main/scala/akka/transactor/UntypedTransactor.scala b/akka-stm/src/main/scala/akka/transactor/UntypedTransactor.scala
index c9d4e96aea..7c1dcb5d4f 100644
--- a/akka-stm/src/main/scala/akka/transactor/UntypedTransactor.scala
+++ b/akka-stm/src/main/scala/akka/transactor/UntypedTransactor.scala
@@ -4,14 +4,13 @@
package akka.transactor
-import akka.actor.{UntypedActor, ActorRef}
-import akka.stm.{DefaultTransactionConfig, TransactionFactory}
+import akka.actor.{ UntypedActor, ActorRef }
+import akka.stm.{ DefaultTransactionConfig, TransactionFactory }
-import java.util.{Set => JSet}
+import java.util.{ Set ⇒ JSet }
import scala.collection.JavaConversions._
-
/**
* An UntypedActor version of transactor for using from Java.
*/
@@ -29,16 +28,16 @@ abstract class UntypedTransactor extends UntypedActor {
@throws(classOf[Exception])
final def onReceive(message: Any): Unit = {
message match {
- case coordinated @ Coordinated(message) => {
+ case coordinated@Coordinated(message) ⇒ {
val others = coordinate(message)
- for (sendTo <- others) {
+ for (sendTo ← others) {
sendTo.actor.sendOneWay(coordinated(sendTo.message.getOrElse(message)))
}
before(message)
coordinated.atomic(txFactory) { atomically(message) }
after(message)
}
- case message => {
+ case message ⇒ {
val normal = normally(message)
if (!normal) onReceive(Coordinated(message))
}
@@ -70,7 +69,7 @@ abstract class UntypedTransactor extends UntypedActor {
* For including one other actor in this coordinated transaction and specifying the
* message to send. Use as the result in `coordinated`.
*/
- def include(actor: ActorRef, message: Any): JSet[SendTo] = Set(SendTo(actor, Some(message)))
+ def include(actor: ActorRef, message: Any): JSet[SendTo] = Set(SendTo(actor, Some(message)))
/**
* For including another actor in this coordinated transaction and sending
@@ -82,7 +81,7 @@ abstract class UntypedTransactor extends UntypedActor {
* For including another actor in this coordinated transaction and specifying the
* message to send. Use to create the result in `coordinated`.
*/
- def sendTo(actor: ActorRef, message: Any): SendTo = SendTo(actor, Some(message))
+ def sendTo(actor: ActorRef, message: Any): SendTo = SendTo(actor, Some(message))
/**
* A Receive block that runs before the coordinated transaction is entered.
diff --git a/akka-stm/src/test/scala/agent/AgentSpec.scala b/akka-stm/src/test/scala/agent/AgentSpec.scala
index 18233917c3..96b95317b8 100644
--- a/akka-stm/src/test/scala/agent/AgentSpec.scala
+++ b/akka-stm/src/test/scala/agent/AgentSpec.scala
@@ -28,7 +28,7 @@ class AgentSpec extends WordSpec with MustMatchers {
agent send countDown
countDown.await(5 seconds)
- agent() must be ("abcd")
+ agent() must be("abcd")
agent.close
}
@@ -38,13 +38,13 @@ class AgentSpec extends WordSpec with MustMatchers {
val agent = Agent("a")
agent send (_ + "b")
- val longRunning = (s: String) => { Thread.sleep(2000); s + "c" }
+ val longRunning = (s: String) ⇒ { Thread.sleep(2000); s + "c" }
agent sendOff longRunning
agent send (_ + "d")
agent send countDown
countDown.await(5 seconds)
- agent() must be ("abcd")
+ agent() must be("abcd")
agent.close
}
@@ -54,14 +54,14 @@ class AgentSpec extends WordSpec with MustMatchers {
val agent = Agent("a")
val r1 = agent.alter(_ + "b")(5000)
- val r2 = agent.alterOff((s: String) => { Thread.sleep(2000); s + "c" })(5000)
+ val r2 = agent.alterOff((s: String) ⇒ { Thread.sleep(2000); s + "c" })(5000)
val r3 = agent.alter(_ + "d")(5000)
r1.await.resultOrException.get must be === "ab"
r2.await.resultOrException.get must be === "abc"
r3.await.resultOrException.get must be === "abcd"
- agent() must be ("abcd")
+ agent() must be("abcd")
agent.close
}
@@ -72,7 +72,7 @@ class AgentSpec extends WordSpec with MustMatchers {
val readTimeout = 5 seconds
val agent = Agent(5)
- val f1 = (i: Int) => {
+ val f1 = (i: Int) ⇒ {
readLatch.await(readTimeout.length, readTimeout.unit)
i + 5
}
@@ -82,8 +82,8 @@ class AgentSpec extends WordSpec with MustMatchers {
agent send countDown
countDown.await(5 seconds)
- read must be (5)
- agent() must be (10)
+ read must be(5)
+ agent() must be(10)
agent.close
}
@@ -91,7 +91,7 @@ class AgentSpec extends WordSpec with MustMatchers {
"be readable within a transaction" in {
val agent = Agent(5)
val value = atomic { agent() }
- value must be (5)
+ value must be(5)
agent.close
}
@@ -105,7 +105,7 @@ class AgentSpec extends WordSpec with MustMatchers {
agent send countDown
countDown.await(5 seconds)
- agent() must be (10)
+ agent() must be(10)
agent.close
}
@@ -120,12 +120,12 @@ class AgentSpec extends WordSpec with MustMatchers {
agent send (_ * 2)
throw new RuntimeException("Expected failure")
}
- } catch { case _ => }
+ } catch { case _ ⇒ }
agent send countDown
countDown.await(5 seconds)
- agent() must be (5)
+ agent() must be(5)
agent.close
}
@@ -137,7 +137,7 @@ class AgentSpec extends WordSpec with MustMatchers {
val future = agent.future
- future.await.result.get must be ("abc")
+ future.await.result.get must be("abc")
agent.close
}
@@ -147,7 +147,7 @@ class AgentSpec extends WordSpec with MustMatchers {
agent send (_ + "b")
agent send (_ + "c")
- agent.await must be ("abc")
+ agent.await must be("abc")
agent.close
}
@@ -156,8 +156,8 @@ class AgentSpec extends WordSpec with MustMatchers {
val agent1 = Agent(5)
val agent2 = agent1 map (_ * 2)
- agent1() must be (5)
- agent2() must be (10)
+ agent1() must be(5)
+ agent2() must be(10)
agent1.close
agent2.close
@@ -167,21 +167,21 @@ class AgentSpec extends WordSpec with MustMatchers {
val agent = Agent(3)
var result = 0
- for (value <- agent) {
- result += value
+ for (value ← agent) {
+ result += value
}
- result must be (3)
+ result must be(3)
agent.close
}
"be able to be used in a 'map' for comprehension" in {
val agent1 = Agent(5)
- val agent2 = for (value <- agent1) yield value * 2
+ val agent2 = for (value ← agent1) yield value * 2
- agent1() must be (5)
- agent2() must be (10)
+ agent1() must be(5)
+ agent2() must be(10)
agent1.close
agent2.close
@@ -192,13 +192,13 @@ class AgentSpec extends WordSpec with MustMatchers {
val agent2 = Agent(2)
val agent3 = for {
- value1 <- agent1
- value2 <- agent2
- } yield value1 + value2
+ value1 ← agent1
+ value2 ← agent2
+ } yield value1 + value2
- agent1() must be (1)
- agent2() must be (2)
- agent3() must be (3)
+ agent1() must be(1)
+ agent2() must be(2)
+ agent3() must be(3)
agent1.close
agent2.close
diff --git a/akka-stm/src/test/scala/stm/RefSpec.scala b/akka-stm/src/test/scala/stm/RefSpec.scala
index 8270706146..019d693e54 100644
--- a/akka-stm/src/test/scala/stm/RefSpec.scala
+++ b/akka-stm/src/test/scala/stm/RefSpec.scala
@@ -18,7 +18,7 @@ class RefSpec extends WordSpec with MustMatchers {
val ref = Ref(3)
val value = atomic { ref.get }
- value must be (3)
+ value must be(3)
}
"keep the initial value, even if the first transaction is rolled back" in {
@@ -30,12 +30,12 @@ class RefSpec extends WordSpec with MustMatchers {
throw new Exception
}
} catch {
- case e => {}
+ case e ⇒ {}
}
val value = atomic { ref.get }
- value must be (3)
+ value must be(3)
}
"be settable using set" in {
@@ -45,7 +45,7 @@ class RefSpec extends WordSpec with MustMatchers {
val value = atomic { ref.get }
- value must be (3)
+ value must be(3)
}
"be settable using swap" in {
@@ -55,7 +55,7 @@ class RefSpec extends WordSpec with MustMatchers {
val value = atomic { ref.get }
- value must be (3)
+ value must be(3)
}
"be changeable using alter" in {
@@ -71,7 +71,7 @@ class RefSpec extends WordSpec with MustMatchers {
val value = atomic { ref.get }
- value must be (3)
+ value must be(3)
}
"be able to be mapped" in {
@@ -84,8 +84,8 @@ class RefSpec extends WordSpec with MustMatchers {
val value1 = atomic { ref1.get }
val value2 = atomic { ref2.get }
- value1 must be (1)
- value2 must be (2)
+ value1 must be(1)
+ value2 must be(2)
}
"be able to be used in a 'foreach' for comprehension" in {
@@ -94,24 +94,24 @@ class RefSpec extends WordSpec with MustMatchers {
var result = 0
atomic {
- for (value <- ref) {
+ for (value ← ref) {
result += value
}
}
- result must be (3)
+ result must be(3)
}
"be able to be used in a 'map' for comprehension" in {
val ref1 = Ref(1)
val ref2 = atomic {
- for (value <- ref1) yield value + 2
+ for (value ← ref1) yield value + 2
}
val value2 = atomic { ref2.get }
- value2 must be (3)
+ value2 must be(3)
}
"be able to be used in a 'flatMap' for comprehension" in {
@@ -120,33 +120,33 @@ class RefSpec extends WordSpec with MustMatchers {
val ref3 = atomic {
for {
- value1 <- ref1
- value2 <- ref2
+ value1 ← ref1
+ value2 ← ref2
} yield value1 + value2
}
val value3 = atomic { ref3.get }
- value3 must be (3)
+ value3 must be(3)
}
"be able to be used in a 'filter' for comprehension" in {
val ref1 = Ref(1)
val refLess2 = atomic {
- for (value <- ref1 if value < 2) yield value
+ for (value ← ref1 if value < 2) yield value
}
val optLess2 = atomic { refLess2.opt }
val refGreater2 = atomic {
- for (value <- ref1 if value > 2) yield value
+ for (value ← ref1 if value > 2) yield value
}
val optGreater2 = atomic { refGreater2.opt }
- optLess2 must be (Some(1))
- optGreater2 must be (None)
+ optLess2 must be(Some(1))
+ optGreater2 must be(None)
}
}
}
diff --git a/akka-stm/src/test/scala/stm/StmSpec.scala b/akka-stm/src/test/scala/stm/StmSpec.scala
index f20545e03b..e7890b138d 100644
--- a/akka-stm/src/test/scala/stm/StmSpec.scala
+++ b/akka-stm/src/test/scala/stm/StmSpec.scala
@@ -29,7 +29,7 @@ class StmSpec extends WordSpec with MustMatchers {
increment
increment
- total must be (3)
+ total must be(3)
}
"be able to do nested atomic {..} statements" in {
@@ -50,7 +50,7 @@ class StmSpec extends WordSpec with MustMatchers {
atomic {
increment
- total must be (3)
+ total must be(3)
}
}
@@ -72,10 +72,10 @@ class StmSpec extends WordSpec with MustMatchers {
throw new Exception
}
} catch {
- case e => {}
+ case e ⇒ {}
}
- total must be (0)
+ total must be(0)
}
"use the outer transaction settings by default" in {
@@ -98,8 +98,8 @@ class StmSpec extends WordSpec with MustMatchers {
}
}
- writableOuter must be (1)
- evaluating { readonlyOuter } must produce [ReadonlyException]
+ writableOuter must be(1)
+ evaluating { readonlyOuter } must produce[ReadonlyException]
}
"allow propagation settings for nested transactions" in {
@@ -122,8 +122,8 @@ class StmSpec extends WordSpec with MustMatchers {
}
}
- writableOuter must be (1)
- readonlyOuter must be (2)
+ writableOuter must be(1)
+ readonlyOuter must be(2)
}
}
}
diff --git a/akka-stm/src/test/scala/transactor/CoordinatedIncrementSpec.scala b/akka-stm/src/test/scala/transactor/CoordinatedIncrementSpec.scala
index 116baa7da7..5615c97322 100644
--- a/akka-stm/src/test/scala/transactor/CoordinatedIncrementSpec.scala
+++ b/akka-stm/src/test/scala/transactor/CoordinatedIncrementSpec.scala
@@ -4,8 +4,8 @@ import org.scalatest.WordSpec
import org.scalatest.matchers.MustMatchers
import akka.transactor.Coordinated
-import akka.actor.{Actor, ActorRef}
-import akka.stm.{Ref, TransactionFactory}
+import akka.actor.{ Actor, ActorRef }
+import akka.stm.{ Ref, TransactionFactory }
import akka.util.duration._
object CoordinatedIncrement {
@@ -22,7 +22,7 @@ object CoordinatedIncrement {
}
def receive = {
- case coordinated @ Coordinated(Increment(friends)) => {
+ case coordinated@Coordinated(Increment(friends)) ⇒ {
if (friends.nonEmpty) {
friends.head ! coordinated(Increment(friends.tail))
}
@@ -31,13 +31,13 @@ object CoordinatedIncrement {
}
}
- case GetCount => self.reply(count.get)
+ case GetCount ⇒ self.reply(count.get)
}
}
class Failer extends Actor {
def receive = {
- case Coordinated(Increment(friends)) => {
+ case Coordinated(Increment(friends)) ⇒ {
throw new RuntimeException("Expected failure")
}
}
@@ -63,7 +63,7 @@ class CoordinatedIncrementSpec extends WordSpec with MustMatchers {
val coordinated = Coordinated()
counters(0) ! coordinated(Increment(counters.tail))
coordinated.await
- for (counter <- counters) {
+ for (counter ← counters) {
(counter !! GetCount).get must be === 1
}
counters foreach (_.stop())
@@ -75,7 +75,7 @@ class CoordinatedIncrementSpec extends WordSpec with MustMatchers {
val coordinated = Coordinated()
counters(0) ! Coordinated(Increment(counters.tail :+ failer))
coordinated.await
- for (counter <- counters) {
+ for (counter ← counters) {
(counter !! GetCount).get must be === 0
}
counters foreach (_.stop())
diff --git a/akka-stm/src/test/scala/transactor/FickleFriendsSpec.scala b/akka-stm/src/test/scala/transactor/FickleFriendsSpec.scala
index 2c953fb36a..b275c1a071 100644
--- a/akka-stm/src/test/scala/transactor/FickleFriendsSpec.scala
+++ b/akka-stm/src/test/scala/transactor/FickleFriendsSpec.scala
@@ -4,11 +4,11 @@ import org.scalatest.WordSpec
import org.scalatest.matchers.MustMatchers
import akka.transactor.Coordinated
-import akka.actor.{Actor, ActorRef}
+import akka.actor.{ Actor, ActorRef }
import akka.stm._
import akka.util.duration._
-import scala.util.Random.{nextInt => random}
+import scala.util.Random.{ nextInt ⇒ random }
import java.util.concurrent.CountDownLatch
@@ -30,7 +30,7 @@ object FickleFriends {
}
def receive = {
- case FriendlyIncrement(friends, latch) => {
+ case FriendlyIncrement(friends, latch) ⇒ {
var success = false
while (!success) {
try {
@@ -46,12 +46,12 @@ object FickleFriends {
}
}
} catch {
- case _ => () // swallow exceptions
+ case _ ⇒ () // swallow exceptions
}
}
}
- case GetCount => self.reply(count.get)
+ case GetCount ⇒ self.reply(count.get)
}
}
@@ -72,7 +72,7 @@ object FickleFriends {
}
def receive = {
- case coordinated @ Coordinated(Increment(friends)) => {
+ case coordinated@Coordinated(Increment(friends)) ⇒ {
val failAt = random(8)
failIf(failAt, 0)
if (friends.nonEmpty) {
@@ -86,7 +86,7 @@ object FickleFriends {
}
}
- case GetCount => self.reply(count.get)
+ case GetCount ⇒ self.reply(count.get)
}
}
}
@@ -110,7 +110,7 @@ class FickleFriendsSpec extends WordSpec with MustMatchers {
coordinator ! FriendlyIncrement(counters, latch)
latch.await // this could take a while
(coordinator !! GetCount).get must be === 1
- for (counter <- counters) {
+ for (counter ← counters) {
(counter !! GetCount).get must be === 1
}
counters foreach (_.stop())
diff --git a/akka-stm/src/test/scala/transactor/JavaUntypedCoordinatedSpec.scala b/akka-stm/src/test/scala/transactor/JavaUntypedCoordinatedSpec.scala
index a7de3fc63b..c2a96f436c 100644
--- a/akka-stm/src/test/scala/transactor/JavaUntypedCoordinatedSpec.scala
+++ b/akka-stm/src/test/scala/transactor/JavaUntypedCoordinatedSpec.scala
@@ -4,5 +4,4 @@ import org.scalatest.junit.JUnitWrapperSuite
class JavaUntypedCoordinatedSpec extends JUnitWrapperSuite(
"akka.transactor.test.UntypedCoordinatedIncrementTest",
- Thread.currentThread.getContextClassLoader
-)
+ Thread.currentThread.getContextClassLoader)
diff --git a/akka-stm/src/test/scala/transactor/JavaUntypedTransactorSpec.scala b/akka-stm/src/test/scala/transactor/JavaUntypedTransactorSpec.scala
index 6efc2f0f1b..a643fb141d 100644
--- a/akka-stm/src/test/scala/transactor/JavaUntypedTransactorSpec.scala
+++ b/akka-stm/src/test/scala/transactor/JavaUntypedTransactorSpec.scala
@@ -4,5 +4,4 @@ import org.scalatest.junit.JUnitWrapperSuite
class JavaUntypedTransactorSpec extends JUnitWrapperSuite(
"akka.transactor.test.UntypedTransactorTest",
- Thread.currentThread.getContextClassLoader
-)
+ Thread.currentThread.getContextClassLoader)
diff --git a/akka-stm/src/test/scala/transactor/TransactorSpec.scala b/akka-stm/src/test/scala/transactor/TransactorSpec.scala
index f44b6f58fa..33ca14402f 100644
--- a/akka-stm/src/test/scala/transactor/TransactorSpec.scala
+++ b/akka-stm/src/test/scala/transactor/TransactorSpec.scala
@@ -4,7 +4,7 @@ import org.scalatest.WordSpec
import org.scalatest.matchers.MustMatchers
import akka.transactor.Transactor
-import akka.actor.{Actor, ActorRef}
+import akka.actor.{ Actor, ActorRef }
import akka.stm._
import akka.util.duration._
@@ -24,18 +24,18 @@ object TransactorIncrement {
}
override def coordinate = {
- case Increment(friends, latch) => {
+ case Increment(friends, latch) ⇒ {
if (friends.nonEmpty) sendTo(friends.head -> Increment(friends.tail, latch))
else nobody
}
}
override def before = {
- case i: Increment =>
+ case i: Increment ⇒
}
def atomically = {
- case Increment(friends, latch) => {
+ case Increment(friends, latch) ⇒ {
increment
deferred { latch.countDown() }
compensating { latch.countDown() }
@@ -43,17 +43,17 @@ object TransactorIncrement {
}
override def after = {
- case i: Increment =>
+ case i: Increment ⇒
}
override def normally = {
- case GetCount => self.reply(count.get)
+ case GetCount ⇒ self.reply(count.get)
}
}
class Failer extends Transactor {
def atomically = {
- case _ => throw new RuntimeException("Expected failure")
+ case _ ⇒ throw new RuntimeException("Expected failure")
}
}
}
@@ -63,7 +63,7 @@ object SimpleTransactor {
class Setter extends Transactor {
def atomically = {
- case Set(ref, value, latch) => {
+ case Set(ref, value, latch) ⇒ {
ref.set(value)
latch.countDown()
}
@@ -91,7 +91,7 @@ class TransactorSpec extends WordSpec with MustMatchers {
val incrementLatch = new CountDownLatch(numCounters)
counters(0) ! Increment(counters.tail, incrementLatch)
incrementLatch.await(timeout.length, timeout.unit)
- for (counter <- counters) {
+ for (counter ← counters) {
(counter !! GetCount).get must be === 1
}
counters foreach (_.stop())
@@ -103,7 +103,7 @@ class TransactorSpec extends WordSpec with MustMatchers {
val failLatch = new CountDownLatch(numCounters + 1)
counters(0) ! Increment(counters.tail :+ failer, failLatch)
failLatch.await(timeout.length, timeout.unit)
- for (counter <- counters) {
+ for (counter ← counters) {
(counter !! GetCount).get must be === 0
}
counters foreach (_.stop())
diff --git a/akka-testkit/src/main/scala/akka/testkit/CallingThreadDispatcher.scala b/akka-testkit/src/main/scala/akka/testkit/CallingThreadDispatcher.scala
index 319b40b6f4..218315ec2f 100644
--- a/akka-testkit/src/main/scala/akka/testkit/CallingThreadDispatcher.scala
+++ b/akka-testkit/src/main/scala/akka/testkit/CallingThreadDispatcher.scala
@@ -2,7 +2,7 @@ package akka.testkit
import akka.event.EventHandler
import akka.actor.ActorRef
-import akka.dispatch.{MessageDispatcher, MessageInvocation, FutureInvocation}
+import akka.dispatch.{ MessageDispatcher, MessageInvocation, FutureInvocation }
import java.util.concurrent.locks.ReentrantLock
import java.util.LinkedList
import java.util.concurrent.RejectedExecutionException
@@ -40,7 +40,7 @@ object CallingThreadDispatcher {
queues = queues mapValues (_ filter (_.get ne null)) filter (!_._2.isEmpty)
}
- private[akka] def registerQueue(mbox : CallingThreadMailbox, q : NestingQueue) : Unit = synchronized {
+ private[akka] def registerQueue(mbox: CallingThreadMailbox, q: NestingQueue): Unit = synchronized {
if (queues contains mbox) {
val newSet = queues(mbox) + new WeakReference(q)
queues += mbox -> newSet
@@ -55,11 +55,11 @@ object CallingThreadDispatcher {
* given mailbox. When this method returns, the queue will be entered
* (active).
*/
- private[akka] def gatherFromAllInactiveQueues(mbox : CallingThreadMailbox, own : NestingQueue) : Unit = synchronized {
+ private[akka] def gatherFromAllInactiveQueues(mbox: CallingThreadMailbox, own: NestingQueue): Unit = synchronized {
if (!own.isActive) own.enter
if (queues contains mbox) {
for {
- ref <- queues(mbox)
+ ref ← queues(mbox)
q = ref.get
if (q ne null) && !q.isActive
/*
@@ -136,23 +136,23 @@ class CallingThreadDispatcher(val warnings: Boolean = true) extends MessageDispa
val mbox = getMailbox(handle.receiver)
val queue = mbox.queue
val execute = mbox.suspended.ifElseYield {
- queue.push(handle)
+ queue.push(handle)
+ if (warnings && handle.senderFuture.isDefined) {
+ EventHandler.warning(this, "suspended, creating Future could deadlock; target: %s" format handle.receiver)
+ }
+ false
+ } {
+ queue.push(handle)
+ if (queue.isActive) {
if (warnings && handle.senderFuture.isDefined) {
- EventHandler.warning(this, "suspended, creating Future could deadlock; target: %s" format handle.receiver)
+ EventHandler.warning(this, "blocked on this thread, creating Future could deadlock; target: %s" format handle.receiver)
}
false
- } {
- queue.push(handle)
- if (queue.isActive) {
- if (warnings && handle.senderFuture.isDefined) {
- EventHandler.warning(this, "blocked on this thread, creating Future could deadlock; target: %s" format handle.receiver)
- }
- false
- } else {
- queue.enter
- true
- }
+ } else {
+ queue.enter
+ true
}
+ }
if (execute) runQueue(mbox, queue)
}
@@ -167,18 +167,19 @@ class CallingThreadDispatcher(val warnings: Boolean = true) extends MessageDispa
* there is no-one who cares to execute it before the next message is sent or
* it is suspended and resumed.
*/
- @tailrec private def runQueue(mbox : CallingThreadMailbox, queue : NestingQueue) {
+ @tailrec
+ private def runQueue(mbox: CallingThreadMailbox, queue: NestingQueue) {
assert(queue.isActive)
mbox.lock.lock
val recurse = try {
val handle = mbox.suspended.ifElseYield[MessageInvocation] {
- queue.leave
- null
- } {
- val ret = queue.pop
- if (ret eq null) queue.leave
- ret
- }
+ queue.leave
+ null
+ } {
+ val ret = queue.pop
+ if (ret eq null) queue.leave
+ ret
+ }
if (handle ne null) {
try {
handle.invoke
@@ -187,7 +188,7 @@ class CallingThreadDispatcher(val warnings: Boolean = true) extends MessageDispa
EventHandler.warning(this, "calling %s with message %s did not reply as expected, might deadlock" format (handle.receiver, handle.message))
}
} catch {
- case _ => queue.leave
+ case _ ⇒ queue.leave
}
true
} else if (queue.isActive) {
@@ -206,11 +207,12 @@ class CallingThreadDispatcher(val warnings: Boolean = true) extends MessageDispa
class NestingQueue {
private var q = new LinkedList[MessageInvocation]()
def size = q.size
- def push(handle : MessageInvocation) { q.offer(handle) }
+ def push(handle: MessageInvocation) { q.offer(handle) }
def peek = q.peek
def pop = q.poll
- @volatile private var active = false
+ @volatile
+ private var active = false
def enter { if (active) sys.error("already active") else active = true }
def leave { if (!active) sys.error("not active") else active = false }
def isActive = active
diff --git a/akka-testkit/src/main/scala/akka/testkit/TestActorRef.scala b/akka-testkit/src/main/scala/akka/testkit/TestActorRef.scala
index f0e9ceab7b..7b656278b8 100644
--- a/akka-testkit/src/main/scala/akka/testkit/TestActorRef.scala
+++ b/akka-testkit/src/main/scala/akka/testkit/TestActorRef.scala
@@ -19,7 +19,7 @@ import com.eaio.uuid.UUID
* @author Roland Kuhn
* @since 1.1
*/
-class TestActorRef[T <: Actor](factory: () => T, address: String) extends LocalActorRef(factory, address) {
+class TestActorRef[T <: Actor](factory: () ⇒ T, address: String) extends LocalActorRef(factory, address) {
dispatcher = CallingThreadDispatcher.global
receiveTimeout = None
@@ -27,21 +27,21 @@ class TestActorRef[T <: Actor](factory: () => T, address: String) extends LocalA
/**
* Query actor's current receive behavior.
*/
- override def isDefinedAt(o : Any) = actor.isDefinedAt(o)
+ override def isDefinedAt(o: Any) = actor.isDefinedAt(o)
/**
* Directly inject messages into actor receive behavior. Any exceptions
* thrown will be available to you, while still being able to use
* become/unbecome and their message counterparts.
*/
- def apply(o : Any) { actor(o) }
+ def apply(o: Any) { actor(o) }
/**
* Retrieve reference to the underlying actor, where the static type matches the factory used inside the
* constructor. Beware that this reference is discarded by the ActorRef upon restarting the actor (should this
* reference be linked to a supervisor). The old Actor may of course still be used in post-mortem assertions.
*/
- def underlyingActor : T = actor.asInstanceOf[T]
+ def underlyingActor: T = actor.asInstanceOf[T]
/**
* Override to return the more specific static type.
@@ -53,19 +53,19 @@ class TestActorRef[T <: Actor](factory: () => T, address: String) extends LocalA
override def toString = "TestActor[" + address + ":" + uuid + "]"
- override def equals(other : Any) =
+ override def equals(other: Any) =
other.isInstanceOf[TestActorRef[_]] &&
- other.asInstanceOf[TestActorRef[_]].uuid == uuid
+ other.asInstanceOf[TestActorRef[_]].uuid == uuid
/**
* Override to check whether the new supervisor is running on the CallingThreadDispatcher,
* as it should be. This can of course be tricked by linking before setting the dispatcher before starting the
* supervisor, but then you just asked for trouble.
*/
- override def supervisor_=(a : Option[ActorRef]) {
- for (ref <- a) {
+ override def supervisor_=(a: Option[ActorRef]) {
+ for (ref ← a) {
if (!ref.dispatcher.isInstanceOf[CallingThreadDispatcher])
- EventHandler.warning(this, "supervisor "+ref+" does not use CallingThreadDispatcher")
+ EventHandler.warning(this, "supervisor " + ref + " does not use CallingThreadDispatcher")
}
super.supervisor_=(a)
}
@@ -74,22 +74,22 @@ class TestActorRef[T <: Actor](factory: () => T, address: String) extends LocalA
object TestActorRef {
- def apply[T <: Actor](factory: => T): TestActorRef[T] = apply[T](factory, new UUID().toString)
+ def apply[T <: Actor](factory: ⇒ T): TestActorRef[T] = apply[T](factory, new UUID().toString)
- def apply[T <: Actor](factory: => T, address: String): TestActorRef[T] = new TestActorRef(() => factory, address)
+ def apply[T <: Actor](factory: ⇒ T, address: String): TestActorRef[T] = new TestActorRef(() ⇒ factory, address)
- def apply[T <: Actor : Manifest]: TestActorRef[T] = apply[T](new UUID().toString)
+ def apply[T <: Actor: Manifest]: TestActorRef[T] = apply[T](new UUID().toString)
- def apply[T <: Actor : Manifest](address: String): TestActorRef[T] = new TestActorRef[T] ({ () =>
+ def apply[T <: Actor: Manifest](address: String): TestActorRef[T] = new TestActorRef[T]({ () ⇒
import ReflectiveAccess.{ createInstance, noParams, noArgs }
createInstance[T](manifest[T].erasure, noParams, noArgs) match {
- case r: Right[_, T] => r.b
- case l: Left[Exception, _] => throw new ActorInitializationException(
+ case r: Right[_, T] ⇒ r.b
+ case l: Left[Exception, _] ⇒ throw new ActorInitializationException(
"Could not instantiate Actor" +
- "\nMake sure Actor is NOT defined inside a class/trait," +
- "\nif so put it outside the class/trait, f.e. in a companion object," +
- "\nOR try to change: 'actorOf[MyActor]' to 'actorOf(new MyActor)'.", l.a)
+ "\nMake sure Actor is NOT defined inside a class/trait," +
+ "\nif so put it outside the class/trait, f.e. in a companion object," +
+ "\nOR try to change: 'actorOf[MyActor]' to 'actorOf(new MyActor)'.", l.a)
}
}, address)
}
diff --git a/akka-testkit/src/main/scala/akka/testkit/TestKit.scala b/akka-testkit/src/main/scala/akka/testkit/TestKit.scala
index fdad53c4ff..8e76b636cc 100644
--- a/akka-testkit/src/main/scala/akka/testkit/TestKit.scala
+++ b/akka-testkit/src/main/scala/akka/testkit/TestKit.scala
@@ -1,22 +1,22 @@
package akka.testkit
-import akka.actor.{Actor, FSM}
+import akka.actor.{ Actor, FSM }
import Actor._
import akka.util.Duration
import akka.util.duration._
-import java.util.concurrent.{BlockingDeque, LinkedBlockingDeque, TimeUnit}
+import java.util.concurrent.{ BlockingDeque, LinkedBlockingDeque, TimeUnit }
import scala.annotation.tailrec
object TestActor {
type Ignore = Option[PartialFunction[AnyRef, Boolean]]
- case class SetTimeout(d : Duration)
- case class SetIgnore(i : Ignore)
+ case class SetTimeout(d: Duration)
+ case class SetIgnore(i: Ignore)
}
-class TestActor(queue : BlockingDeque[AnyRef]) extends Actor with FSM[Int, TestActor.Ignore] {
+class TestActor(queue: BlockingDeque[AnyRef]) extends Actor with FSM[Int, TestActor.Ignore] {
import FSM._
import TestActor._
@@ -24,14 +24,14 @@ class TestActor(queue : BlockingDeque[AnyRef]) extends Actor with FSM[Int, TestA
startWith(0, None)
when(0, stateTimeout = 5 seconds) {
- case Ev(SetTimeout(d)) =>
+ case Ev(SetTimeout(d)) ⇒
setStateTimeout(0, if (d.finite_?) d else None)
stay
- case Ev(SetIgnore(ign)) => stay using ign
- case Ev(StateTimeout) =>
+ case Ev(SetIgnore(ign)) ⇒ stay using ign
+ case Ev(StateTimeout) ⇒
stop
- case Event(x : AnyRef, ign) =>
- val ignore = ign map (z => if (z isDefinedAt x) z(x) else false) getOrElse false
+ case Event(x: AnyRef, ign) ⇒
+ val ignore = ign map (z ⇒ if (z isDefinedAt x) z(x) else false) getOrElse false
if (!ignore) {
queue.offerLast(x)
}
@@ -74,7 +74,7 @@ class TestActor(queue : BlockingDeque[AnyRef]) extends Actor with FSM[Int, TestA
trait TestKit {
private val queue = new LinkedBlockingDeque[AnyRef]()
-
+
/**
* ActorRef of the test actor. Access is provided to enable e.g.
* registration as message target.
@@ -87,14 +87,14 @@ trait TestKit {
*/
protected implicit val senderOption = Some(testActor)
- private var end : Duration = Duration.Inf
+ private var end: Duration = Duration.Inf
/*
* THIS IS A HACK: expectNoMsg and receiveWhile are bounded by `end`, but
* running them should not trigger an AssertionError, so mark their end
* time here and do not fail at the end of `within` if that time is not
* long gone.
*/
- private var lastSoftTimeout : Duration = now - 5.millis
+ private var lastSoftTimeout: Duration = now - 5.millis
/**
* Stop test actor. Should be done at the end of the test unless relying on
@@ -114,13 +114,13 @@ trait TestKit {
* } finally { stopTestActor }
*
*/
- def setTestActorTimeout(d : Duration) { testActor ! TestActor.SetTimeout(d) }
+ def setTestActorTimeout(d: Duration) { testActor ! TestActor.SetTimeout(d) }
/**
* Ignore all messages in the test actor for which the given partial
* function returns true.
*/
- def ignoreMsg(f : PartialFunction[AnyRef, Boolean]) { testActor ! TestActor.SetIgnore(Some(f)) }
+ def ignoreMsg(f: PartialFunction[AnyRef, Boolean]) { testActor ! TestActor.SetIgnore(Some(f)) }
/**
* Stop ignoring messages in the test actor.
@@ -130,12 +130,12 @@ trait TestKit {
/**
* Obtain current time (`System.currentTimeMillis`) as Duration.
*/
- def now : Duration = System.nanoTime.nanos
+ def now: Duration = System.nanoTime.nanos
/**
* Obtain time remaining for execution of the innermost enclosing `within` block.
*/
- def remaining : Duration = end - now
+ def remaining: Duration = end - now
/**
* Execute code block while bounding its execution time between `min` and
@@ -150,10 +150,10 @@ trait TestKit {
* }
*
*/
- def within[T](min : Duration, max : Duration)(f : => T) : T = {
+ def within[T](min: Duration, max: Duration)(f: ⇒ T): T = {
val start = now
val rem = end - start
- assert (rem >= min, "required min time "+min+" not possible, only "+format(min.unit, rem)+" left")
+ assert(rem >= min, "required min time " + min + " not possible, only " + format(min.unit, rem) + " left")
val max_diff = if (max < rem) max else rem
val prev_end = end
@@ -162,12 +162,12 @@ trait TestKit {
val ret = try f finally end = prev_end
val diff = now - start
- assert (min <= diff, "block took "+format(min.unit, diff)+", should at least have been "+min)
+ assert(min <= diff, "block took " + format(min.unit, diff) + ", should at least have been " + min)
/*
* caution: HACK AHEAD
*/
if (now - lastSoftTimeout > 5.millis) {
- assert (diff <= max_diff, "block took "+format(max.unit, diff)+", exceeding "+format(max.unit, max_diff))
+ assert(diff <= max_diff, "block took " + format(max.unit, diff) + ", exceeding " + format(max.unit, max_diff))
} else {
lastSoftTimeout -= 5.millis
}
@@ -178,13 +178,13 @@ trait TestKit {
/**
* Same as calling `within(0 seconds, max)(f)`.
*/
- def within[T](max : Duration)(f : => T) : T = within(0 seconds, max)(f)
+ def within[T](max: Duration)(f: ⇒ T): T = within(0 seconds, max)(f)
/**
* Same as `expectMsg`, but takes the maximum wait time from the innermost
* enclosing `within` block.
*/
- def expectMsg(obj : Any) : AnyRef = expectMsg(remaining, obj)
+ def expectMsg(obj: Any): AnyRef = expectMsg(remaining, obj)
/**
* Receive one message from the test actor and assert that it equals the
@@ -193,10 +193,10 @@ trait TestKit {
*
* @return the received object
*/
- def expectMsg(max : Duration, obj : Any) : AnyRef = {
+ def expectMsg(max: Duration, obj: Any): AnyRef = {
val o = receiveOne(max)
- assert (o ne null, "timeout during expectMsg")
- assert (obj == o, "expected "+obj+", found "+o)
+ assert(o ne null, "timeout during expectMsg")
+ assert(obj == o, "expected " + obj + ", found " + o)
o
}
@@ -204,7 +204,7 @@ trait TestKit {
* Same as `expectMsg`, but takes the maximum wait time from the innermost
* enclosing `within` block.
*/
- def expectMsg[T](f : PartialFunction[Any, T]) : T = expectMsg(remaining)(f)
+ def expectMsg[T](f: PartialFunction[Any, T]): T = expectMsg(remaining)(f)
/**
* Receive one message from the test actor and assert that the given
@@ -216,10 +216,10 @@ trait TestKit {
*
* @return the received object as transformed by the partial function
*/
- def expectMsg[T](max : Duration)(f : PartialFunction[Any, T]) : T = {
+ def expectMsg[T](max: Duration)(f: PartialFunction[Any, T]): T = {
val o = receiveOne(max)
- assert (o ne null, "timeout during expectMsg")
- assert (f.isDefinedAt(o), "does not match: "+o)
+ assert(o ne null, "timeout during expectMsg")
+ assert(f.isDefinedAt(o), "does not match: " + o)
f(o)
}
@@ -227,7 +227,7 @@ trait TestKit {
* Same as `expectMsgClass`, but takes the maximum wait time from the innermost
* enclosing `within` block.
*/
- def expectMsgClass[C](c : Class[C]) : C = expectMsgClass(remaining, c)
+ def expectMsgClass[C](c: Class[C]): C = expectMsgClass(remaining, c)
/**
* Receive one message from the test actor and assert that it conforms to
@@ -236,10 +236,10 @@ trait TestKit {
*
* @return the received object
*/
- def expectMsgClass[C](max : Duration, c : Class[C]) : C = {
+ def expectMsgClass[C](max: Duration, c: Class[C]): C = {
val o = receiveOne(max)
- assert (o ne null, "timeout during expectMsgClass")
- assert (c isInstance o, "expected "+c+", found "+o.getClass)
+ assert(o ne null, "timeout during expectMsgClass")
+ assert(c isInstance o, "expected " + c + ", found " + o.getClass)
o.asInstanceOf[C]
}
@@ -247,7 +247,7 @@ trait TestKit {
* Same as `expectMsgAnyOf`, but takes the maximum wait time from the innermost
* enclosing `within` block.
*/
- def expectMsgAnyOf(obj : Any*) : AnyRef = expectMsgAnyOf(remaining, obj : _*)
+ def expectMsgAnyOf(obj: Any*): AnyRef = expectMsgAnyOf(remaining, obj: _*)
/**
* Receive one message from the test actor and assert that it equals one of
@@ -256,10 +256,10 @@ trait TestKit {
*
* @return the received object
*/
- def expectMsgAnyOf(max : Duration, obj : Any*) : AnyRef = {
+ def expectMsgAnyOf(max: Duration, obj: Any*): AnyRef = {
val o = receiveOne(max)
- assert (o ne null, "timeout during expectMsgAnyOf")
- assert (obj exists (_ == o), "found unexpected "+o)
+ assert(o ne null, "timeout during expectMsgAnyOf")
+ assert(obj exists (_ == o), "found unexpected " + o)
o
}
@@ -267,7 +267,7 @@ trait TestKit {
* Same as `expectMsgAnyClassOf`, but takes the maximum wait time from the innermost
* enclosing `within` block.
*/
- def expectMsgAnyClassOf(obj : Class[_]*) : AnyRef = expectMsgAnyClassOf(remaining, obj : _*)
+ def expectMsgAnyClassOf(obj: Class[_]*): AnyRef = expectMsgAnyClassOf(remaining, obj: _*)
/**
* Receive one message from the test actor and assert that it conforms to
@@ -276,10 +276,10 @@ trait TestKit {
*
* @return the received object
*/
- def expectMsgAnyClassOf(max : Duration, obj : Class[_]*) : AnyRef = {
+ def expectMsgAnyClassOf(max: Duration, obj: Class[_]*): AnyRef = {
val o = receiveOne(max)
- assert (o ne null, "timeout during expectMsgAnyClassOf")
- assert (obj exists (_ isInstance o), "found unexpected "+o)
+ assert(o ne null, "timeout during expectMsgAnyClassOf")
+ assert(obj exists (_ isInstance o), "found unexpected " + o)
o
}
@@ -287,7 +287,7 @@ trait TestKit {
* Same as `expectMsgAllOf`, but takes the maximum wait time from the innermost
* enclosing `within` block.
*/
- def expectMsgAllOf(obj : Any*) { expectMsgAllOf(remaining, obj : _*) }
+ def expectMsgAllOf(obj: Any*) { expectMsgAllOf(remaining, obj: _*) }
/**
* Receive a number of messages from the test actor matching the given
@@ -304,16 +304,16 @@ trait TestKit {
* }
*
*/
- def expectMsgAllOf(max : Duration, obj : Any*) {
+ def expectMsgAllOf(max: Duration, obj: Any*) {
val recv = receiveN(obj.size, now + max)
- assert (obj forall (x => recv exists (x == _)), "not found all")
+ assert(obj forall (x ⇒ recv exists (x == _)), "not found all")
}
/**
* Same as `expectMsgAllClassOf`, but takes the maximum wait time from the innermost
* enclosing `within` block.
*/
- def expectMsgAllClassOf(obj : Class[_]*) { expectMsgAllClassOf(remaining, obj : _*) }
+ def expectMsgAllClassOf(obj: Class[_]*) { expectMsgAllClassOf(remaining, obj: _*) }
/**
* Receive a number of messages from the test actor matching the given
@@ -323,16 +323,16 @@ trait TestKit {
* Wait time is bounded by the given duration, with an AssertionFailure
* being thrown in case of timeout.
*/
- def expectMsgAllClassOf(max : Duration, obj : Class[_]*) {
+ def expectMsgAllClassOf(max: Duration, obj: Class[_]*) {
val recv = receiveN(obj.size, now + max)
- assert (obj forall (x => recv exists (_.getClass eq x)), "not found all")
+ assert(obj forall (x ⇒ recv exists (_.getClass eq x)), "not found all")
}
/**
* Same as `expectMsgAllConformingOf`, but takes the maximum wait time from the innermost
* enclosing `within` block.
*/
- def expectMsgAllConformingOf(obj : Class[_]*) { expectMsgAllClassOf(remaining, obj : _*) }
+ def expectMsgAllConformingOf(obj: Class[_]*) { expectMsgAllClassOf(remaining, obj: _*) }
/**
* Receive a number of messages from the test actor matching the given
@@ -345,9 +345,9 @@ trait TestKit {
* Beware that one object may satisfy all given class constraints, which
* may be counter-intuitive.
*/
- def expectMsgAllConformingOf(max : Duration, obj : Class[_]*) {
+ def expectMsgAllConformingOf(max: Duration, obj: Class[_]*) {
val recv = receiveN(obj.size, now + max)
- assert (obj forall (x => recv exists (x isInstance _)), "not found all")
+ assert(obj forall (x ⇒ recv exists (x isInstance _)), "not found all")
}
/**
@@ -359,9 +359,9 @@ trait TestKit {
/**
* Assert that no message is received for the specified time.
*/
- def expectNoMsg(max : Duration) {
+ def expectNoMsg(max: Duration) {
val o = receiveOne(max)
- assert (o eq null, "received unexpected message "+o)
+ assert(o eq null, "received unexpected message " + o)
lastSoftTimeout = now
}
@@ -369,7 +369,7 @@ trait TestKit {
* Same as `receiveWhile`, but takes the maximum wait time from the innermost
* enclosing `within` block.
*/
- def receiveWhile[T](f : PartialFunction[AnyRef, T]) : Seq[T] = receiveWhile(remaining)(f)
+ def receiveWhile[T](f: PartialFunction[AnyRef, T]): Seq[T] = receiveWhile(remaining)(f)
/**
* Receive a series of messages as long as the given partial function
@@ -391,16 +391,17 @@ trait TestKit {
* assert(series == (1 to 7).toList)
*
*/
- def receiveWhile[T](max : Duration)(f : PartialFunction[AnyRef, T]) : Seq[T] = {
+ def receiveWhile[T](max: Duration)(f: PartialFunction[AnyRef, T]): Seq[T] = {
val stop = now + max
- @tailrec def doit(acc : List[T]) : List[T] = {
+ @tailrec
+ def doit(acc: List[T]): List[T] = {
receiveOne(stop - now) match {
- case null =>
+ case null ⇒
acc.reverse
- case o if (f isDefinedAt o) =>
+ case o if (f isDefinedAt o) ⇒
doit(f(o) :: acc)
- case o =>
+ case o ⇒
queue.offerFirst(o)
acc.reverse
}
@@ -411,16 +412,16 @@ trait TestKit {
ret
}
- private def receiveN(n : Int, stop : Duration) : Seq[AnyRef] = {
- for { x <- 1 to n } yield {
+ private def receiveN(n: Int, stop: Duration): Seq[AnyRef] = {
+ for { x ← 1 to n } yield {
val timeout = stop - now
val o = receiveOne(timeout)
- assert (o ne null, "timeout while expecting "+n+" messages")
+ assert(o ne null, "timeout while expecting " + n + " messages")
o
}
}
- private def receiveOne(max : Duration) : AnyRef = {
+ private def receiveOne(max: Duration): AnyRef = {
if (max == 0.seconds) {
queue.pollFirst
} else if (max.finite_?) {
@@ -430,7 +431,7 @@ trait TestKit {
}
}
- private def format(u : TimeUnit, d : Duration) = "%.3f %s".format(d.toUnit(u), u.toString.toLowerCase)
+ private def format(u: TimeUnit, d: Duration) = "%.3f %s".format(d.toUnit(u), u.toString.toLowerCase)
}
// vim: set ts=2 sw=2 et:
diff --git a/akka-testkit/src/test/scala/akka/testkit/TestActorRefSpec.scala b/akka-testkit/src/test/scala/akka/testkit/TestActorRefSpec.scala
index 0bf0c8df27..f12667899e 100644
--- a/akka-testkit/src/test/scala/akka/testkit/TestActorRefSpec.scala
+++ b/akka-testkit/src/test/scala/akka/testkit/TestActorRefSpec.scala
@@ -1,7 +1,7 @@
package akka.testkit
import org.scalatest.matchers.MustMatchers
-import org.scalatest.{BeforeAndAfterEach, WordSpec}
+import org.scalatest.{ BeforeAndAfterEach, WordSpec }
import akka.actor._
import akka.config.Supervision.OneForOneStrategy
import akka.event.EventHandler
@@ -17,45 +17,45 @@ object TestActorRefSpec {
var counter = 4
val thread = Thread.currentThread
- var otherthread : Thread = null
+ var otherthread: Thread = null
trait TActor extends Actor {
def receive = new Receive {
val recv = receiveT
- def isDefinedAt(o : Any) = recv.isDefinedAt(o)
- def apply(o : Any) {
+ def isDefinedAt(o: Any) = recv.isDefinedAt(o)
+ def apply(o: Any) {
if (Thread.currentThread ne thread)
otherthread = Thread.currentThread
recv(o)
}
}
- def receiveT : Receive
+ def receiveT: Receive
}
class ReplyActor extends TActor {
var replyTo: Channel[Any] = null
def receiveT = {
- case "complexRequest" => {
+ case "complexRequest" ⇒ {
replyTo = self.channel
val worker = TestActorRef[WorkerActor].start()
worker ! "work"
}
- case "complexRequest2" =>
+ case "complexRequest2" ⇒
val worker = TestActorRef[WorkerActor].start()
worker ! self.channel
- case "workDone" => replyTo ! "complexReply"
- case "simpleRequest" => self.reply("simpleReply")
+ case "workDone" ⇒ replyTo ! "complexReply"
+ case "simpleRequest" ⇒ self.reply("simpleReply")
}
}
class WorkerActor() extends TActor {
def receiveT = {
- case "work" => {
+ case "work" ⇒ {
self.reply("workDone")
self.stop()
}
- case replyTo: Channel[Any] => {
+ case replyTo: Channel[Any] ⇒ {
replyTo ! "complexReply"
}
}
@@ -64,13 +64,13 @@ object TestActorRefSpec {
class SenderActor(replyActor: ActorRef) extends TActor {
def receiveT = {
- case "complex" => replyActor ! "complexRequest"
- case "complex2" => replyActor ! "complexRequest2"
- case "simple" => replyActor ! "simpleRequest"
- case "complexReply" => {
+ case "complex" ⇒ replyActor ! "complexRequest"
+ case "complex2" ⇒ replyActor ! "complexRequest2"
+ case "simple" ⇒ replyActor ! "simpleRequest"
+ case "complexReply" ⇒ {
counter -= 1
}
- case "simpleReply" => {
+ case "simpleReply" ⇒ {
counter -= 1
}
}
@@ -79,9 +79,9 @@ object TestActorRefSpec {
class Logger extends Actor {
import EventHandler._
var count = 0
- var msg : String = _
+ var msg: String = _
def receive = {
- case Warning(_, m : String) => count += 1; msg = m
+ case Warning(_, m: String) ⇒ count += 1; msg = m
}
}
@@ -98,7 +98,7 @@ class TestActorRefSpec extends WordSpec with MustMatchers with BeforeAndAfterEac
}
private def assertThread {
- otherthread must (be (null) or equal (thread))
+ otherthread must (be(null) or equal(thread))
}
"A TestActorRef must be an ActorRef, hence it" must {
@@ -107,24 +107,24 @@ class TestActorRefSpec extends WordSpec with MustMatchers with BeforeAndAfterEac
"used with TestActorRef" in {
val a = TestActorRef(new Actor {
- val nested = TestActorRef(new Actor { def receive = { case _ => } }).start()
- def receive = { case _ => self reply nested }
+ val nested = TestActorRef(new Actor { def receive = { case _ ⇒ } }).start()
+ def receive = { case _ ⇒ self reply nested }
}).start()
a must not be (null)
val nested = (a !! "any").get.asInstanceOf[ActorRef]
nested must not be (null)
- a must not be theSameInstanceAs (nested)
+ a must not be theSameInstanceAs(nested)
}
"used with ActorRef" in {
val a = TestActorRef(new Actor {
- val nested = Actor.actorOf(new Actor { def receive = { case _ => } }).start()
- def receive = { case _ => self reply nested }
+ val nested = Actor.actorOf(new Actor { def receive = { case _ ⇒ } }).start()
+ def receive = { case _ ⇒ self reply nested }
}).start()
a must not be (null)
val nested = (a !! "any").get.asInstanceOf[ActorRef]
nested must not be (null)
- a must not be theSameInstanceAs (nested)
+ a must not be theSameInstanceAs(nested)
}
}
@@ -140,7 +140,7 @@ class TestActorRefSpec extends WordSpec with MustMatchers with BeforeAndAfterEac
clientRef ! "simple"
clientRef ! "simple"
- counter must be (0)
+ counter must be(0)
counter = 4
@@ -149,7 +149,7 @@ class TestActorRefSpec extends WordSpec with MustMatchers with BeforeAndAfterEac
clientRef ! "simple"
clientRef ! "simple"
- counter must be (0)
+ counter must be(0)
assertThread
}
@@ -160,7 +160,7 @@ class TestActorRefSpec extends WordSpec with MustMatchers with BeforeAndAfterEac
a !! PoisonPill
}
a must not be ('running)
- a must be ('shutdown)
+ a must be('shutdown)
assertThread
}
@@ -170,26 +170,26 @@ class TestActorRefSpec extends WordSpec with MustMatchers with BeforeAndAfterEac
val boss = TestActorRef(new TActor {
self.faultHandler = OneForOneStrategy(List(classOf[Throwable]), Some(2), Some(1000))
val ref = TestActorRef(new TActor {
- def receiveT = { case _ => }
+ def receiveT = { case _ ⇒ }
override def preRestart(reason: Throwable) { counter -= 1 }
override def postRestart(reason: Throwable) { counter -= 1 }
}).start()
self.dispatcher = CallingThreadDispatcher.global
self link ref
- def receiveT = { case "sendKill" => ref ! Kill }
+ def receiveT = { case "sendKill" ⇒ ref ! Kill }
}).start()
boss ! "sendKill"
- counter must be (0)
+ counter must be(0)
assertThread
}
"support futures" in {
val a = TestActorRef[WorkerActor].start()
- val f : Future[String] = a !!! "work"
- f must be ('completed)
- f.get must equal ("workDone")
+ val f: Future[String] = a !!! "work"
+ f must be('completed)
+ f.get must equal("workDone")
}
}
@@ -198,49 +198,49 @@ class TestActorRefSpec extends WordSpec with MustMatchers with BeforeAndAfterEac
"allow access to internals" in {
val ref = TestActorRef(new TActor {
- var s : String = _
+ var s: String = _
def receiveT = {
- case x : String => s = x
+ case x: String ⇒ s = x
}
}).start()
ref ! "hallo"
val actor = ref.underlyingActor
- actor.s must equal ("hallo")
+ actor.s must equal("hallo")
}
"set receiveTimeout to None" in {
val a = TestActorRef[WorkerActor]
- a.receiveTimeout must be (None)
+ a.receiveTimeout must be(None)
}
"set CallingThreadDispatcher" in {
val a = TestActorRef[WorkerActor]
- a.dispatcher.getClass must be (classOf[CallingThreadDispatcher])
+ a.dispatcher.getClass must be(classOf[CallingThreadDispatcher])
}
"warn about scheduled supervisor" in {
- val boss = Actor.actorOf(new Actor { def receive = { case _ => } }).start()
+ val boss = Actor.actorOf(new Actor { def receive = { case _ ⇒ } }).start()
val ref = TestActorRef[WorkerActor].start()
val log = TestActorRef[Logger]
EventHandler.addListener(log)
boss link ref
val la = log.underlyingActor
- la.count must be (1)
- la.msg must (include ("supervisor") and include ("CallingThreadDispatcher"))
+ la.count must be(1)
+ la.msg must (include("supervisor") and include("CallingThreadDispatcher"))
EventHandler.removeListener(log)
}
"proxy isDefinedAt/apply for the underlying actor" in {
val ref = TestActorRef[WorkerActor].start()
- ref.isDefinedAt("work") must be (true)
- ref.isDefinedAt("sleep") must be (false)
+ ref.isDefinedAt("work") must be(true)
+ ref.isDefinedAt("sleep") must be(false)
intercept[IllegalActorStateException] { ref("work") }
val ch = Future.channel()
ref ! ch
val f = ch.future
- f must be ('completed)
- f.get must be ("complexReply")
+ f must be('completed)
+ f.get must be("complexReply")
}
}
diff --git a/akka-typed-actor/src/main/scala/akka/actor/ThaipedActor.scala b/akka-typed-actor/src/main/scala/akka/actor/ThaipedActor.scala
index 3c000cb9fa..11eead0872 100644
--- a/akka-typed-actor/src/main/scala/akka/actor/ThaipedActor.scala
+++ b/akka-typed-actor/src/main/scala/akka/actor/ThaipedActor.scala
@@ -1,16 +1,16 @@
package akka.thaipedactor
-import java.lang.reflect.{Method, InvocationHandler, Proxy}
-import akka.japi.{Creator, Option => JOption}
-import akka.actor.Actor.{actorOf, futureToAnyOptionAsTypedOption}
-import akka.transactor.annotation.{Coordinated => CoordinatedAnnotation}
+import java.lang.reflect.{ Method, InvocationHandler, Proxy }
+import akka.japi.{ Creator, Option ⇒ JOption }
+import akka.actor.Actor.{ actorOf, futureToAnyOptionAsTypedOption }
+import akka.transactor.annotation.{ Coordinated ⇒ CoordinatedAnnotation }
import akka.util.Duration
-import akka.dispatch.{MessageDispatcher, Dispatchers, AlreadyCompletedFuture, Future}
-import akka.actor.{ActorRef, Actor}
+import akka.dispatch.{ MessageDispatcher, Dispatchers, AlreadyCompletedFuture, Future }
+import akka.actor.{ ActorRef, Actor }
object MethodCall {
private[akka] def isOneWay(method: Method): Boolean =
- method.getReturnType == java.lang.Void.TYPE
+ method.getReturnType == java.lang.Void.TYPE
private[akka] def isCoordinated(method: Method): Boolean =
method.isAnnotationPresent(classOf[CoordinatedAnnotation])
@@ -43,59 +43,59 @@ case class MethodCall(method: Method, parameters: Array[AnyRef]) {
//We do not yet obey Actor.SERIALIZE_MESSAGES
parameters match {
- case null => method.invoke(instance)
- case args if args.length == 0 => method.invoke(instance)
- case args => method.invoke(instance, args:_*)
+ case null ⇒ method.invoke(instance)
+ case args if args.length == 0 ⇒ method.invoke(instance)
+ case args ⇒ method.invoke(instance, args: _*)
}
}
}
object ThaipedActor {
- class ThaipedActor[TI <: AnyRef](createInstance: => TI) extends Actor {
+ class ThaipedActor[TI <: AnyRef](createInstance: ⇒ TI) extends Actor {
val me = createInstance
def receive = {
- case m: MethodCall => m match {
- case m if m.isOneWay => m.callMethodOn(me)
+ case m: MethodCall ⇒ m match {
+ case m if m.isOneWay ⇒ m.callMethodOn(me)
- case m if m.returnsFuture_? => self.senderFuture.get completeWith m.callMethodOn(me).asInstanceOf[Future[Any]]
+ case m if m.returnsFuture_? ⇒ self.senderFuture.get completeWith m.callMethodOn(me).asInstanceOf[Future[Any]]
- case m => self reply m.callMethodOn(me)
+ case m ⇒ self reply m.callMethodOn(me)
}
}
}
case class ThaipedActorInvocationHandler(actor: ActorRef) extends InvocationHandler {
def invoke(proxy: AnyRef, method: Method, args: Array[AnyRef]): AnyRef = method.getName match {
- case "toString" => actor.toString
- case "equals" => if (proxy eq args(0)) java.lang.Boolean.TRUE else java.lang.Boolean.FALSE
- case "hashCode" => actor.hashCode.asInstanceOf[AnyRef]
- case _ =>
- MethodCall(method, args) match {
- case m if m.isOneWay =>
- actor ! m
- null
+ case "toString" ⇒ actor.toString
+ case "equals" ⇒ if (proxy eq args(0)) java.lang.Boolean.TRUE else java.lang.Boolean.FALSE
+ case "hashCode" ⇒ actor.hashCode.asInstanceOf[AnyRef]
+ case _ ⇒
+ MethodCall(method, args) match {
+ case m if m.isOneWay ⇒
+ actor ! m
+ null
- case m if m.returnsJOption_? =>
- (actor !!! m).as[JOption[Any]] match {
- case Some(null) => JOption.none[Any]
- case Some(joption) => joption
- case None => JOption.none[Any]
- }
+ case m if m.returnsJOption_? ⇒
+ (actor !!! m).as[JOption[Any]] match {
+ case Some(null) ⇒ JOption.none[Any]
+ case Some(joption) ⇒ joption
+ case None ⇒ JOption.none[Any]
+ }
- case m if m.returnsOption_? =>
- (actor !!! m).as[AnyRef] match {
- case Some(null) => None
- case Some(option) => option
- case None => None
- }
+ case m if m.returnsOption_? ⇒
+ (actor !!! m).as[AnyRef] match {
+ case Some(null) ⇒ None
+ case Some(option) ⇒ option
+ case None ⇒ None
+ }
- case m if m.returnsFuture_? =>
- actor !!! m
+ case m if m.returnsFuture_? ⇒
+ actor !!! m
- case m =>
- (actor !!! m).get
- }
+ case m ⇒
+ (actor !!! m).get
+ }
}
}
@@ -103,16 +103,16 @@ object ThaipedActor {
case class Configuration(timeout: Duration = defaultTimeout, dispatcher: MessageDispatcher = Dispatchers.defaultGlobalDispatcher)
- def thaipedActorOf[T <: AnyRef,TI <: T](interface: Class[T], impl: Class[TI], config: Configuration, loader: ClassLoader): T =
+ def thaipedActorOf[T <: AnyRef, TI <: T](interface: Class[T], impl: Class[TI], config: Configuration, loader: ClassLoader): T =
newThaipedActor(interface, impl.newInstance.asInstanceOf[TI], config, loader)
- def thaipedActorOf[T <: AnyRef,TI <: T](interface: Class[T], impl: Creator[TI], config: Configuration, loader: ClassLoader): T =
+ def thaipedActorOf[T <: AnyRef, TI <: T](interface: Class[T], impl: Creator[TI], config: Configuration, loader: ClassLoader): T =
newThaipedActor(interface, impl.create, config, loader)
- def thaipedActorOf[T <: AnyRef : Manifest, TI <: T](impl: Creator[TI], config: Configuration, loader: ClassLoader): T =
- newThaipedActor[T,TI](implicitly[Manifest[T]].erasure.asInstanceOf[Class[T]], impl.create, config, loader)
+ def thaipedActorOf[T <: AnyRef: Manifest, TI <: T](impl: Creator[TI], config: Configuration, loader: ClassLoader): T =
+ newThaipedActor[T, TI](implicitly[Manifest[T]].erasure.asInstanceOf[Class[T]], impl.create, config, loader)
- protected def newThaipedActor[T <: AnyRef, TI <: T](interface: Class[T], impl: => TI, config: Configuration, loader: ClassLoader): T = {
+ protected def newThaipedActor[T <: AnyRef, TI <: T](interface: Class[T], impl: ⇒ TI, config: Configuration, loader: ClassLoader): T = {
val actor = actorOf(new ThaipedActor[TI](impl))
actor.timeout = config.timeout.toMillis
@@ -125,28 +125,28 @@ object ThaipedActor {
}
def stop(thaipedActor: AnyRef): Boolean = getActorFor(thaipedActor) match {
- case Some(ref) =>
+ case Some(ref) ⇒
ref.stop
true
- case _ => false
+ case _ ⇒ false
}
def getActorFor(thaipedActor: AnyRef): Option[ActorRef] = thaipedActor match {
- case null => None
- case other =>
+ case null ⇒ None
+ case other ⇒
Proxy.getInvocationHandler(other) match {
- case null => None
- case handler: ThaipedActorInvocationHandler => Option(handler.actor)
- case _ => None
+ case null ⇒ None
+ case handler: ThaipedActorInvocationHandler ⇒ Option(handler.actor)
+ case _ ⇒ None
}
}
def isThaipedActor(thaipedActor_? : AnyRef): Boolean = thaipedActor_? match {
- case null => false
- case some => Proxy.getInvocationHandler(some) match {
- case null => false
- case handler: ThaipedActorInvocationHandler => true
- case _ => false
+ case null ⇒ false
+ case some ⇒ Proxy.getInvocationHandler(some) match {
+ case null ⇒ false
+ case handler: ThaipedActorInvocationHandler ⇒ true
+ case _ ⇒ false
}
}
}
\ No newline at end of file
diff --git a/akka-typed-actor/src/main/scala/akka/actor/TypedActor.scala b/akka-typed-actor/src/main/scala/akka/actor/TypedActor.scala
index b593d2eaed..81e3de54b7 100644
--- a/akka-typed-actor/src/main/scala/akka/actor/TypedActor.scala
+++ b/akka-typed-actor/src/main/scala/akka/actor/TypedActor.scala
@@ -8,15 +8,15 @@ import Actor._
import akka.config.Supervision._
import akka.util._
import ReflectiveAccess._
-import akka.transactor.{Coordinated, Coordination, CoordinateException}
-import akka.transactor.annotation.{Coordinated => CoordinatedAnnotation}
+import akka.transactor.{ Coordinated, Coordination, CoordinateException }
+import akka.transactor.annotation.{ Coordinated ⇒ CoordinatedAnnotation }
-import org.codehaus.aspectwerkz.joinpoint.{MethodRtti, JoinPoint}
+import org.codehaus.aspectwerkz.joinpoint.{ MethodRtti, JoinPoint }
import org.codehaus.aspectwerkz.proxy.Proxy
-import org.codehaus.aspectwerkz.annotation.{Aspect, Around}
+import org.codehaus.aspectwerkz.annotation.{ Aspect, Around }
import java.net.InetSocketAddress
-import java.lang.reflect.{Method, Field, InvocationHandler, Proxy => JProxy}
+import java.lang.reflect.{ Method, Field, InvocationHandler, Proxy ⇒ JProxy }
import scala.reflect.BeanProperty
import akka.dispatch._
@@ -114,8 +114,10 @@ import akka.dispatch._
abstract class TypedActor extends Actor with Proxyable {
val DELEGATE_FIELD_NAME = "DELEGATE_0".intern
- @volatile private[akka] var proxy: AnyRef = _
- @volatile private var proxyDelegate: Field = _
+ @volatile
+ private[akka] var proxy: AnyRef = _
+ @volatile
+ private var proxyDelegate: Field = _
/**
* Holds RTTI (runtime type information) for the TypedActor, f.e. current 'sender'
@@ -207,22 +209,21 @@ abstract class TypedActor extends Actor with Proxyable {
self.senderFuture.get.asInstanceOf[CompletableFuture[T]] completeWithResult value
def receive = {
- case joinPoint: JoinPoint =>
+ case joinPoint: JoinPoint ⇒
SenderContextInfo.senderActorRef.withValue(self) {
SenderContextInfo.senderProxy.withValue(proxy) {
- if (Actor.SERIALIZE_MESSAGES) serializeArguments(joinPoint)
+ if (Actor.SERIALIZE_MESSAGES) serializeArguments(joinPoint)
if (TypedActor.isOneWay(joinPoint)) joinPoint.proceed
else if (TypedActor.returnsFuture_?(joinPoint)) {
joinPoint.proceed match {
- case f: Future[Any] => self.senderFuture.get.completeWith(f)
- case null => self.reply(null)
+ case f: Future[Any] ⇒ self.senderFuture.get.completeWith(f)
+ case null ⇒ self.reply(null)
}
- }
- else self.reply(joinPoint.proceed)
+ } else self.reply(joinPoint.proceed)
}
}
- case coordinated @ Coordinated(joinPoint: JoinPoint) =>
+ case coordinated@Coordinated(joinPoint: JoinPoint) ⇒
SenderContextInfo.senderActorRef.withValue(self) {
SenderContextInfo.senderProxy.withValue(proxy) {
if (Actor.SERIALIZE_MESSAGES) serializeArguments(joinPoint)
@@ -230,9 +231,9 @@ abstract class TypedActor extends Actor with Proxyable {
}
}
- case Link(proxy) => self.link(proxy)
- case Unlink(proxy) => self.unlink(proxy)
- case unexpected => throw new IllegalActorStateException(
+ case Link(proxy) ⇒ self.link(proxy)
+ case Unlink(proxy) ⇒ self.unlink(proxy)
+ case unexpected ⇒ throw new IllegalActorStateException(
"Unexpected message [" + unexpected + "] sent to [" + this + "]")
}
@@ -254,29 +255,29 @@ abstract class TypedActor extends Actor with Proxyable {
val args = joinPoint.getRtti.asInstanceOf[MethodRtti].getParameterValues
var unserializable = false
var hasMutableArgument = false
- for (arg <- args.toList) {
+ for (arg ← args.toList) {
if (!arg.isInstanceOf[String] &&
- !arg.isInstanceOf[Byte] &&
- !arg.isInstanceOf[Int] &&
- !arg.isInstanceOf[Long] &&
- !arg.isInstanceOf[Float] &&
- !arg.isInstanceOf[Double] &&
- !arg.isInstanceOf[Boolean] &&
- !arg.isInstanceOf[Char] &&
- !arg.isInstanceOf[java.lang.Byte] &&
- !arg.isInstanceOf[java.lang.Integer] &&
- !arg.isInstanceOf[java.lang.Long] &&
- !arg.isInstanceOf[java.lang.Float] &&
- !arg.isInstanceOf[java.lang.Double] &&
- !arg.isInstanceOf[java.lang.Boolean] &&
- !arg.isInstanceOf[java.lang.Character]) hasMutableArgument = true
+ !arg.isInstanceOf[Byte] &&
+ !arg.isInstanceOf[Int] &&
+ !arg.isInstanceOf[Long] &&
+ !arg.isInstanceOf[Float] &&
+ !arg.isInstanceOf[Double] &&
+ !arg.isInstanceOf[Boolean] &&
+ !arg.isInstanceOf[Char] &&
+ !arg.isInstanceOf[java.lang.Byte] &&
+ !arg.isInstanceOf[java.lang.Integer] &&
+ !arg.isInstanceOf[java.lang.Long] &&
+ !arg.isInstanceOf[java.lang.Float] &&
+ !arg.isInstanceOf[java.lang.Double] &&
+ !arg.isInstanceOf[java.lang.Boolean] &&
+ !arg.isInstanceOf[java.lang.Character]) hasMutableArgument = true
if (arg.getClass.getName.contains(TypedActor.AW_PROXY_PREFIX)) unserializable = true
}
if (!unserializable && hasMutableArgument) {
//FIXME serializeArguments
- // val copyOfArgs = Serializers.Java.deepClone(args)
- // joinPoint.getRtti.asInstanceOf[MethodRtti].setParameterValues(copyOfArgs.asInstanceOf[Array[AnyRef]])
+ // val copyOfArgs = Serializers.Java.deepClone(args)
+ // joinPoint.getRtti.asInstanceOf[MethodRtti].setParameterValues(copyOfArgs.asInstanceOf[Array[AnyRef]])
joinPoint
}
}
@@ -322,7 +323,7 @@ final class TypedActorContext(private[akka] val actorRef: ActorRef) {
*/
def uuid = actorRef.uuid
- def address = actorRef.address
+ def address = actorRef.address
def receiveTimeout = actorRef.receiveTimeout
@@ -362,10 +363,10 @@ final class TypedActorContext(private[akka] val actorRef: ActorRef) {
* Java style getter.
* @deprecated use 'sender()'
*/
- def getSender: AnyRef = {
- if (_sender eq null) throw new IllegalActorStateException("Sender reference should not be null.")
- else _sender
- }
+ def getSender: AnyRef = {
+ if (_sender eq null) throw new IllegalActorStateException("Sender reference should not be null.")
+ else _sender
+ }
/**
* Returns the current sender future TypedActor reference.
@@ -378,15 +379,15 @@ final class TypedActorContext(private[akka] val actorRef: ActorRef) {
object TypedActorConfiguration {
- def apply() : TypedActorConfiguration = {
+ def apply(): TypedActorConfiguration = {
new TypedActorConfiguration()
}
- def apply(timeoutMillis: Long) : TypedActorConfiguration = {
+ def apply(timeoutMillis: Long): TypedActorConfiguration = {
new TypedActorConfiguration().timeout(Duration(timeoutMillis, "millis"))
}
- def apply(timeout: Duration) : TypedActorConfiguration = {
+ def apply(timeout: Duration): TypedActorConfiguration = {
new TypedActorConfiguration().timeout(timeout)
}
}
@@ -402,19 +403,19 @@ final class TypedActorConfiguration {
private[akka] var _threadBasedDispatcher: Option[Boolean] = None
def timeout = _timeout
- def timeout(timeout: Duration) : TypedActorConfiguration = {
+ def timeout(timeout: Duration): TypedActorConfiguration = {
_timeout = timeout.toMillis
this
}
- def dispatcher(messageDispatcher: MessageDispatcher) : TypedActorConfiguration = {
+ def dispatcher(messageDispatcher: MessageDispatcher): TypedActorConfiguration = {
if (_threadBasedDispatcher.isDefined) throw new IllegalArgumentException(
"Cannot specify both 'threadBasedDispatcher()' and 'dispatcher()'")
_messageDispatcher = Some(messageDispatcher)
this
}
- def threadBasedDispatcher() : TypedActorConfiguration = {
+ def threadBasedDispatcher(): TypedActorConfiguration = {
if (_messageDispatcher.isDefined) throw new IllegalArgumentException(
"Cannot specify both 'threadBasedDispatcher()' and 'dispatcher()'")
_threadBasedDispatcher = Some(true)
@@ -428,7 +429,7 @@ final class TypedActorConfiguration {
* @author michaelkober
*/
trait TypedActorFactory {
- def create: TypedActor
+ def create: TypedActor
}
/**
@@ -458,7 +459,7 @@ object TypedActor {
* @param intfClass interface the typed actor implements
* @param factory factory method that constructs the typed actor
*/
- def newInstance[T](intfClass: Class[T], factory: => AnyRef): T = {
+ def newInstance[T](intfClass: Class[T], factory: ⇒ AnyRef): T = {
newInstance(intfClass, factory, TypedActorConfiguration())
}
@@ -468,7 +469,7 @@ object TypedActor {
* @param factory factory method that constructs the typed actor
* @param config configuration object for the typed actor
*/
- def newInstance[T](intfClass: Class[T], factory: => AnyRef, config: TypedActorConfiguration): T =
+ def newInstance[T](intfClass: Class[T], factory: ⇒ AnyRef, config: TypedActorConfiguration): T =
newInstance(intfClass, actorOf(newTypedActor(factory)), config)
/**
@@ -486,7 +487,7 @@ object TypedActor {
* @param targetClass implementation class of the typed actor
* @param timeout timeout for future
*/
- def newInstance[T](intfClass: Class[T], targetClass: Class[_], timeout: Long) : T = {
+ def newInstance[T](intfClass: Class[T], targetClass: Class[_], timeout: Long): T = {
newInstance(intfClass, targetClass, TypedActorConfiguration(timeout))
}
@@ -496,7 +497,7 @@ object TypedActor {
* @param factory factory method that constructs the typed actor
* @param timeout timeout for future
*/
- def newInstance[T](intfClass: Class[T], factory: => AnyRef, timeout: Long) : T = {
+ def newInstance[T](intfClass: Class[T], factory: ⇒ AnyRef, timeout: Long): T = {
newInstance(intfClass, factory, TypedActorConfiguration(timeout))
}
@@ -509,7 +510,7 @@ object TypedActor {
remoteAddress: Option[InetSocketAddress], timeout: Long): T =
newInstance(intfClass, targetClass, TypedActorConfiguration(timeout))
- private def newInstance[T](intfClass: Class[T], actorRef: ActorRef, config: TypedActorConfiguration) : T = {
+ private def newInstance[T](intfClass: Class[T], actorRef: ActorRef, config: TypedActorConfiguration): T = {
val typedActor = actorRef.actorInstance.get.asInstanceOf[TypedActor]
val proxy = Proxy.newInstance(Array(intfClass), Array(typedActor), true, false)
typedActor.initialize(proxy)
@@ -541,14 +542,14 @@ object TypedActor {
* });
*
*/
- def newInstance[T](intfClass: Class[T], factory: TypedActorFactory) : T =
+ def newInstance[T](intfClass: Class[T], factory: TypedActorFactory): T =
newInstance(intfClass, factory.create)
/**
* Java API.
*/
-// def newInstance[T](intfClass: Class[T], factory: TypedActorFactory, timeout: Long) : T =
-// newInstance(intfClass, factory.create, timeout)
+ // def newInstance[T](intfClass: Class[T], factory: TypedActorFactory, timeout: Long) : T =
+ // newInstance(intfClass, factory.create, timeout)
/**
* Java API.
@@ -578,7 +579,6 @@ object TypedActor {
awProxy.asInstanceOf[T]
}
-
/*
// NOTE: currently not used - but keep it around
private[akka] def newInstance[T <: TypedActor](targetClass: Class[T],
@@ -608,8 +608,8 @@ object TypedActor {
*/
def actorFor(proxy: AnyRef): Option[ActorRef] =
Actor.registry.local find {
- case a if a.actor.isInstanceOf[TypedActor] && a.actor.asInstanceOf[TypedActor].proxy == proxy =>
- a
+ case a if a.actor.isInstanceOf[TypedActor] && a.actor.asInstanceOf[TypedActor].proxy == proxy ⇒
+ a
}
/**
@@ -704,7 +704,7 @@ object TypedActor {
typedActor
}
- private[akka] def newTypedActor(factory: => AnyRef): TypedActor = {
+ private[akka] def newTypedActor(factory: ⇒ AnyRef): TypedActor = {
val instance = factory
val typedActor =
if (instance.isInstanceOf[TypedActor]) instance.asInstanceOf[TypedActor]
@@ -743,7 +743,6 @@ object TypedActor {
private[akka] def isJoinPoint(message: Any): Boolean = message.isInstanceOf[JoinPoint]
}
-
/**
* AspectWerkz Aspect that is turning POJO into proxy to a server managed remote TypedActor.
*
@@ -816,13 +815,13 @@ private[akka] abstract class ActorAspect {
isStopped switchOn {
val proxy = TypedActor.proxyFor(actorRef)
if (proxy ne null)
- TypedActor.stop(proxy)
+ TypedActor.stop(proxy)
}
}
if (isOneWay && isCoordinated) {
val coordinatedOpt = Option(Coordination.coordinated.value)
- val coordinated = coordinatedOpt.map( coord =>
+ val coordinated = coordinatedOpt.map(coord ⇒
if (Coordination.firstParty.value) { // already included in coordination
Coordination.firstParty.value = false
coord.noIncrement(joinPoint)
@@ -841,11 +840,11 @@ private[akka] abstract class ActorAspect {
} else if (TypedActor.returnsFuture_?(methodRtti)) {
actorRef.!!!(joinPoint, timeout)(senderActorRef)
} else if (TypedActor.returnsOption_?(methodRtti)) {
- import akka.japi.{Option => JOption}
+ import akka.japi.{ Option ⇒ JOption }
(actorRef.!!(joinPoint, timeout)(senderActorRef)).as[JOption[AnyRef]] match {
- case None => JOption.none[AnyRef]
- case Some(x) if ((x eq null) || x.isEmpty) => JOption.some[AnyRef](null)
- case Some(x) => x
+ case None ⇒ JOption.none[AnyRef]
+ case Some(x) if ((x eq null) || x.isEmpty) ⇒ JOption.some[AnyRef](null)
+ case Some(x) ⇒ x
}
} else {
val result = (actorRef.!!(joinPoint, timeout)(senderActorRef)).as[AnyRef]
@@ -861,8 +860,8 @@ private[akka] abstract class ActorAspect {
def extractOwnerTypeHint(s: String) =
s.indexOf(TypedActor.AW_PROXY_PREFIX) match {
- case -1 => s
- case x => s.substring(0,x + TypedActor.AW_PROXY_PREFIX.length)
+ case -1 ⇒ s
+ case x ⇒ s.substring(0, x + TypedActor.AW_PROXY_PREFIX.length)
}
//TODO: Add ownerTypeHint and parameter types to the TypedActorInfo?
val message: Tuple3[String, Array[Class[_]], Array[AnyRef]] =
@@ -889,16 +888,15 @@ private[akka] abstract class ActorAspect {
else if (future_?.isEmpty) throw new IllegalActorStateException("No future returned from call to [" + joinPoint + "]")
else if (TypedActor.returnsFuture_?(methodRtti)) future_?.get
else if (TypedActor.returnsOption_?(methodRtti)) {
- import akka.japi.{Option => JOption}
+ import akka.japi.{ Option ⇒ JOption }
future_?.get.await.resultOrException.as[JOption[AnyRef]] match {
- case None => JOption.none[AnyRef]
- case Some(x) if ((x eq null) || x.isEmpty) => JOption.some[AnyRef](null)
- case Some(x) => x
+ case None ⇒ JOption.none[AnyRef]
+ case Some(x) if ((x eq null) || x.isEmpty) ⇒ JOption.some[AnyRef](null)
+ case Some(x) ⇒ x
}
- }
- else {
+ } else {
val result = future_?.get.await.resultOrException
- if(result.isDefined) result.get
+ if (result.isDefined) result.get
else throw new IllegalActorStateException("No result returned from call to [" + joinPoint + "]")
}
}
@@ -911,12 +909,11 @@ private[akka] abstract class ActorAspect {
actorRef = init.actorRef
uuid = actorRef.uuid
timeout = init.timeout
- remoteAddress = None//actorRef.remoteAddress
+ remoteAddress = None //actorRef.remoteAddress
}
}
}
-
/**
* Internal helper class to help pass the contextual information between threads.
*
@@ -925,7 +922,7 @@ private[akka] abstract class ActorAspect {
private[akka] object SenderContextInfo {
import scala.util.DynamicVariable
private[actor] val senderActorRef = new DynamicVariable[ActorRef](null)
- private[actor] val senderProxy = new DynamicVariable[AnyRef](null)
+ private[actor] val senderProxy = new DynamicVariable[AnyRef](null)
}
/**
@@ -969,7 +966,6 @@ private[akka] sealed case class AspectInit(
timeout: Long) {
}
-
/**
* Marker interface for server manager typed actors.
*/
diff --git a/akka-typed-actor/src/main/scala/akka/config/TypedActorConfigurator.scala b/akka-typed-actor/src/main/scala/akka/config/TypedActorConfigurator.scala
index 451b742793..cfa937bb52 100644
--- a/akka-typed-actor/src/main/scala/akka/config/TypedActorConfigurator.scala
+++ b/akka-typed-actor/src/main/scala/akka/config/TypedActorConfigurator.scala
@@ -6,8 +6,8 @@ package akka.config
import Supervision._
-import java.util.{List => JList}
-import java.util.{ArrayList}
+import java.util.{ List ⇒ JList }
+import java.util.{ ArrayList }
import com.google.inject._
@@ -33,7 +33,7 @@ class TypedActorConfigurator {
* @return a list with all the typed actors for the class
*/
def getInstances[T](clazz: Class[T]): JList[T] =
- INSTANCE.getInstance(clazz).foldLeft(new ArrayList[T]){ (l, i) => l add i ; l }
+ INSTANCE.getInstance(clazz).foldLeft(new ArrayList[T]) { (l, i) ⇒ l add i; l }
/**
* Returns the first item in a list of all typed actors that has been put under supervision for the class specified.
@@ -67,7 +67,7 @@ class TypedActorConfigurator {
def getComponentInterfaces: JList[Class[_]] = {
val al = new ArrayList[Class[_]]
- for (c <- INSTANCE.getComponentInterfaces) al.add(c)
+ for (c ← INSTANCE.getComponentInterfaces) al.add(c)
al
}
diff --git a/akka-typed-actor/src/main/scala/akka/config/TypedActorGuiceConfigurator.scala b/akka-typed-actor/src/main/scala/akka/config/TypedActorGuiceConfigurator.scala
index 826ac95ed3..6631888c0d 100644
--- a/akka-typed-actor/src/main/scala/akka/config/TypedActorGuiceConfigurator.scala
+++ b/akka-typed-actor/src/main/scala/akka/config/TypedActorGuiceConfigurator.scala
@@ -26,7 +26,7 @@ import com.google.inject._
*/
private[akka] class TypedActorGuiceConfigurator extends TypedActorConfiguratorBase {
private var injector: Injector = _
- private var supervisor: Option[Supervisor] = None
+ private var supervisor: Option[Supervisor] = None
private var faultHandlingStrategy: FaultHandlingStrategy = NoFaultHandlingStrategy
private var components: List[SuperviseTypedActor] = _
private var supervised: List[Supervise] = Nil
@@ -45,8 +45,8 @@ private[akka] class TypedActorGuiceConfigurator extends TypedActorConfiguratorBa
if (injector eq null) throw new IllegalActorStateException(
"inject() and/or supervise() must be called before invoking getInstance(clazz)")
val (proxy, targetInstance, component) =
- typedActorRegistry.getOrElse(clazz, throw new IllegalActorStateException(
- "Class [" + clazz.getName + "] has not been put under supervision" +
+ typedActorRegistry.getOrElse(clazz, throw new IllegalActorStateException(
+ "Class [" + clazz.getName + "] has not been put under supervision" +
"\n(by passing in the config to the 'configure' and then invoking 'supervise') method"))
injector.injectMembers(targetInstance)
List(proxy.asInstanceOf[T])
@@ -61,27 +61,26 @@ private[akka] class TypedActorGuiceConfigurator extends TypedActorConfiguratorBa
}
def getComponentInterfaces: List[Class[_]] =
- for (c <- components) yield {
+ for (c ← components) yield {
if (c.intf.isDefined) c.intf.get
else c.target
}
- override def configure(faultHandlingStrategy: FaultHandlingStrategy, components: List[SuperviseTypedActor]):
- TypedActorConfiguratorBase = synchronized {
+ override def configure(faultHandlingStrategy: FaultHandlingStrategy, components: List[SuperviseTypedActor]): TypedActorConfiguratorBase = synchronized {
this.faultHandlingStrategy = faultHandlingStrategy
this.components = components.toArray.toList.asInstanceOf[List[SuperviseTypedActor]]
- bindings = for (component <- this.components) yield {
+ bindings = for (component ← this.components) yield {
newDelegatingProxy(component)
-// if (component.intf.isDefined) newDelegatingProxy(component)
-// else newSubclassingProxy(component)
+ // if (component.intf.isDefined) newDelegatingProxy(component)
+ // else newSubclassingProxy(component)
}
val deps = new java.util.ArrayList[DependencyBinding](bindings.size)
- for (b <- bindings) deps.add(b)
+ for (b ← bindings) deps.add(b)
modules.add(new TypedActorGuiceModule(deps))
this
}
-/*
+ /*
private def newSubclassingProxy(component: SuperviseTypedActor): DependencyBinding = {
val targetClass =
if (component.target.isInstanceOf[Class[_ <: TypedActor]]) component.target.asInstanceOf[Class[_ <: TypedActor]]
@@ -102,7 +101,7 @@ private[akka] class TypedActorGuiceConfigurator extends TypedActorConfiguratorBa
private def newDelegatingProxy(component: SuperviseTypedActor): DependencyBinding = {
component.target.getConstructor(Array[Class[_]](): _*).setAccessible(true)
val interfaceClass = if (component.intf.isDefined) component.intf.get
- else throw new IllegalActorStateException("No interface for TypedActor specified")
+ else throw new IllegalActorStateException("No interface for TypedActor specified")
val implementationClass = component.target
val timeout = component.timeout
@@ -150,7 +149,7 @@ private[akka] class TypedActorGuiceConfigurator extends TypedActorConfiguratorBa
* }})
*
*/
- def addExternalGuiceModule(module: Module): TypedActorConfiguratorBase = synchronized {
+ def addExternalGuiceModule(module: Module): TypedActorConfiguratorBase = synchronized {
modules.add(module)
this
}
diff --git a/akka-typed-actor/src/main/scala/akka/transactor/Coordination.scala b/akka-typed-actor/src/main/scala/akka/transactor/Coordination.scala
index 1f72176eed..716d70bc24 100644
--- a/akka-typed-actor/src/main/scala/akka/transactor/Coordination.scala
+++ b/akka-typed-actor/src/main/scala/akka/transactor/Coordination.scala
@@ -9,7 +9,7 @@ import akka.stm.Atomic
import scala.util.DynamicVariable
-class CoordinateException private[akka](message: String, cause: Throwable = null) extends AkkaException(message, cause)
+class CoordinateException private[akka] (message: String, cause: Throwable = null) extends AkkaException(message, cause)
/**
* Coordinating transactions between typed actors.
@@ -50,7 +50,7 @@ object Coordination {
* It's possible to specify whether or not this `coordinate` block waits for all of
* the transactions to complete - the default is that it does.
*/
- def coordinate[U](wait: Boolean = true)(body: => U): Unit = {
+ def coordinate[U](wait: Boolean = true)(body: ⇒ U): Unit = {
firstParty.value = !wait
coordinated.withValue(Coordinated()) {
body
@@ -65,7 +65,7 @@ object Coordination {
* Coordinated transactions will wait for all other transactions in the coordination
* before committing. The timeout is specified by the default transaction factory.
*/
- def coordinate[U](body: => U): Unit = coordinate(true)(body)
+ def coordinate[U](body: ⇒ U): Unit = coordinate(true)(body)
/**
* Java API: coordinate that accepts an [[akka.transactor.Atomically]].
diff --git a/akka-typed-actor/src/test/scala/actor/typed-actor/Issue552Spec.scala b/akka-typed-actor/src/test/scala/actor/typed-actor/Issue552Spec.scala
index 0092570fd3..4f986f37db 100644
--- a/akka-typed-actor/src/test/scala/actor/typed-actor/Issue552Spec.scala
+++ b/akka-typed-actor/src/test/scala/actor/typed-actor/Issue552Spec.scala
@@ -8,25 +8,25 @@ import org.junit.runner.RunWith
object Ticket552Spec {
-trait Base {
- val id: String
- def getSomething(key: String): String = id + key
-}
+ trait Base {
+ val id: String
+ def getSomething(key: String): String = id + key
+ }
-trait MyBaseOne extends Base {
- val id: String = "myBaseOne "
- def getSomethingDifferent(key: Int): Int
-}
+ trait MyBaseOne extends Base {
+ val id: String = "myBaseOne "
+ def getSomethingDifferent(key: Int): Int
+ }
-trait MyBaseTwo extends Base {
- val id: String = "myBaseTwo "
-}
+ trait MyBaseTwo extends Base {
+ val id: String = "myBaseTwo "
+ }
-class MyBaseOneImpl extends TypedActor with MyBaseOne {
- override def getSomethingDifferent(key: Int): Int = key + 2
-}
+ class MyBaseOneImpl extends TypedActor with MyBaseOne {
+ override def getSomethingDifferent(key: Int): Int = key + 2
+ }
-class MyBaseTwoImpl extends TypedActor with MyBaseTwo
+ class MyBaseTwoImpl extends TypedActor with MyBaseTwo
}
@@ -34,69 +34,72 @@ class MyBaseTwoImpl extends TypedActor with MyBaseTwo
class Ticket552Spec extends WordSpec with MustMatchers {
import Ticket552Spec._
- "TypedActor" should {
+ "TypedActor" should {
- "return int" in {
- val myBaseOneActor: MyBaseOne =
- TypedActor.newInstance[MyBaseOne](classOf[MyBaseOne],
- classOf[MyBaseOneImpl],3000)
+ "return int" in {
+ val myBaseOneActor: MyBaseOne =
+ TypedActor.newInstance[MyBaseOne](classOf[MyBaseOne],
+ classOf[MyBaseOneImpl], 3000)
- try {
- myBaseOneActor.getSomethingDifferent(5) must be === 7
- } catch {
- case e: Exception => println(e.toString)
- } finally {
- TypedActor.stop(myBaseOneActor)
- }
- }
+ try {
+ myBaseOneActor.getSomethingDifferent(5) must be === 7
+ } catch {
+ case e: Exception ⇒ println(e.toString)
+ }
+ finally {
+ TypedActor.stop(myBaseOneActor)
+ }
+ }
- "return string" in {
- val myBaseOneActor: Base =
- TypedActor.newInstance[Base](classOf[Base],
- classOf[MyBaseOneImpl],3000)
+ "return string" in {
+ val myBaseOneActor: Base =
+ TypedActor.newInstance[Base](classOf[Base],
+ classOf[MyBaseOneImpl], 3000)
- try {
- myBaseOneActor.getSomething("hello") must be === "myBaseOne hello"
- } catch {
- case e: Exception => println(e.toString)
- } finally {
- TypedActor.stop(myBaseOneActor)
- }
- }
+ try {
+ myBaseOneActor.getSomething("hello") must be === "myBaseOne hello"
+ } catch {
+ case e: Exception ⇒ println(e.toString)
+ }
+ finally {
+ TypedActor.stop(myBaseOneActor)
+ }
+ }
- "fail for myBaseTwo" in {
- val myBaseTwoActor: MyBaseTwo =
- TypedActor.newInstance[MyBaseTwo](classOf[MyBaseTwo],
- classOf[MyBaseTwoImpl],3000)
+ "fail for myBaseTwo" in {
+ val myBaseTwoActor: MyBaseTwo =
+ TypedActor.newInstance[MyBaseTwo](classOf[MyBaseTwo],
+ classOf[MyBaseTwoImpl], 3000)
- try {
- intercept[java.lang.AbstractMethodError] {
- myBaseTwoActor.getSomething("hello")
- }
- } catch {
- case e: java.lang.AbstractMethodError => e.printStackTrace
- }
- finally {
- TypedActor.stop(myBaseTwoActor)
- }
- }
+ try {
+ intercept[java.lang.AbstractMethodError] {
+ myBaseTwoActor.getSomething("hello")
+ }
+ } catch {
+ case e: java.lang.AbstractMethodError ⇒ e.printStackTrace
+ }
+ finally {
+ TypedActor.stop(myBaseTwoActor)
+ }
+ }
- "fail for myBaseOne inherited method" in {
- val myBaseOneActor: MyBaseOne =
- TypedActor.newInstance[MyBaseOne](classOf[MyBaseOne],
- classOf[MyBaseOneImpl],3000)
+ "fail for myBaseOne inherited method" in {
+ val myBaseOneActor: MyBaseOne =
+ TypedActor.newInstance[MyBaseOne](classOf[MyBaseOne],
+ classOf[MyBaseOneImpl], 3000)
- try {
- intercept[java.lang.AbstractMethodError] {
- myBaseOneActor.getSomething("hello")
- }
- } catch {
- case e: java.lang.AbstractMethodError => e.printStackTrace
- } finally {
- TypedActor.stop(myBaseOneActor)
- }
- }
+ try {
+ intercept[java.lang.AbstractMethodError] {
+ myBaseOneActor.getSomething("hello")
+ }
+ } catch {
+ case e: java.lang.AbstractMethodError ⇒ e.printStackTrace
+ }
+ finally {
+ TypedActor.stop(myBaseOneActor)
+ }
+ }
- }
+ }
}
diff --git a/akka-typed-actor/src/test/scala/actor/typed-actor/Issue675Spec.scala b/akka-typed-actor/src/test/scala/actor/typed-actor/Issue675Spec.scala
index dfdd298732..07678fccf2 100644
--- a/akka-typed-actor/src/test/scala/actor/typed-actor/Issue675Spec.scala
+++ b/akka-typed-actor/src/test/scala/actor/typed-actor/Issue675Spec.scala
@@ -13,7 +13,6 @@ import org.junit.runner.RunWith
import Issue675Spec._
-
object Issue675Spec {
var l = collection.mutable.ListBuffer.empty[String]
@@ -30,12 +29,8 @@ object Issue675Spec {
}
}
-
@RunWith(classOf[JUnitRunner])
-class Issue675Spec extends
- Spec with
- ShouldMatchers with
- BeforeAndAfterEach {
+class Issue675Spec extends Spec with ShouldMatchers with BeforeAndAfterEach {
override def afterEach() {
Actor.registry.local.shutdownAll()
diff --git a/akka-typed-actor/src/test/scala/actor/typed-actor/ThaipedActorSpec.scala b/akka-typed-actor/src/test/scala/actor/typed-actor/ThaipedActorSpec.scala
index df8e292ab4..78e95f1d0f 100644
--- a/akka-typed-actor/src/test/scala/actor/typed-actor/ThaipedActorSpec.scala
+++ b/akka-typed-actor/src/test/scala/actor/typed-actor/ThaipedActorSpec.scala
@@ -7,11 +7,11 @@ package akka.thaipedactor
import org.scalatest.matchers.MustMatchers
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
-import org.scalatest.{BeforeAndAfterAll, WordSpec, BeforeAndAfterEach}
+import org.scalatest.{ BeforeAndAfterAll, WordSpec, BeforeAndAfterEach }
import akka.thaipedactor.ThaipedActor._
-import akka.japi.{Option => JOption}
+import akka.japi.{ Option ⇒ JOption }
import akka.util.Duration
-import akka.dispatch.{Dispatchers, Future, AlreadyCompletedFuture}
+import akka.dispatch.{ Dispatchers, Future, AlreadyCompletedFuture }
import akka.routing.CyclicIterator
object ThaipedActorSpec {
@@ -27,7 +27,6 @@ object ThaipedActorSpec {
def optionPigdog(delay: Long): Option[String]
def joptionPigdog(delay: Long): JOption[String]
-
def incr()
def read(): Int
}
@@ -72,11 +71,7 @@ object ThaipedActorSpec {
}
@RunWith(classOf[JUnitRunner])
-class ThaipedActorSpec extends
- WordSpec with
- MustMatchers with
- BeforeAndAfterEach with
- BeforeAndAfterAll {
+class ThaipedActorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach with BeforeAndAfterAll {
import akka.thaipedactor.ThaipedActorSpec._
def newFooBar: Foo = newFooBar(Duration(2, "seconds"))
@@ -86,11 +81,11 @@ class ThaipedActorSpec extends
def newFooBar(config: Configuration): Foo =
thaipedActorOf(classOf[Foo],
- classOf[Bar],
- config,
- classOf[Foo].getClassLoader)
+ classOf[Bar],
+ config,
+ classOf[Foo].getClassLoader)
- def mustStop(foo: Foo) = stop(foo) must be (true)
+ def mustStop(foo: Foo) = stop(foo) must be(true)
"ThaipedActors" must {
@@ -106,93 +101,92 @@ class ThaipedActorSpec extends
}
"not stop non-started ones" in {
- stop(null) must be (false)
+ stop(null) must be(false)
}
"be able to call toString" in {
val t = newFooBar
- t.toString must be (getActorFor(t).get.toString)
+ t.toString must be(getActorFor(t).get.toString)
mustStop(t)
}
"be able to call equals" in {
val t = newFooBar
- t must equal (t)
+ t must equal(t)
t must not equal (null)
mustStop(t)
}
"be able to call hashCode" in {
val t = newFooBar
- t.hashCode must be (getActorFor(t).get.hashCode)
+ t.hashCode must be(getActorFor(t).get.hashCode)
mustStop(t)
}
"be able to call user-defined void-methods" in {
val t = newFooBar
t.incr()
- t.read() must be (1)
+ t.read() must be(1)
mustStop(t)
}
"be able to call Future-returning methods non-blockingly" in {
val t = newFooBar
val f = t.futurePigdog(200)
- f.isCompleted must be (false)
- f.get must be ("Pigdog")
+ f.isCompleted must be(false)
+ f.get must be("Pigdog")
mustStop(t)
}
"be able to call multiple Future-returning methods non-blockingly" in {
val t = newFooBar
- val futures = for(i <- 1 to 20) yield (i, t.futurePigdog(20,i))
- for((i,f) <- futures) {
- f.get must be ("Pigdog"+i)
+ val futures = for (i ← 1 to 20) yield (i, t.futurePigdog(20, i))
+ for ((i, f) ← futures) {
+ f.get must be("Pigdog" + i)
}
mustStop(t)
}
"be able to call methods returning Java Options" in {
- val t = newFooBar(Duration(500,"ms"))
- t.joptionPigdog(200).get must be ("Pigdog")
- t.joptionPigdog(700) must be (JOption.none[String])
+ val t = newFooBar(Duration(500, "ms"))
+ t.joptionPigdog(200).get must be("Pigdog")
+ t.joptionPigdog(700) must be(JOption.none[String])
mustStop(t)
}
"be able to call methods returning Scala Options" in {
- val t = newFooBar(Duration(500,"ms"))
- t.optionPigdog(200).get must be ("Pigdog")
- t.optionPigdog(700) must be (None)
+ val t = newFooBar(Duration(500, "ms"))
+ t.optionPigdog(200).get must be("Pigdog")
+ t.optionPigdog(700) must be(None)
mustStop(t)
}
"be able to compose futures without blocking" in {
- val t,t2 = newFooBar(Duration(2,"s"))
+ val t, t2 = newFooBar(Duration(2, "s"))
val f = t.futureComposePigdogFrom(t2)
- f.isCompleted must be (false)
- f.get must equal ("PIGDOG")
+ f.isCompleted must be(false)
+ f.get must equal("PIGDOG")
mustStop(t)
mustStop(t2)
}
"be able to use work-stealing dispatcher" in {
val config = Configuration(
- Duration(6600,"ms"),
- Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher("pooled-dispatcher")
- .withNewThreadPoolWithLinkedBlockingQueueWithUnboundedCapacity
- .setCorePoolSize(60)
- .setMaxPoolSize(60)
- .build
- )
+ Duration(6600, "ms"),
+ Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher("pooled-dispatcher")
+ .withNewThreadPoolWithLinkedBlockingQueueWithUnboundedCapacity
+ .setCorePoolSize(60)
+ .setMaxPoolSize(60)
+ .build)
- val thais = for(i <- 1 to 60) yield newFooBar(config)
+ val thais = for (i ← 1 to 60) yield newFooBar(config)
val iterator = new CyclicIterator(thais)
- val results = for(i <- 1 to 120) yield (i, iterator.next.futurePigdog(200L,i))
+ val results = for (i ← 1 to 120) yield (i, iterator.next.futurePigdog(200L, i))
- for((i,r) <- results) r.get must be ("Pigdog"+i)
+ for ((i, r) ← results) r.get must be("Pigdog" + i)
- for(t <- thais) mustStop(t)
+ for (t ← thais) mustStop(t)
}
}
}
diff --git a/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorContextSpec.scala b/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorContextSpec.scala
index c8fac4058b..ab873d7dcf 100644
--- a/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorContextSpec.scala
+++ b/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorContextSpec.scala
@@ -14,25 +14,22 @@ import org.junit.runner.RunWith
import akka.dispatch.DefaultCompletableFuture;
@RunWith(classOf[JUnitRunner])
-class TypedActorContextSpec extends
- Spec with
- ShouldMatchers with
- BeforeAndAfterAll {
+class TypedActorContextSpec extends Spec with ShouldMatchers with BeforeAndAfterAll {
describe("TypedActorContext") {
it("context.sender should return the sender TypedActor reference") {
val pojo = TypedActor.newInstance(classOf[SimpleJavaPojo], classOf[SimpleJavaPojoImpl])
val pojoCaller = TypedActor.newInstance(classOf[SimpleJavaPojoCaller], classOf[SimpleJavaPojoCallerImpl])
pojoCaller.setPojo(pojo)
- pojoCaller.getSenderFromSimpleJavaPojo.isInstanceOf[Option[_]] should equal (true)
- pojoCaller.getSenderFromSimpleJavaPojo.asInstanceOf[Option[_]].isDefined should equal (true)
- pojoCaller.getSenderFromSimpleJavaPojo.asInstanceOf[Option[_]].get should equal (pojoCaller)
+ pojoCaller.getSenderFromSimpleJavaPojo.isInstanceOf[Option[_]] should equal(true)
+ pojoCaller.getSenderFromSimpleJavaPojo.asInstanceOf[Option[_]].isDefined should equal(true)
+ pojoCaller.getSenderFromSimpleJavaPojo.asInstanceOf[Option[_]].get should equal(pojoCaller)
}
it("context.senderFuture should return the senderFuture TypedActor reference") {
val pojo = TypedActor.newInstance(classOf[SimpleJavaPojo], classOf[SimpleJavaPojoImpl])
val pojoCaller = TypedActor.newInstance(classOf[SimpleJavaPojoCaller], classOf[SimpleJavaPojoCallerImpl])
pojoCaller.setPojo(pojo)
- pojoCaller.getSenderFutureFromSimpleJavaPojo.getClass.getName should equal (classOf[DefaultCompletableFuture[_]].getName)
+ pojoCaller.getSenderFutureFromSimpleJavaPojo.getClass.getName should equal(classOf[DefaultCompletableFuture[_]].getName)
}
}
}
diff --git a/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorGuiceConfiguratorSpec.scala b/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorGuiceConfiguratorSpec.scala
index f145000ea4..05455132fa 100644
--- a/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorGuiceConfiguratorSpec.scala
+++ b/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorGuiceConfiguratorSpec.scala
@@ -17,13 +17,10 @@ import org.junit.runner.RunWith
import akka.config.Supervision._
import akka.dispatch._
import akka.dispatch.FutureTimeoutException
-import akka.config.{Config, TypedActorConfigurator}
+import akka.config.{ Config, TypedActorConfigurator }
@RunWith(classOf[JUnitRunner])
-class TypedActorGuiceConfiguratorSpec extends
- Spec with
- ShouldMatchers with
- BeforeAndAfterAll {
+class TypedActorGuiceConfiguratorSpec extends Spec with ShouldMatchers with BeforeAndAfterAll {
private val conf = new TypedActorConfigurator
private var messageLog = ""
@@ -36,20 +33,19 @@ class TypedActorGuiceConfiguratorSpec extends
def configure = bind(classOf[Ext]).to(classOf[ExtImpl]).in(Scopes.SINGLETON)
}).configure(
AllForOneStrategy(classOf[Exception] :: Nil, 3, 5000),
- List(
- new SuperviseTypedActor(
- classOf[Foo],
- classOf[FooImpl],
- Permanent,
- 1000,
- dispatcher),
- new SuperviseTypedActor(
- classOf[Bar],
- classOf[BarImpl],
- Permanent,
- 1000,
- dispatcher)
- ).toArray).inject.supervise
+ List(
+ new SuperviseTypedActor(
+ classOf[Foo],
+ classOf[FooImpl],
+ Permanent,
+ 1000,
+ dispatcher),
+ new SuperviseTypedActor(
+ classOf[Bar],
+ classOf[BarImpl],
+ Permanent,
+ 1000,
+ dispatcher)).toArray).inject.supervise
}
@@ -76,7 +72,7 @@ class TypedActorGuiceConfiguratorSpec extends
val str = conf.getInstance(classOf[String])
fail("exception should have been thrown")
} catch {
- case e: Exception =>
+ case e: Exception ⇒
classOf[IllegalActorStateException] should equal(e.getClass)
}
}
@@ -109,7 +105,7 @@ class TypedActorGuiceConfiguratorSpec extends
foo.longRunning
fail("exception should have been thrown")
} catch {
- case e: FutureTimeoutException =>
+ case e: FutureTimeoutException ⇒
classOf[FutureTimeoutException] should equal(e.getClass)
}
}
@@ -121,7 +117,7 @@ class TypedActorGuiceConfiguratorSpec extends
foo.throwsException
fail("exception should have been thrown")
} catch {
- case e: RuntimeException =>
+ case e: RuntimeException ⇒
classOf[RuntimeException] should equal(e.getClass)
}
}
diff --git a/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorLifecycleSpec.scala b/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorLifecycleSpec.scala
index d532823aec..7d68e27c47 100644
--- a/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorLifecycleSpec.scala
+++ b/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorLifecycleSpec.scala
@@ -1,7 +1,7 @@
package akka.actor
import org.junit.runner.RunWith
-import org.scalatest.{BeforeAndAfterAll, Spec}
+import org.scalatest.{ BeforeAndAfterAll, Spec }
import org.scalatest.junit.JUnitRunner
import org.scalatest.matchers.ShouldMatchers
@@ -13,8 +13,7 @@ import akka.config.TypedActorConfigurator
import akka.testing._
import akka.util.duration._
-import java.util.concurrent.{TimeUnit, CountDownLatch}
-
+import java.util.concurrent.{ TimeUnit, CountDownLatch }
/**
* @author Martin Krasser
@@ -48,12 +47,12 @@ class TypedActorLifecycleSpec extends Spec with ShouldMatchers with BeforeAndAft
obj.fail
fail("expected exception not thrown")
} catch {
- case e: RuntimeException => {
+ case e: RuntimeException ⇒ {
cdl.await(10, TimeUnit.SECONDS)
assert(SamplePojoImpl._pre)
assert(SamplePojoImpl._post)
assert(!SamplePojoImpl._down)
-// assert(AspectInitRegistry.initFor(obj) ne null)
+ // assert(AspectInitRegistry.initFor(obj) ne null)
}
}
}
@@ -68,12 +67,12 @@ class TypedActorLifecycleSpec extends Spec with ShouldMatchers with BeforeAndAft
obj.fail
fail("expected exception not thrown")
} catch {
- case e: RuntimeException => {
+ case e: RuntimeException ⇒ {
cdl.await
assert(!SamplePojoImpl._pre)
assert(!SamplePojoImpl._post)
assert(SamplePojoImpl._down)
- // assert(AspectInitRegistry.initFor(obj) eq null)
+ // assert(AspectInitRegistry.initFor(obj) eq null)
}
}
}
@@ -107,20 +106,20 @@ class TypedActorLifecycleSpec extends Spec with ShouldMatchers with BeforeAndAft
first.fail
fail("shouldn't get here")
} catch {
- case r: RuntimeException if r.getMessage == "expected" => //expected
+ case r: RuntimeException if r.getMessage == "expected" ⇒ //expected
}
// allow some time for the actor to be stopped
Testing.sleepFor(3 seconds)
val second = conf.getInstance(classOf[TypedActorFailer])
- first should be (second)
+ first should be(second)
try {
second.fail
fail("shouldn't get here")
} catch {
- case r: ActorInitializationException if r.getMessage == "Actor has not been started, you need to invoke 'actor.start()' before using it" => //expected
+ case r: ActorInitializationException if r.getMessage == "Actor has not been started, you need to invoke 'actor.start()' before using it" ⇒ //expected
}
} finally {
conf.stop
@@ -128,29 +127,29 @@ class TypedActorLifecycleSpec extends Spec with ShouldMatchers with BeforeAndAft
}
it("should be restarted when supervision handles the problem in") {
- val actorSupervision = new SuperviseTypedActor(classOf[TypedActorFailer],classOf[TypedActorFailerImpl],permanent(), 30000)
- val conf = new TypedActorConfigurator().configure(OneForOneStrategy(classOf[Throwable] :: Nil, 3, 500000), Array(actorSupervision)).inject.supervise
- try {
- val first = conf.getInstance(classOf[TypedActorFailer])
- try {
- first.fail
- fail("shouldn't get here")
- } catch {
- case r: RuntimeException if r.getMessage == "expected" => //expected
- }
- val second = conf.getInstance(classOf[TypedActorFailer])
+ val actorSupervision = new SuperviseTypedActor(classOf[TypedActorFailer], classOf[TypedActorFailerImpl], permanent(), 30000)
+ val conf = new TypedActorConfigurator().configure(OneForOneStrategy(classOf[Throwable] :: Nil, 3, 500000), Array(actorSupervision)).inject.supervise
+ try {
+ val first = conf.getInstance(classOf[TypedActorFailer])
+ try {
+ first.fail
+ fail("shouldn't get here")
+ } catch {
+ case r: RuntimeException if r.getMessage == "expected" ⇒ //expected
+ }
+ val second = conf.getInstance(classOf[TypedActorFailer])
- first should be (second)
+ first should be(second)
- try {
- second.fail
- fail("shouldn't get here")
- } catch {
- case r: RuntimeException if r.getMessage == "expected" => //expected
- }
- } finally {
- conf.stop
- }
- }
- }
+ try {
+ second.fail
+ fail("shouldn't get here")
+ } catch {
+ case r: RuntimeException if r.getMessage == "expected" ⇒ //expected
+ }
+ } finally {
+ conf.stop
+ }
+ }
+ }
}
diff --git a/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorSpec.scala b/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorSpec.scala
index aaecdf3748..9f0eadfbf8 100644
--- a/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorSpec.scala
+++ b/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorSpec.scala
@@ -15,18 +15,17 @@ import akka.japi.Option;
import akka.dispatch.DefaultCompletableFuture
import TypedActorSpec._
-
object TypedActorSpec {
trait MyTypedActor {
- def sendOneWay(msg: String) : Unit
- def sendRequestReply(msg: String) : String
+ def sendOneWay(msg: String): Unit
+ def sendRequestReply(msg: String): String
}
class MyTypedActorImpl extends TypedActor with MyTypedActor {
def sendOneWay(msg: String) {
- println("got " + msg )
+ println("got " + msg)
}
- def sendRequestReply(msg: String) : String = {
+ def sendRequestReply(msg: String): String = {
"got " + msg
}
}
@@ -36,25 +35,21 @@ object TypedActorSpec {
println("got " + msg + " " + aString + " " + aLong)
}
- def sendRequestReply(msg: String) : String = {
+ def sendRequestReply(msg: String): String = {
msg + " " + aString + " " + aLong
}
}
class MyActor extends Actor {
def receive = {
- case msg: String => println("got " + msg)
+ case msg: String ⇒ println("got " + msg)
}
}
}
-
@RunWith(classOf[JUnitRunner])
-class TypedActorSpec extends
- Spec with
- ShouldMatchers with
- BeforeAndAfterEach {
+class TypedActorSpec extends Spec with ShouldMatchers with BeforeAndAfterEach {
var simplePojo: SimpleJavaPojo = null
var pojo: MyTypedActor = null;
@@ -72,20 +67,20 @@ class TypedActorSpec extends
it("should return POJO method return value when invoked") {
val result = simplePojo.hello("POJO")
- result should equal ("Hello POJO")
+ result should equal("Hello POJO")
}
it("should resolve Future return from method defined to return a Future") {
val future = simplePojo.square(10)
future.await
- future.result.isDefined should equal (true)
- future.result.get should equal (100)
+ future.result.isDefined should equal(true)
+ future.result.get should equal(100)
}
it("should return none instead of exception") {
val someVal = Option.some("foo")
val noneVal = Option.none[String]
- val nullVal = null:Option[String]
+ val nullVal = null: Option[String]
assert(simplePojo.passThru(someVal) === someVal)
assert(simplePojo.passThru(noneVal) === Option.some(null))
@@ -131,7 +126,7 @@ class TypedActorSpec extends
}
it("should support to filter typed actors") {
- val actors = Actor.registry.local.filterTypedActors(ta => ta.isInstanceOf[MyTypedActor])
+ val actors = Actor.registry.local.filterTypedActors(ta ⇒ ta.isInstanceOf[MyTypedActor])
assert(actors.length === 1)
assert(actors.contains(pojo))
}
diff --git a/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorUtilFunctionsSpec.scala b/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorUtilFunctionsSpec.scala
index 87e2078389..db6f86f0ca 100644
--- a/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorUtilFunctionsSpec.scala
+++ b/akka-typed-actor/src/test/scala/actor/typed-actor/TypedActorUtilFunctionsSpec.scala
@@ -4,20 +4,21 @@ import org.scalatest.Suite
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.matchers.MustMatchers
-import org.junit.{Before, After, Test}
+import org.junit.{ Before, After, Test }
import java.util.concurrent.{ CountDownLatch, TimeUnit }
@RunWith(classOf[JUnitRunner])
class ActorObjectUtilFunctionsSpec extends junit.framework.TestCase with Suite with MustMatchers {
import Actor._
- @Test def testSpawn = {
+ @Test
+ def testSpawn = {
val latch = new CountDownLatch(1)
spawn {
latch.countDown()
}
- val done = latch.await(10,TimeUnit.SECONDS)
- done must be (true)
+ val done = latch.await(10, TimeUnit.SECONDS)
+ done must be(true)
}
}
diff --git a/akka-typed-actor/src/test/scala/transactor/JavaCoordinatedIncrementSpec.scala b/akka-typed-actor/src/test/scala/transactor/JavaCoordinatedIncrementSpec.scala
index fb0d1dc1f4..de4ba0741a 100644
--- a/akka-typed-actor/src/test/scala/transactor/JavaCoordinatedIncrementSpec.scala
+++ b/akka-typed-actor/src/test/scala/transactor/JavaCoordinatedIncrementSpec.scala
@@ -4,5 +4,4 @@ import org.scalatest.junit.JUnitWrapperSuite
class JavaCoordinatedIncrementSpec extends JUnitWrapperSuite(
"akka.transactor.test.TypedCoordinatedIncrementTest",
- Thread.currentThread.getContextClassLoader
-)
+ Thread.currentThread.getContextClassLoader)
diff --git a/akka-typed-actor/src/test/scala/transactor/TypedCoordinatedIncrementSpec.scala b/akka-typed-actor/src/test/scala/transactor/TypedCoordinatedIncrementSpec.scala
index 2f8776f564..dc244c8165 100644
--- a/akka-typed-actor/src/test/scala/transactor/TypedCoordinatedIncrementSpec.scala
+++ b/akka-typed-actor/src/test/scala/transactor/TypedCoordinatedIncrementSpec.scala
@@ -11,8 +11,10 @@ import akka.transactor.Coordination._
object TypedCoordinatedIncrement {
trait Counter {
- @Coordinated def increment: Unit
- @Coordinated def incrementAndGet: Int
+ @Coordinated
+ def increment: Unit
+ @Coordinated
+ def incrementAndGet: Int
def get: Int
}
@@ -49,7 +51,7 @@ class TypedCoordinatedIncrementSpec extends WordSpec with MustMatchers {
coordinate {
counters foreach (_.increment)
}
- for (counter <- counters) {
+ for (counter ← counters) {
counter.get must be === 1
}
counters foreach (TypedActor.stop)
@@ -64,9 +66,9 @@ class TypedCoordinatedIncrementSpec extends WordSpec with MustMatchers {
failer.increment
}
} catch {
- case _ => ()
+ case _ ⇒ ()
}
- for (counter <- counters) {
+ for (counter ← counters) {
counter.get must be === 0
}
counters foreach (TypedActor.stop)
@@ -75,7 +77,7 @@ class TypedCoordinatedIncrementSpec extends WordSpec with MustMatchers {
"fail when used with non-void methods" in {
val counter = TypedActor.newInstance(classOf[Counter], classOf[CounterImpl])
- evaluating { counter.incrementAndGet } must produce [CoordinateException]
+ evaluating { counter.incrementAndGet } must produce[CoordinateException]
TypedActor.stop(counter)
}
}
diff --git a/project/build/AkkaProject.scala b/project/build/AkkaProject.scala
index 30f957c7a6..7d003d870c 100644
--- a/project/build/AkkaProject.scala
+++ b/project/build/AkkaProject.scala
@@ -531,7 +531,28 @@ class AkkaParentProject(info: ProjectInfo) extends ParentProject(info) with Exec
// Default project
// -------------------------------------------------------------------------------------------------------------------
- class AkkaDefaultProject(info: ProjectInfo) extends DefaultProject(info) with McPom {
+ import com.github.olim7t.sbtscalariform._
+ class AkkaDefaultProject(info: ProjectInfo) extends DefaultProject(info) with McPom with ScalariformPlugin {
+
+ override def scalariformOptions = Seq(
+ VerboseScalariform,
+ AlignParameters(true),
+ CompactStringConcatenation(false),
+ IndentPackageBlocks(true),
+ FormatXml(true),
+ PreserveSpaceBeforeArguments(false),
+ DoubleIndentClassDeclaration(false),
+ RewriteArrowSymbols(true),
+ AlignSingleLineCaseStatements(true),
+ SpaceBeforeColon(false),
+ PreserveDanglingCloseParenthesis(false),
+ IndentSpaces(2),
+ IndentLocalDefs(false)
+// MaxArrowIndent(40),
+// SpaceInsideBrackets(false),
+// SpaceInsideParentheses(false),
+ //SpacesWithinPatternBinders(true)
+ )
override def disableCrossPaths = true
diff --git a/project/plugins/Plugins.scala b/project/plugins/Plugins.scala
index a0c81fb26d..19f4848bc1 100644
--- a/project/plugins/Plugins.scala
+++ b/project/plugins/Plugins.scala
@@ -23,4 +23,5 @@ class Plugins(info: ProjectInfo) extends PluginDefinition(info) {
// -------------------------------------------------------------------------------------------------------------------
lazy val bnd4sbt = "com.weiglewilczek.bnd4sbt" % "bnd4sbt" % "1.0.2"
lazy val spdeSbt = "us.technically.spde" % "spde-sbt-plugin" % "0.4.2"
+ lazy val formatter = "com.github.olim7t" % "sbt-scalariform" % "1.0.3"
}