diff --git a/akka-actor-tests/src/main/scala/akka/testing/Serializers.scala b/akka-actor-tests/src/main/scala/akka/testing/Serializers.scala new file mode 100644 index 0000000000..0a7aa8fb7b --- /dev/null +++ b/akka-actor-tests/src/main/scala/akka/testing/Serializers.scala @@ -0,0 +1,69 @@ +/** + * Copyright (C) 2009-2011 Scalable Solutions AB + */ + +package akka.testing + +import akka.serialization.Serializer +import com.google.protobuf.Message +import org.codehaus.jackson.map.ObjectMapper +import java.io.{ ObjectOutputStream, ByteArrayOutputStream, ObjectInputStream, ByteArrayInputStream } +import akka.util.ClassLoaderObjectInputStream +import sjson.json._ + +class ProtobufSerializer extends Serializer { + val ARRAY_OF_BYTE_ARRAY = Array[Class[_]](classOf[Array[Byte]]) + + def toBinary(obj: AnyRef): Array[Byte] = { + if (!obj.isInstanceOf[Message]) throw new IllegalArgumentException( + "Can't serialize a non-protobuf message using protobuf [" + obj + "]") + obj.asInstanceOf[Message].toByteArray + } + + def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]], classLoader: Option[ClassLoader] = None): AnyRef = { + if (!clazz.isDefined) throw new IllegalArgumentException( + "Need a protobuf message class to be able to serialize bytes using protobuf") + clazz.get.getDeclaredMethod("parseFrom", ARRAY_OF_BYTE_ARRAY: _*).invoke(null, bytes).asInstanceOf[Message] + } +} +object ProtobufSerializer extends ProtobufSerializer + +class JavaJSONSerializer extends Serializer { + private val mapper = new ObjectMapper + + def toBinary(obj: AnyRef): Array[Byte] = { + val bos = new ByteArrayOutputStream + val out = new ObjectOutputStream(bos) + mapper.writeValue(out, obj) + out.close + bos.toByteArray + } + + def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]], classLoader: Option[ClassLoader] = None): AnyRef = { + if (!clazz.isDefined) throw new IllegalArgumentException( + "Can't deserialize JSON to instance if no class is provided") + val in = + if (classLoader.isDefined) new ClassLoaderObjectInputStream(classLoader.get, new ByteArrayInputStream(bytes)) + else new ObjectInputStream(new ByteArrayInputStream(bytes)) + val obj = mapper.readValue(in, clazz.get).asInstanceOf[AnyRef] + in.close + obj + } +} +object JavaJSONSerializer extends JavaJSONSerializer + +class SJSONSerializer extends Serializer { + + def toBinary(obj: AnyRef): Array[Byte] = + sjson.json.Serializer.SJSON.out(obj) + + def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]], cl: Option[ClassLoader] = None): AnyRef = { + if (!clazz.isDefined) throw new IllegalArgumentException( + "Can't deserialize JSON to instance if no class is provided") + + import sjson.json.Serializer._ + val sj = new SJSON with DefaultConstructor { val classLoader = cl } + sj.in(bytes, clazz.get.getName) + } +} +object SJSONSerializer extends SJSONSerializer 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 dd0cb87990..3f2f8e57db 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 @@ -23,7 +23,7 @@ object ActorFireForgetRequestReplySpec { case "Send" ⇒ self.reply("Reply") case "SendImplicit" ⇒ - self.sender.get ! "ReplyImplicit" + self.channel ! "ReplyImplicit" } } 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 944e334712..dcd58763d0 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 @@ -11,9 +11,10 @@ import akka.testing._ import akka.util.duration._ import akka.testing.Testing.sleepFor import akka.config.Supervision.{ OneForOneStrategy } -import akka.actor._ import akka.dispatch.Future import java.util.concurrent.{ TimeUnit, CountDownLatch } +import java.lang.IllegalStateException +import akka.util.ReflectiveAccess object ActorRefSpec { @@ -68,26 +69,189 @@ object ActorRefSpec { } } } + + class OuterActor(val inner: ActorRef) extends Actor { + def receive = { + case "self" ⇒ self reply self + case x ⇒ inner forward x + } + } + + class FailingOuterActor(val inner: ActorRef) extends Actor { + val fail = new InnerActor + + def receive = { + case "self" ⇒ self reply self + case x ⇒ inner forward x + } + } + + class FailingInheritingOuterActor(_inner: ActorRef) extends OuterActor(_inner) { + val fail = new InnerActor + } + + class InnerActor extends Actor { + def receive = { + case "innerself" ⇒ self reply self + case other ⇒ self reply other + } + } + + class FailingInnerActor extends Actor { + val fail = new InnerActor + + def receive = { + case "innerself" ⇒ self reply self + case other ⇒ self reply other + } + } + + class FailingInheritingInnerActor extends InnerActor { + val fail = new InnerActor + } } class ActorRefSpec extends WordSpec with MustMatchers { - import ActorRefSpec._ + import akka.actor.ActorRefSpec._ "An ActorRef" must { "not allow Actors to be created outside of an actorOf" in { intercept[akka.actor.ActorInitializationException] { new Actor { def receive = { case _ ⇒ } } - fail("shouldn't get here") } intercept[akka.actor.ActorInitializationException] { - val a = Actor.actorOf(new Actor { + Actor.actorOf(new Actor { val nested = new Actor { def receive = { case _ ⇒ } } def receive = { case _ ⇒ } }).start() - fail("shouldn't get here") } + + def refStackMustBeEmpty = Actor.actorRefInCreation.get.headOption must be === None + + refStackMustBeEmpty + + intercept[akka.actor.ActorInitializationException] { + Actor.actorOf(new FailingOuterActor(Actor.actorOf(new InnerActor).start)).start() + } + + refStackMustBeEmpty + + intercept[akka.actor.ActorInitializationException] { + Actor.actorOf(new OuterActor(Actor.actorOf(new FailingInnerActor).start)).start() + } + + refStackMustBeEmpty + + intercept[akka.actor.ActorInitializationException] { + Actor.actorOf(new FailingInheritingOuterActor(Actor.actorOf(new InnerActor).start)).start() + } + + refStackMustBeEmpty + + intercept[akka.actor.ActorInitializationException] { + Actor.actorOf(new FailingOuterActor(Actor.actorOf(new FailingInheritingInnerActor).start)).start() + } + + refStackMustBeEmpty + + intercept[akka.actor.ActorInitializationException] { + Actor.actorOf(new FailingInheritingOuterActor(Actor.actorOf(new FailingInheritingInnerActor).start)).start() + } + + refStackMustBeEmpty + + intercept[akka.actor.ActorInitializationException] { + Actor.actorOf(new FailingInheritingOuterActor(Actor.actorOf(new FailingInnerActor).start)).start() + } + + refStackMustBeEmpty + + intercept[akka.actor.ActorInitializationException] { + Actor.actorOf(new OuterActor(Actor.actorOf(new InnerActor { + val a = new InnerActor + }).start)).start() + } + + refStackMustBeEmpty + + intercept[akka.actor.ActorInitializationException] { + Actor.actorOf(new FailingOuterActor(Actor.actorOf(new FailingInheritingInnerActor).start)).start() + } + + refStackMustBeEmpty + + intercept[akka.actor.ActorInitializationException] { + Actor.actorOf(new OuterActor(Actor.actorOf(new FailingInheritingInnerActor).start)).start() + } + + refStackMustBeEmpty + + intercept[akka.actor.ActorInitializationException] { + Actor.actorOf(new OuterActor(Actor.actorOf({ new InnerActor; new InnerActor }).start)).start() + } + + refStackMustBeEmpty + + (intercept[java.lang.IllegalStateException] { + Actor.actorOf(new OuterActor(Actor.actorOf({ throw new IllegalStateException("Ur state be b0rked"); new InnerActor }).start)).start() + }).getMessage must be === "Ur state be b0rked" + + refStackMustBeEmpty + } + + "be serializable using Java Serialization on local node" in { + val a = Actor.actorOf[InnerActor].start + + import java.io._ + + val baos = new ByteArrayOutputStream(8192 * 32) + val out = new ObjectOutputStream(baos) + + out.writeObject(a) + + out.flush + out.close + + val in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray)) + val readA = in.readObject + + a.isInstanceOf[LocalActorRef] must be === true + readA.isInstanceOf[LocalActorRef] must be === true + (readA eq a) must be === true + } + + "must throw exception on deserialize if not present in local registry and remoting is not enabled" in { + ReflectiveAccess.RemoteModule.isEnabled must be === false + + val a = Actor.actorOf[InnerActor].start + + val inetAddress = ReflectiveAccess.RemoteModule.configDefaultAddress + + val expectedSerializedRepresentation = SerializedActorRef( + a.uuid, + a.address, + inetAddress.getAddress.getHostAddress, + inetAddress.getPort, + a.timeout) + + Actor.registry.unregister(a) + + import java.io._ + + val baos = new ByteArrayOutputStream(8192 * 32) + val out = new ObjectOutputStream(baos) + + out.writeObject(a) + + out.flush + out.close + + val in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray)) + (intercept[java.lang.IllegalStateException] { + in.readObject + }).getMessage must be === "Trying to deserialize ActorRef (" + expectedSerializedRepresentation + ") but it's not found in the local registry and remoting is not enabled!" } "support nested actorOfs" in { @@ -96,12 +260,23 @@ class ActorRefSpec extends WordSpec with MustMatchers { def receive = { case _ ⇒ self reply nested } }).start() - val nested = (a !! "any").get.asInstanceOf[ActorRef] + val nested = (a ? "any").as[ActorRef].get a must not be null nested must not be null (a ne nested) must be === true } + "support advanced nested actorOfs" in { + val a = Actor.actorOf(new OuterActor(Actor.actorOf(new InnerActor).start)).start + val inner = (a ? "innerself").as[Any].get + + (a ? a).as[ActorRef].get must be(a) + (a ? "self").as[ActorRef].get must be(a) + inner must not be a + + (a ? "msg").as[String] must be === Some("msg") + } + "support reply via channel" in { val serverRef = Actor.actorOf[ReplyActor].start() val clientRef = Actor.actorOf(new SenderActor(serverRef)).start() @@ -135,11 +310,11 @@ class ActorRefSpec extends WordSpec with MustMatchers { } }).start() - val ffive: Future[String] = ref !!! 5 - val fnull: Future[String] = ref !!! null + val ffive = (ref ? 5).mapTo[String] + val fnull = (ref ? null).mapTo[String] intercept[ActorKilledException] { - ref !! PoisonPill + (ref ? PoisonPill).get fail("shouldn't get here") } diff --git a/akka-actor-tests/src/test/scala/akka/actor/actor/ActorTimeoutSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/actor/ActorTimeoutSpec.scala new file mode 100644 index 0000000000..707fb8f54c --- /dev/null +++ b/akka-actor-tests/src/test/scala/akka/actor/actor/ActorTimeoutSpec.scala @@ -0,0 +1,53 @@ +/** + * Copyright (C) 2009-2011 Scalable Solutions AB + */ +package akka.actor + +import org.scalatest.{ WordSpec, BeforeAndAfterAll } +import org.scalatest.matchers.MustMatchers +import akka.testkit.TestKit +import akka.dispatch.FutureTimeoutException +import akka.util.duration._ + +class ActorTimeoutSpec + extends WordSpec + with BeforeAndAfterAll + with MustMatchers + with TestKit { + + val echo = Actor.actorOf(new Actor { + def receive = { + case x ⇒ + } + }).start() + + val testTimeout = if (Actor.defaultTimeout.duration < 400.millis) 500 millis else 100 millis + + override def afterAll { echo.stop() } + + "An Actor-based Future" must { + + "use the global default timeout if no implicit in scope" in { + echo.timeout = 12 + within((Actor.TIMEOUT - 100).millis, (Actor.TIMEOUT + 300).millis) { + val f = echo ? "hallo" + intercept[FutureTimeoutException] { f.await } + } + } + + "use implicitly supplied timeout" in { + implicit val timeout = Actor.Timeout(testTimeout) + within(testTimeout - 100.millis, testTimeout + 300.millis) { + val f = (echo ? "hallo").mapTo[String] + intercept[FutureTimeoutException] { f.await } + f.value must be(None) + } + } + + "use explicitly supplied timeout" in { + within(testTimeout - 100.millis, testTimeout + 300.millis) { + (echo.?("hallo", testTimeout)).as[String] must be(None) + } + } + } +} 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 258809c5b6..315798cc19 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 @@ -102,7 +102,7 @@ object Chameneos { } } else { waitingChameneo.foreach(_ ! Exit) - self.sender.get ! Exit + self.channel ! Exit } } } 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 bd56a79a8e..15316f727d 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 @@ -22,7 +22,9 @@ class DeployerSpec extends WordSpec with MustMatchers { Clustered( Node("node1"), Replicate(3), - Stateless)))) + Replication( + TransactionLog, + WriteThrough))))) } } } 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 2c6773bc1c..eea3355b74 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 @@ -50,10 +50,7 @@ object ForwardActorSpec { val latch = TestLatch() val forwardActor = actorOf[ForwardActor] forwardActor.start() - (forwardActor !! "SendBangBang") match { - case Some(_) ⇒ latch.countDown() - case None ⇒ {} - } + forwardActor ? "SendBangBang" onComplete { _ ⇒ latch.countDown() } def receive = { case _ ⇒ {} } 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 e2aa812e34..8c5f397387 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 @@ -66,7 +66,7 @@ object SupervisorSpec { } override def receive = { - case Die ⇒ temp !! (Die, TimeoutMillis) + case Die ⇒ (temp.?(Die, TimeoutMillis)).get } } @@ -200,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)).as[String].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 { @@ -215,7 +215,7 @@ class SupervisorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach val master = actorOf[Master].start() intercept[RuntimeException] { - master !! (Die, TimeoutMillis) + (master.?(Die, TimeoutMillis)).get } sleepFor(1 second) @@ -226,7 +226,7 @@ class SupervisorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach val (temporaryActor, supervisor) = temporaryActorAllForOne intercept[RuntimeException] { - temporaryActor !! (Die, TimeoutMillis) + (temporaryActor.?(Die, TimeoutMillis)).get } sleepFor(1 second) @@ -374,13 +374,13 @@ class SupervisorSpec extends WordSpec with MustMatchers with BeforeAndAfterEach Supervise(dyingActor, Permanent) :: Nil)) intercept[Exception] { - dyingActor !! (Die, TimeoutMillis) + (dyingActor.?(Die, TimeoutMillis)).get } // give time for restart sleepFor(3 seconds) - (dyingActor !! (Ping, TimeoutMillis)).getOrElse("nil") must be(PongMessage) + (dyingActor.?(Ping, TimeoutMillis)).as[String].getOrElse("nil") must be === PongMessage inits.get must be(3) diff --git a/akka-actor-tests/src/test/scala/akka/config/ConfigSpec.scala b/akka-actor-tests/src/test/scala/akka/config/ConfigSpec.scala index 66d21435f4..594d0ad811 100644 --- a/akka-actor-tests/src/test/scala/akka/config/ConfigSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/config/ConfigSpec.scala @@ -37,9 +37,8 @@ class ConfigSpec extends WordSpec with MustMatchers { getInt("akka.actor.throughput") must equal(Some(5)) getInt("akka.actor.throughput-deadline-time") must equal(Some(-1)) - getString("akka.remote.layer") must equal(Some("akka.remote.netty.NettyRemoteSupport")) - getString("akka.remote.server.hostname") must equal(Some("localhost")) - getInt("akka.remote.server.port") must equal(Some(2552)) + getString("akka.cluster.layer") must equal(Some("akka.remote.netty.NettyRemoteSupport")) + getInt("akka.cluster.server.port") must equal(Some(2552)) } } } 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 97dc67da22..a6e24302f6 100644 --- a/akka-actor-tests/src/test/scala/akka/dispatch/ActorModelSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/dispatch/ActorModelSpec.scala @@ -8,13 +8,13 @@ import org.junit.Test import org.scalatest.Assertions._ import akka.testing._ import akka.dispatch._ -import akka.actor.{ ActorRef, Actor } import akka.actor.Actor._ import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.{ ConcurrentHashMap, CountDownLatch, TimeUnit } import akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor import akka.util.{ Duration, Switch } import org.multiverse.api.latches.StandardLatch +import akka.actor.{ ActorKilledException, PoisonPill, ActorRef, Actor } object ActorModelSpec { @@ -342,6 +342,22 @@ abstract class ActorModelSpec extends JUnitSuite { assertDispatcher(dispatcher)(starts = run, stops = run) } } + + @Test + def dispatcherShouldCompleteAllUncompletedSenderFuturesOnDeregister { + implicit val dispatcher = newInterceptedDispatcher + val a = newTestActor.start() + dispatcher.suspend(a) + val f1: Future[String] = a ? Reply("foo") mapTo manifest[String] + val stopped = a ? PoisonPill + val shouldBeCompleted = for (i ← 1 to 10) yield a ? Reply(i) + dispatcher.resume(a) + assert(f1.get === "foo") + stopped.await + for (each ← shouldBeCompleted) + assert(each.exception.get.isInstanceOf[ActorKilledException]) + a.stop() + } } class DispatcherModelTest extends ActorModelSpec { diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenWorkStealingDispatcherSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/BalancingDispatcherSpec.scala similarity index 100% rename from akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenWorkStealingDispatcherSpec.scala rename to akka-actor-tests/src/test/scala/akka/dispatch/BalancingDispatcherSpec.scala diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcherActorSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/DispatcherActorSpec.scala similarity index 95% rename from akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcherActorSpec.scala rename to akka-actor-tests/src/test/scala/akka/dispatch/DispatcherActorSpec.scala index 69fc9ea635..75f984065c 100644 --- a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcherActorSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/dispatch/DispatcherActorSpec.scala @@ -45,7 +45,7 @@ class DispatcherActorSpec extends JUnitSuite { @Test def shouldSendReplySync = { val actor = actorOf[TestActor].start() - val result = (actor !! ("Hello", 10000)).as[String] + val result = (actor.?("Hello", 10000)).as[String] assert("World" === result.get) actor.stop() } @@ -53,8 +53,8 @@ class DispatcherActorSpec extends JUnitSuite { @Test def shouldSendReplyAsync = { val actor = actorOf[TestActor].start() - val result = actor !! "Hello" - assert("World" === result.get.asInstanceOf[String]) + val result = (actor ? "Hello").as[String] + assert("World" === result.get) actor.stop() } @@ -62,7 +62,7 @@ class DispatcherActorSpec extends JUnitSuite { def shouldSendReceiveException = { val actor = actorOf[TestActor].start() try { - actor !! "Failure" + (actor ? "Failure").get fail("Should have thrown an exception") } catch { case e ⇒ diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcherActorsSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/DispatcherActorsSpec.scala similarity index 100% rename from akka-actor-tests/src/test/scala/akka/dispatch/ExecutorBasedEventDrivenDispatcherActorsSpec.scala rename to akka-actor-tests/src/test/scala/akka/dispatch/DispatcherActorsSpec.scala 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 9a52d8f34d..de81074303 100644 --- a/akka-actor-tests/src/test/scala/akka/dispatch/FutureSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/dispatch/FutureSpec.scala @@ -40,7 +40,7 @@ class FutureSpec extends JUnitSuite { def shouldActorReplyResultThroughExplicitFuture { val actor = actorOf[TestActor] actor.start() - val future = actor !!! "Hello" + val future = actor ? "Hello" future.await assert(future.result.isDefined) assert("World" === future.result.get) @@ -51,7 +51,7 @@ class FutureSpec extends JUnitSuite { def shouldActorReplyExceptionThroughExplicitFuture { val actor = actorOf[TestActor] actor.start() - val future = actor !!! "Failure" + val future = actor ? "Failure" future.await assert(future.exception.isDefined) assert("Expected exception; to test fault-tolerance" === future.exception.get.getMessage) @@ -62,22 +62,8 @@ class FutureSpec extends JUnitSuite { 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 future2 = actor1 !!! "Hello" flatMap (actor2 !!! (_: String)) - val future3 = actor1 !!! "Hello" flatMap (actor2 !!! (_: Int)) - assert((future1.get: Any) === "WORLD") - assert((future2.get: Any) === "WORLD") - intercept[ClassCastException] { future3.get } - actor1.stop() - actor2.stop() - } - - @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 future1 = actor1 ? "Hello" flatMap { _ match { case s: String ⇒ actor2 ? s } } + val future2 = actor1 ? "Hello" flatMap { _ match { case i: Int ⇒ actor2 ? i } } assert((future1.get: Any) === "WORLD") intercept[MatchError] { future2.get } actor1.stop() @@ -93,18 +79,18 @@ class FutureSpec extends JUnitSuite { } }).start() - val future0 = actor !!! "Hello" + 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.mapTo[Int] // returns 5 + b: String ← (actor ? a).mapTo[String] // returns "10" + c: String ← (actor ? 7).mapTo[String] // returns "14" } yield b + "-" + c val future2 = for { - a: Int ← future0 - b: Int ← actor !!! a - c: String ← actor !!! 7 + a: Int ← future0.mapTo[Int] + b: Int ← (actor ? a).mapTo[Int] + c: String ← (actor ? 7).mapTo[String] } yield b + "-" + c assert(future1.get === "10-14") @@ -124,15 +110,15 @@ class FutureSpec extends JUnitSuite { }).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") @@ -146,30 +132,30 @@ class FutureSpec extends JUnitSuite { val future2 = future1 map (_ / 0) val future3 = future2 map (_.toString) - val future4 = future1 failure { + val future4 = future1 recover { case e: ArithmeticException ⇒ 0 } map (_.toString) - val future5 = future2 failure { + val future5 = future2 recover { case e: ArithmeticException ⇒ 0 } map (_.toString) - val future6 = future2 failure { + val future6 = future2 recover { case e: MatchError ⇒ 0 } map (_.toString) - val future7 = future3 failure { case e: ArithmeticException ⇒ "You got ERROR" } + val future7 = future3 recover { case e: ArithmeticException ⇒ "You got ERROR" } val actor = actorOf[TestActor].start() - val future8 = actor !!! "Failure" - val future9 = actor !!! "Failure" failure { + val future8 = actor ? "Failure" + val future9 = actor ? "Failure" recover { case e: RuntimeException ⇒ "FAIL!" } - val future10 = actor !!! "Hello" failure { + val future10 = actor ? "Hello" recover { case e: RuntimeException ⇒ "FAIL!" } - val future11 = actor !!! "Failure" failure { case _ ⇒ "Oops!" } + val future11 = actor ? "Failure" recover { case _ ⇒ "Oops!" } assert(future1.get === 5) intercept[ArithmeticException] { future2.get } @@ -194,7 +180,7 @@ class FutureSpec extends JUnitSuite { }).start() } val timeout = 10000 - def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.!!![Int]((idx, idx * 200), timeout) } + def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.?((idx, idx * 200), timeout).mapTo[Int] } assert(Futures.fold(0, timeout)(futures)(_ + _).await.result.get === 45) } @@ -205,7 +191,7 @@ class FutureSpec extends JUnitSuite { 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.!!![Int]((idx, idx * 200), 10000) } + def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.?((idx, idx * 200), 10000).mapTo[Int] } assert(futures.foldLeft(Future(0))((fr, fa) ⇒ for (r ← fr; a ← fa) yield (r + a)).get === 45) } @@ -222,7 +208,7 @@ class FutureSpec extends JUnitSuite { }).start() } val timeout = 10000 - def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.!!![Int]((idx, idx * 100), timeout) } + def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.?((idx, idx * 100), timeout).mapTo[Int] } assert(Futures.fold(0, timeout)(futures)(_ + _).await.exception.get.getMessage === "shouldFoldResultsWithException: expected") } @@ -239,7 +225,7 @@ class FutureSpec extends JUnitSuite { }).start() } val timeout = 10000 - def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.!!![Int]((idx, idx * 200), timeout) } + def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.?((idx, idx * 200), timeout).mapTo[Int] } assert(Futures.reduce(futures, timeout)(_ + _).get === 45) } @@ -256,7 +242,7 @@ class FutureSpec extends JUnitSuite { }).start() } val timeout = 10000 - def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.!!![Int]((idx, idx * 100), timeout) } + def futures = actors.zipWithIndex map { case (actor: ActorRef, idx: Int) ⇒ actor.?((idx, idx * 100), timeout).mapTo[Int] } assert(Futures.reduce(futures, timeout)(_ + _).await.exception.get.getMessage === "shouldFoldResultsWithException: expected") } @@ -269,7 +255,7 @@ class FutureSpec extends JUnitSuite { def receiveShouldExecuteOnComplete { val latch = new StandardLatch val actor = actorOf[TestActor].start() - actor !!! "Hello" receive { case "World" ⇒ latch.open } + actor ? "Hello" onResult { case "World" ⇒ latch.open } assert(latch.tryAwait(5, TimeUnit.SECONDS)) actor.stop() } @@ -285,7 +271,7 @@ class FutureSpec extends JUnitSuite { } }).start() - val oddFutures: List[Future[Int]] = List.fill(100)(oddActor !!! 'GetNext) + val oddFutures = List.fill(100)(oddActor ? 'GetNext mapTo manifest[Int]) assert(Future.sequence(oddFutures).get.sum === 10000) oddActor.stop() @@ -304,13 +290,13 @@ 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") } + f2 onResult { 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 onResult { case _ ⇒ throw new ThrowableTest("current thread receive") } f3.await assert(f3.resultOrException === Some("SUCCESS")) @@ -342,9 +328,9 @@ class FutureSpec extends JUnitSuite { val actor = actorOf[TestActor].start val x = Future("Hello") - val y = x flatMap (actor !!! _) + val y = x flatMap (actor ? _) mapTo manifest[String] - val r = flow(x() + " " + y[String]() + "!") + val r = flow(x() + " " + y() + "!") assert(r.get === "Hello World!") @@ -370,9 +356,9 @@ class FutureSpec extends JUnitSuite { val actor = actorOf[TestActor].start val x = Future(3) - val y = actor !!! "Hello" + val y = (actor ? "Hello").mapTo[Int] - val r = flow(x() + y[Int](), 100) + val r = flow(x() + y(), 100) intercept[ClassCastException](r.get) } @@ -384,7 +370,7 @@ class FutureSpec extends JUnitSuite { val actor = actorOf[TestActor].start val x = Future("Hello") - val y = actor !!! "Hello" + val y = actor ? "Hello" mapTo manifest[Nothing] val r = flow(x() + y()) 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 e71ca14721..678cbd2e86 100644 --- a/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala @@ -4,7 +4,7 @@ import org.scalatest.matchers.MustMatchers import org.scalatest.{ BeforeAndAfterAll, BeforeAndAfterEach } import org.scalatest.junit.JUnitRunner import org.junit.runner.RunWith -import akka.actor.{ Actor, ActorRegistry } +import akka.actor.{ Actor, ActorRegistry, NullChannel } import akka.actor.Actor.{ actorOf } import java.util.concurrent.{ TimeUnit, CountDownLatch, BlockingQueue } import java.util.{ Queue } @@ -84,7 +84,7 @@ abstract class MailboxSpec extends WordSpec with MustMatchers with BeforeAndAfte new MessageInvocation( actorOf(new Actor { //Dummy actor def receive = { case _ ⇒ } - }), msg, None, None) + }), msg, NullChannel) } def ensureInitialMailboxState(config: MailboxType, q: MessageQueue) { @@ -158,4 +158,4 @@ class PriorityMailboxSpec extends MailboxSpec { 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/ThreadBasedActorSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/PinnedActorSpec.scala similarity index 83% rename from akka-actor-tests/src/test/scala/akka/dispatch/ThreadBasedActorSpec.scala rename to akka-actor-tests/src/test/scala/akka/dispatch/PinnedActorSpec.scala index 722c48fbdc..a3d647fcf3 100644 --- a/akka-actor-tests/src/test/scala/akka/dispatch/ThreadBasedActorSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/dispatch/PinnedActorSpec.scala @@ -8,7 +8,7 @@ import akka.dispatch.Dispatchers import akka.actor.Actor import Actor._ -object ThreadBasedActorSpec { +object PinnedActorSpec { class TestActor extends Actor { self.dispatcher = Dispatchers.newPinnedDispatcher(self) @@ -21,8 +21,8 @@ object ThreadBasedActorSpec { } } -class ThreadBasedActorSpec extends JUnitSuite { - import ThreadBasedActorSpec._ +class PinnedActorSpec extends JUnitSuite { + import PinnedActorSpec._ private val unit = TimeUnit.MILLISECONDS @@ -43,7 +43,7 @@ class ThreadBasedActorSpec extends JUnitSuite { @Test def shouldSendReplySync = { val actor = actorOf[TestActor].start() - val result = (actor !! ("Hello", 10000)).as[String] + val result = (actor.?("Hello", 10000)).as[String] assert("World" === result.get) actor.stop() } @@ -51,8 +51,8 @@ class ThreadBasedActorSpec extends JUnitSuite { @Test def shouldSendReplyAsync = { val actor = actorOf[TestActor].start() - val result = actor !! "Hello" - assert("World" === result.get.asInstanceOf[String]) + val result = (actor ? "Hello").as[String] + assert("World" === result.get) actor.stop() } @@ -60,7 +60,7 @@ class ThreadBasedActorSpec extends JUnitSuite { def shouldSendReceiveException = { val actor = actorOf[TestActor].start() try { - actor !! "Failure" + (actor ? "Failure").get fail("Should have thrown an exception") } catch { case e ⇒ 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 5740edb9b8..5ddd9fa411 100644 --- a/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala @@ -44,7 +44,7 @@ class PriorityDispatcherSpec extends WordSpec with MustMatchers { 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.?('Result).as[List[Int]].get must be === (msgs.reverse) } } 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 df6184c292..8522a2c92b 100644 --- a/akka-actor-tests/src/test/scala/akka/misc/ActorRegistrySpec.scala +++ b/akka-actor-tests/src/test/scala/akka/misc/ActorRegistrySpec.scala @@ -89,7 +89,7 @@ class ActorRegistrySpec extends JUnitSuite { val actor2 = actorOf[TestActor]("test-actor-2").start val results = new ConcurrentLinkedQueue[Future[String]] - Actor.registry.local.foreach(actor ⇒ results.add(actor.!!![String]("ping"))) + Actor.registry.local.foreach(actor ⇒ results.add(actor.?("ping").mapTo[String])) assert(results.size === 2) val i = results.iterator 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 0fa5b8e017..9c1704b7f5 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala @@ -7,12 +7,12 @@ import akka.testing._ import akka.testing.Testing.{ sleepFor, testMillis } import akka.util.duration._ +import akka.actor._ import akka.actor.Actor._ import akka.routing._ import java.util.concurrent.atomic.AtomicInteger import akka.dispatch.{ KeptPromise, Future } -import akka.actor.{ TypedActor, Actor } object RoutingSpec { trait Foo { @@ -55,10 +55,11 @@ class RoutingSpec extends WordSpec with MustMatchers { case Test3 ⇒ t2 }.start() + implicit val timeout = Actor.Timeout(testMillis(5 seconds)) 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)).as[Int] + b ← (d ? (Test2)).as[Int] + c ← (d ? (Test3)).as[Int] } yield a + b + c result.isDefined must be(true) @@ -166,38 +167,6 @@ class RoutingSpec extends WordSpec with MustMatchers { for (a ← List(broadcast, a1, a2, a3)) a.stop() } - - "be defined at" in { - import akka.actor.ActorRef - - val Yes = "yes" - val No = "no" - - def testActor() = actorOf(new Actor() { - def receive = { - case Yes ⇒ "yes" - } - }).start() - - val t1 = testActor() - val t2 = testActor() - val t3 = testActor() - val t4 = testActor() - - 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) - - for (a ← List(t1, t2, d1, d2)) a.stop() - } } "Actor Pool" must { @@ -225,11 +194,11 @@ class RoutingSpec extends WordSpec with MustMatchers { }).start() val successes = TestLatch(2) - val successCounter = Some(actorOf(new Actor { + val successCounter = actorOf(new Actor { def receive = { case "success" ⇒ successes.countDown() } - }).start()) + }).start() implicit val replyTo = successCounter pool ! "a" @@ -240,7 +209,7 @@ class RoutingSpec extends WordSpec with MustMatchers { count.get must be(2) - (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be(2) + (pool ? ActorPool.Stat).as[ActorPool.Stats].get.size must be(2) pool.stop() } @@ -269,7 +238,7 @@ class RoutingSpec extends WordSpec with MustMatchers { }).start() try { - (for (count ← 1 to 500) yield pool.!!![String]("Test", 20000)) foreach { + (for (count ← 1 to 500) yield pool.?("Test", 20000)) foreach { _.await.resultOrException.get must be("Response") } } finally { @@ -308,14 +277,14 @@ class RoutingSpec extends WordSpec with MustMatchers { pool ! 1 - (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be(2) + (pool ? ActorPool.Stat).as[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) { - pool !!! t + pool ? t sleepFor(50 millis) } } @@ -328,7 +297,7 @@ class RoutingSpec extends WordSpec with MustMatchers { latch.await count.get must be(loops) - (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be(2) + (pool ? ActorPool.Stat).as[ActorPool.Stats].get.size must be(2) // a whole bunch should max it out @@ -337,7 +306,7 @@ class RoutingSpec extends WordSpec with MustMatchers { latch.await count.get must be(loops) - (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be(4) + (pool ? ActorPool.Stat).as[ActorPool.Stats].get.size must be(4) pool.stop() } @@ -385,7 +354,7 @@ class RoutingSpec extends WordSpec with MustMatchers { latch.await count.get must be(loops) - (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be(2) + (pool ? ActorPool.Stat).as[ActorPool.Stats].get.size must be(2) // send a bunch over the theshold and observe an increment loops = 15 @@ -394,7 +363,7 @@ class RoutingSpec extends WordSpec with MustMatchers { latch.await(10 seconds) count.get must be(loops) - (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be >= (3) + (pool ? ActorPool.Stat).as[ActorPool.Stats].get.size must be >= (3) pool.stop() } @@ -490,7 +459,7 @@ class RoutingSpec extends WordSpec with MustMatchers { sleepFor(5 millis) - val z = (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size + val z = (pool ? ActorPool.Stat).as[ActorPool.Stats].get.size z must be >= (2) @@ -501,7 +470,7 @@ class RoutingSpec extends WordSpec with MustMatchers { sleepFor(500 millis) } - (pool !! ActorPool.Stat).asInstanceOf[Option[ActorPool.Stats]].get.size must be <= (z) + (pool ? ActorPool.Stat).as[ActorPool.Stats].get.size must be <= (z) pool.stop() } diff --git a/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala b/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala new file mode 100644 index 0000000000..48e43a5e6d --- /dev/null +++ b/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala @@ -0,0 +1,63 @@ +/** + * Copyright (C) 2009-2011 Scalable Solutions AB + */ + +package akka.serialization + +import org.scalatest.junit.JUnitSuite +import org.junit.Test +import akka.serialization.Serialization._ +import scala.reflect._ + +object SerializeSpec { + @BeanInfo + case class Address(no: String, street: String, city: String, zip: String) { def this() = this("", "", "", "") } + @BeanInfo + case class Person(name: String, age: Int, address: Address) { def this() = this("", 0, null) } + + case class Record(id: Int, person: Person) +} + +class SerializeSpec extends JUnitSuite { + import SerializeSpec._ + + @Test + def shouldSerializeAddress { + val addr = Address("120", "Monroe Street", "Santa Clara", "95050") + val b = serialize(addr) match { + case Left(exception) ⇒ fail(exception) + case Right(bytes) ⇒ bytes + } + deserialize(b.asInstanceOf[Array[Byte]], classOf[Address], None) match { + case Left(exception) ⇒ fail(exception) + case Right(add) ⇒ assert(add === addr) + } + } + + @Test + def shouldSerializePerson { + val person = Person("debasish ghosh", 25, Address("120", "Monroe Street", "Santa Clara", "95050")) + val b = serialize(person) match { + case Left(exception) ⇒ fail(exception) + case Right(bytes) ⇒ bytes + } + deserialize(b.asInstanceOf[Array[Byte]], classOf[Person], None) match { + case Left(exception) ⇒ fail(exception) + case Right(p) ⇒ assert(p === person) + } + } + + @Test + def shouldSerializeRecordWithDefaultSerializer { + val person = Person("debasish ghosh", 25, Address("120", "Monroe Street", "Santa Clara", "95050")) + val r = Record(100, person) + val b = serialize(r) match { + case Left(exception) ⇒ fail(exception) + case Right(bytes) ⇒ bytes + } + deserialize(b.asInstanceOf[Array[Byte]], classOf[Record], None) match { + case Left(exception) ⇒ fail(exception) + case Right(p) ⇒ assert(p === r) + } + } +} diff --git a/akka-actor-tests/src/test/scala/akka/serialization/akka-serializer.conf b/akka-actor-tests/src/test/scala/akka/serialization/akka-serializer.conf new file mode 100644 index 0000000000..324adb5c96 --- /dev/null +++ b/akka-actor-tests/src/test/scala/akka/serialization/akka-serializer.conf @@ -0,0 +1,16 @@ +akka { + actor { + serializers { + java = "akka.serialization.JavaSerializer" + proto = "akka.testing.ProtobufSerializer" + sjson = "akka.testing.SJSONSerializer" + default = "akka.serialization.JavaSerializer" + } + + bindings { + java = ["akka.serialization.SerializeSpec$Address", "akka.serialization.MyJavaSerializableActor", "akka.serialization.MyStatelessActorWithMessagesInMailbox", "akka.serialization.MyActorWithProtobufMessagesInMailbox"] + sjson = ["akka.serialization.SerializeSpec$Person"] + proto = ["com.google.protobuf.Message", "akka.actor.ProtobufProtocol$MyMessage"] + } + } +} 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 655083a6d8..e0aa5369e7 100644 --- a/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala @@ -38,6 +38,10 @@ class CallingThreadDispatcherModelSpec extends ActorModelSpec { } } + override def dispatcherShouldCompleteAllUncompletedSenderFuturesOnDeregister { + //Can't handle this... + } + } // vim: set ts=2 sw=2 et: 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 ac5bea25aa..b838f33efc 100644 --- a/akka-actor-tests/src/test/scala/akka/ticket/Ticket703Spec.scala +++ b/akka-actor-tests/src/test/scala/akka/ticket/Ticket703Spec.scala @@ -8,7 +8,7 @@ import org.scalatest.matchers.MustMatchers class Ticket703Spec extends WordSpec with MustMatchers { - "A !!! call to an actor pool" should { + "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 { @@ -28,7 +28,7 @@ class Ticket703Spec extends WordSpec with MustMatchers { } }) }).start() - (actorPool.!!![String]("Ping", 7000)).await.result must be === Some("Response") + (actorPool.?("Ping", 7000)).await.result must be === Some("Response") } } -} \ No newline at end of file +} diff --git a/akka-actor/src/main/scala/akka/actor/Actor.scala b/akka-actor/src/main/scala/akka/actor/Actor.scala index 00bf1bbf02..4f8c8f75a3 100644 --- a/akka-actor/src/main/scala/akka/actor/Actor.scala +++ b/akka-actor/src/main/scala/akka/actor/Actor.scala @@ -10,19 +10,20 @@ import akka.config._ import Config._ import akka.util.{ ListenerManagement, ReflectiveAccess, Duration, Helpers } import ReflectiveAccess._ -import Helpers.{ narrow, narrowSilently } import akka.remoteinterface.RemoteSupport import akka.japi.{ Creator, Procedure } import akka.AkkaException import akka.serialization.{ Format, Serializer } import akka.cluster.ClusterNode import akka.event.EventHandler +import scala.collection.immutable.Stack import scala.reflect.BeanProperty import com.eaio.uuid.UUID import java.lang.reflect.InvocationTargetException +import java.util.concurrent.TimeUnit /** * Life-cycle messages for the Actors @@ -72,10 +73,10 @@ case object Kill extends AutoReceivedMessage with LifeCycleMessage case object ReceiveTimeout extends LifeCycleMessage case class MaximumNumberOfRestartsWithinTimeRangeReached( - @BeanProperty val victim: ActorRef, - @BeanProperty val maxNrOfRetries: Option[Int], - @BeanProperty val withinTimeRange: Option[Int], - @BeanProperty val lastExceptionCausingRestart: Throwable) extends LifeCycleMessage + @BeanProperty victim: ActorRef, + @BeanProperty maxNrOfRetries: Option[Int], + @BeanProperty withinTimeRange: Option[Int], + @BeanProperty lastExceptionCausingRestart: Throwable) extends LifeCycleMessage // Exceptions for Actors class ActorStartException private[akka] (message: String, cause: Throwable = null) extends AkkaException(message, cause) @@ -88,8 +89,11 @@ class InvalidMessageException private[akka] (message: String, cause: Throwable = /** * This message is thrown by default when an Actors behavior doesn't match a message */ -case class UnhandledMessageException(msg: Any, ref: ActorRef) extends Exception { - override def getMessage = "Actor %s does not handle [%s]".format(ref, msg) +case class UnhandledMessageException(msg: Any, ref: ActorRef = null) extends Exception { + // constructor with 'null' ActorRef needed to work with client instantiation of remote exception + override def getMessage = + if (ref ne null) "Actor %s does not handle [%s]".format(ref, msg) + else "Actor does not handle [%s]".format(msg) override def fillInStackTrace() = this //Don't waste cycles generating stack trace } @@ -109,9 +113,6 @@ object Status { */ object Actor extends ListenerManagement { - private[akka] val TIMEOUT = Duration(config.getInt("akka.actor.timeout", 5), TIME_UNIT).toMillis - private[akka] val SERIALIZE_MESSAGES = config.getBool("akka.actor.serialize-messages", false) - /** * A Receive is a convenience type that defines actor message behavior currently modeled as * a PartialFunction[Any, Unit]. @@ -131,14 +132,31 @@ object Actor extends ListenerManagement { subclassAudits synchronized { subclassAudits.clear() } } } - Runtime.getRuntime.addShutdownHook(new Thread(hook)) + Runtime.getRuntime.addShutdownHook(new Thread(hook, "akka-shutdown-hook")) hook } - private[actor] val actorRefInCreation = new ThreadLocal[Option[ActorRef]] { - override def initialValue = None + private[actor] val actorRefInCreation = new ThreadLocal[Stack[ActorRef]] { + override def initialValue = Stack[ActorRef]() } + case class Timeout(duration: Duration) { + def this(timeout: Long) = this(Duration(timeout, TimeUnit.MILLISECONDS)) + def this(length: Long, unit: TimeUnit) = this(Duration(length, unit)) + } + object Timeout { + def apply(timeout: Long) = new Timeout(timeout) + def apply(length: Long, unit: TimeUnit) = new Timeout(length, unit) + implicit def durationToTimeout(duration: Duration) = new Timeout(duration) + implicit def intToTimeout(timeout: Int) = new Timeout(timeout) + implicit def longToTimeout(timeout: Long) = new Timeout(timeout) + } + + private[akka] val TIMEOUT = Duration(config.getInt("akka.actor.timeout", 5), TIME_UNIT).toMillis + val defaultTimeout = Timeout(TIMEOUT) + val noTimeoutGiven = Timeout(-123456789) + private[akka] val SERIALIZE_MESSAGES = config.getBool("akka.actor.serialize-messages", false) + /** * Handle to the ActorRegistry. */ @@ -159,9 +177,6 @@ object Actor extends ListenerManagement { */ private[akka] lazy val remote: RemoteSupport = cluster.remoteService - // start up a cluster node to join the ZooKeeper cluster - //if (ClusterModule.isEnabled) cluster.start() - /** * Creates an ActorRef out of the Actor with type T. *
@@ -272,7 +287,7 @@ object Actor extends ListenerManagement {
    * 
*/ def actorOf[T <: Actor](creator: ⇒ T, address: String): ActorRef = { - createActor(address, () ⇒ new LocalActorRef(() ⇒ creator, address)) + createActor(address, () ⇒ new LocalActorRef(() ⇒ creator, address, Transient)) } /** @@ -295,7 +310,7 @@ object Actor extends ListenerManagement { * JAVA API */ def actorOf[T <: Actor](creator: Creator[T], address: String): ActorRef = { - createActor(address, () ⇒ new LocalActorRef(() ⇒ creator.create, address)) + createActor(address, () ⇒ new LocalActorRef(() ⇒ creator.create, address, Transient)) } /** @@ -323,25 +338,6 @@ object Actor extends ListenerManagement { }).start() ! Spawn } - /** - * Implicitly converts the given Option[Any] to a AnyOptionAsTypedOption which offers the method as[T] - * to convert an Option[Any] to an Option[T]. - */ - implicit def toAnyOptionAsTypedOption(anyOption: Option[Any]) = new AnyOptionAsTypedOption(anyOption) - - /** - * Implicitly converts the given Future[_] to a AnyOptionAsTypedOption which offers the method as[T] - * to convert an Option[Any] to an Option[T]. - * This means that the following code is equivalent: - * (actor !! "foo").as[Int] (Deprecated) - * and - * (actor !!! "foo").as[Int] (Recommended) - */ - implicit def futureToAnyOptionAsTypedOption(anyFuture: Future[_]) = new AnyOptionAsTypedOption({ - try { anyFuture.await } catch { case t: FutureTimeoutException ⇒ } - anyFuture.resultOrException - }) - private[akka] def createActor(address: String, actorFactory: () ⇒ ActorRef): ActorRef = { Address.validate(address) registry.actorFor(address) match { // check if the actor for the address is already in the registry @@ -377,18 +373,27 @@ object Actor extends ListenerManagement { "\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) + }, address, Transient) } private def newClusterActorRef(factory: () ⇒ ActorRef, address: String, deploy: Deploy): ActorRef = { deploy match { - case Deploy(_, router, serializerClassName, Clustered(home, replication: Replication, state: State)) ⇒ + case Deploy( + configAdress, router, serializerClassName, + Clustered( + home, + replicas, + replication)) ⇒ ClusterModule.ensureEnabled() - if (!Actor.remote.isRunning) throw new IllegalStateException("Remote server is not running") + + if (configAdress != address) throw new IllegalStateException( + "Deployment config for [" + address + "] is wrong [" + deploy + "]") + if (!Actor.remote.isRunning) throw new IllegalStateException( + "Remote server is not running") val isHomeNode = DeploymentConfig.isHomeNode(home) - val replicas = DeploymentConfig.replicaValueFor(replication) + val nrOfReplicas = DeploymentConfig.replicaValueFor(replicas) def serializerErrorDueTo(reason: String) = throw new akka.config.ConfigurationException( @@ -396,42 +401,34 @@ object Actor extends ListenerManagement { "] for serialization of actor [" + address + "] since " + reason) - val serializer: Serializer = { - if ((serializerClassName eq null) || - (serializerClassName == "") || - (serializerClassName == Format.defaultSerializerName)) { - Format.Default - } else { - val clazz: Class[_] = ReflectiveAccess.getClassFor(serializerClassName) match { - case Right(clazz) ⇒ clazz - case Left(exception) ⇒ - val cause = exception match { - case i: InvocationTargetException ⇒ i.getTargetException - case _ ⇒ exception - } - serializerErrorDueTo(cause.toString) - } - val f = clazz.newInstance.asInstanceOf[AnyRef] - if (f.isInstanceOf[Serializer]) f.asInstanceOf[Serializer] - else serializerErrorDueTo("class must be of type [akka.serialization.Serializer]") - } - } + val serializer: Serializer = + akka.serialization.Serialization.getSerializer(this.getClass).fold(x ⇒ serializerErrorDueTo(x.toString), s ⇒ s) - if (isHomeNode) { // home node for clustered actor - cluster - .use(address, serializer) - .getOrElse(throw new ConfigurationException( - "Could not check out actor [" + address + "] from cluster registry as a \"local\" actor")) - - } else { - if (!cluster.isClustered(address)) { - cluster.store(factory().start(), replicas, false, serializer) // add actor to cluster registry (if not already added) - } + def storeActorAndGetClusterRef(replicationScheme: ReplicationScheme, serializer: Serializer): ActorRef = { + // add actor to cluster registry (if not already added) + if (!cluster.isClustered(address)) + cluster.store(factory().start(), nrOfReplicas, replicationScheme, false, serializer) // remote node (not home node), check out as ClusterActorRef cluster.ref(address, DeploymentConfig.routerTypeFor(router)) } + replication match { + case _: Transient | Transient ⇒ + storeActorAndGetClusterRef(Transient, serializer) + + case replication: Replication ⇒ + if (isHomeNode) { // stateful actor's home node + cluster + .use(address, serializer) + .getOrElse(throw new ConfigurationException( + "Could not check out actor [" + address + "] from cluster registry as a \"local\" actor")) + } else { + // FIXME later manage different 'storage' (data grid) as well + storeActorAndGetClusterRef(replication, serializer) + } + } + case invalid ⇒ throw new IllegalActorStateException( "Could not create actor with address [" + address + "], not bound to a valid deployment scheme [" + invalid + "]") @@ -455,7 +452,7 @@ object Actor extends ListenerManagement { * *

* Here you find functions like: - * - !, !!, !!! and forward + * - !, ? and forward * - link, unlink, startLink etc * - start, stop * - etc. @@ -492,33 +489,40 @@ trait Actor { */ type Receive = Actor.Receive - /* + /** * Some[ActorRef] representation of the 'self' ActorRef reference. *

* Mainly for internal use, functions as the implicit sender references when invoking * the 'forward' function. */ @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'." + + val someSelf: Some[ActorRef] = { + val refStack = Actor.actorRefInCreation.get + if (refStack.isEmpty) throw new ActorInitializationException( + "\n\tYou can not create an instance of an " + getClass.getName + " 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]] + + val ref = refStack.head + + if (ref eq null) + throw new ActorInitializationException("Trying to create an instance of " + getClass.getName + " outside of a wrapping 'actorOf'") + else { + // Push a null marker so any subsequent calls to new Actor doesn't reuse this actor ref + Actor.actorRefInCreation.set(refStack.push(null)) + Some(ref) + } } /* * Option[ActorRef] representation of the 'self' ActorRef reference. *

* Mainly for internal use, functions as the implicit sender references when invoking - * one of the message send functions ('!', '!!' and '!!!'). + * one of the message send functions ('!' and '?'). */ - implicit def optionSelf: Option[ActorRef] = someSelf + def optionSelf: Option[ActorRef] = someSelf /** * The 'self' field holds the ActorRef for this actor. @@ -548,7 +552,7 @@ trait Actor { * */ @transient - val self: ScalaActorRef = someSelf.get + implicit val self: ScalaActorRef = someSelf.get /** * User overridable callback/setting. @@ -611,21 +615,6 @@ trait Actor { throw new UnhandledMessageException(msg, self) } - /** - * Is the actor able to handle the message passed in as arguments? - */ - 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 msg if behaviorStack.nonEmpty && - behaviorStack.head.isDefinedAt(msg) ⇒ true - case msg if behaviorStack.isEmpty && - processingBehavior.isDefinedAt(msg) ⇒ true - case _ ⇒ false - } - } - /** * Changes the Actor's behavior to become the new 'Receive' (PartialFunction[Any, Unit]) handler. * Puts the behavior on top of the hotswap stack. @@ -650,14 +639,13 @@ trait Actor { private[akka] final def apply(msg: Any) = { if (msg.isInstanceOf[AnyRef] && (msg.asInstanceOf[AnyRef] eq null)) - throw new InvalidMessageException("Message from [" + self.sender + "] to [" + self.toString + "] is null") + throw new InvalidMessageException("Message from [" + self.channel + "] to [" + self.toString + "] is null") val behaviorStack = self.hotswap + msg match { case l: AutoReceivedMessage ⇒ autoReceiveMessage(l) - case msg if behaviorStack.nonEmpty && - behaviorStack.head.isDefinedAt(msg) ⇒ behaviorStack.head.apply(msg) - case msg if behaviorStack.isEmpty && - processingBehavior.isDefinedAt(msg) ⇒ processingBehavior.apply(msg) + case msg if behaviorStack.nonEmpty && 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 } } @@ -673,35 +661,11 @@ trait Actor { case Restart(reason) ⇒ throw reason case Kill ⇒ throw new ActorKilledException("Kill") case PoisonPill ⇒ - val f = self.senderFuture() + val ch = self.channel self.stop() - if (f.isDefined) f.get.completeWithException(new ActorKilledException("PoisonPill")) + ch.sendException(new ActorKilledException("PoisonPill")) } } private lazy val processingBehavior = receive //ProcessingBehavior is the original behavior } - -private[actor] class AnyOptionAsTypedOption(anyOption: Option[Any]) { - - /** - * Convenience helper to cast the given Option of Any to an Option of the given type. Will throw a ClassCastException - * if the actual type is not assignable from the given one. - */ - def as[T]: Option[T] = narrow[T](anyOption) - - /** - * Convenience helper to cast the given Option of Any to an Option of the given type. Will swallow a possible - * ClassCastException and return None in that case. - */ - def asSilently[T: Manifest]: Option[T] = narrowSilently[T](anyOption) -} - -/** - * Marker interface for proxyable actors (such as typed actor). - * - * @author Jonas Bonér - */ -trait Proxyable { - private[actor] def swapProxiedActor(newInstance: Actor) -} diff --git a/akka-actor/src/main/scala/akka/actor/ActorRef.scala b/akka-actor/src/main/scala/akka/actor/ActorRef.scala index bc5efa02b0..ae36ba8b2a 100644 --- a/akka-actor/src/main/scala/akka/actor/ActorRef.scala +++ b/akka-actor/src/main/scala/akka/actor/ActorRef.scala @@ -6,10 +6,13 @@ package akka.actor import akka.event.EventHandler import akka.dispatch._ -import akka.config.Config +import akka.config._ import akka.config.Supervision._ import akka.util._ +import akka.serialization.{ Format, Serializer } import ReflectiveAccess._ +import ClusterModule._ +import DeploymentConfig.{ ReplicationScheme, Replication, Transient, WriteThrough, WriteBehind } import java.net.InetSocketAddress import java.util.concurrent.atomic.AtomicReference @@ -19,6 +22,7 @@ import java.util.{ Map ⇒ JMap } import scala.reflect.BeanProperty import scala.collection.immutable.Stack import scala.annotation.tailrec +import java.lang.IllegalStateException private[akka] object ActorRefInternals { @@ -32,27 +36,6 @@ private[akka] object ActorRefInternals { object SHUTDOWN extends StatusType } -/** - * Abstraction for unification of sender and senderFuture for later reply. - * Can be stored away and used at a later point in time. - */ -abstract class Channel[T] { - - /** - * Scala API.

- * Sends the specified message to the channel. - */ - def !(msg: T) - - /** - * Java API.

- * Sends the specified message to the channel. - */ - def sendOneWay(msg: T) { - this.!(msg) - } -} - /** * ActorRef is an immutable and serializable handle to an Actor. *

@@ -85,20 +68,20 @@ abstract class Channel[T] { * * @author Jonas Bonér */ -trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scalaRef: ScalaActorRef ⇒ +trait ActorRef extends ActorRefShared with ForwardableChannel with java.lang.Comparable[ActorRef] with Serializable { scalaRef: ScalaActorRef ⇒ // Only mutable for RemoteServer in order to maintain identity across nodes @volatile protected[akka] var _uuid = newUuid @volatile protected[this] var _status: ActorRefInternals.StatusType = ActorRefInternals.UNSTARTED - val address: String + def address: String /** * User overridable callback/setting. *

- * Defines the default timeout for '!!' and '!!!' invocations, - * e.g. the timeout for the future returned by the call to '!!' and '!!!'. + * Defines the default timeout for '?'/'ask' invocations, + * e.g. the timeout for the future returned by the call to '?'/'ask'. */ @deprecated("Will be replaced by implicit-scoped timeout on all methods that needs it, will default to timeout specified in config", "1.1") @BeanProperty @@ -206,7 +189,7 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal /** * Akka Java API.

* The reference sender future of the last received message. - * Is defined if the message was sent with sent with '!!' or '!!!', else None. + * Is defined if the message was sent with sent with '?'/'ask', else None. */ def getSenderFuture: Option[Promise[Any]] = senderFuture @@ -233,12 +216,6 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal */ def isUnstarted: Boolean = _status == ActorRefInternals.UNSTARTED - /** - * Is the actor able to handle the message passed in as arguments? - */ - @deprecated("Will be removed without replacement, it's just not reliable in the face of `become` and `unbecome`", "1.1") - def isDefinedAt(message: Any): Boolean = actor.isDefinedAt(message) - /** * Only for internal use. UUID is effectively final. */ @@ -248,82 +225,17 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal /** * Akka Java API.

- * Sends a one-way asynchronous message. E.g. fire-and-forget semantics. - *

- *

-   * actor.sendOneWay(message);
-   * 
- *

- */ - def sendOneWay(message: AnyRef): Unit = { - sendOneWay(message, null) - } - - /** - * Akka Java API.

- * Sends a one-way asynchronous message. E.g. fire-and-forget semantics. - *

- * Allows you to pass along the sender of the message. - *

- *

-   * actor.sendOneWay(message, context);
-   * 
- *

- */ - def sendOneWay(message: AnyRef, sender: ActorRef) { - this.!(message)(Option(sender)) - } - - /** - * Akka Java API.

- * @see sendRequestReply(message: AnyRef, timeout: Long, sender: ActorRef) - * Uses the default timeout of the Actor (setTimeout()) and omits the sender reference - */ - def sendRequestReply(message: AnyRef): AnyRef = sendRequestReply(message, timeout, null) - - /** - * Akka Java API.

- * @see sendRequestReply(message: AnyRef, timeout: Long, sender: ActorRef) - * Uses the default timeout of the Actor (setTimeout()) - */ - def sendRequestReply(message: AnyRef, sender: ActorRef): AnyRef = sendRequestReply(message, timeout, sender) - - /** - * Akka Java API.

- * Sends a message asynchronously and waits on a future for a reply message under the hood. - *

- * It waits on the reply either until it receives it or until the timeout expires - * (which will throw an ActorTimeoutException). E.g. send-and-receive-eventually semantics. - *

- * NOTE: - * Use this method with care. In most cases it is better to use 'sendOneWay' together with 'getContext().getSender()' to - * implement request/response message exchanges. - *

- * If you are sending messages using sendRequestReply 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 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.")) - .asInstanceOf[AnyRef] - } - - /** - * Akka Java API.

- * @see sendRequestReplyFuture(message: AnyRef, sender: ActorRef): Future[_] + * @see ask(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 ask(message: AnyRef): Future[AnyRef] = ask(message, timeout, null) /** * Akka Java API.

- * @see sendRequestReplyFuture(message: AnyRef, sender: ActorRef): Future[_] + * @see ask(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 ask(message: AnyRef, sender: ActorRef): Future[AnyRef] = ask(message, timeout, sender) /** * Akka Java API.

@@ -333,10 +245,11 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal * Use this method with care. In most cases it is better to use 'sendOneWay' together with the 'getContext().getSender()' to * implement request/response message exchanges. *

- * If you are sending messages using sendRequestReplyFuture then you have to use getContext().reply(..) + * If you are sending messages using ask 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 ask(message: AnyRef, timeout: Long, sender: ActorRef): Future[AnyRef] = + ?(message, Actor.Timeout(timeout))(sender).asInstanceOf[Future[AnyRef]] /** * Akka Java API.

@@ -344,7 +257,7 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal */ def forward(message: AnyRef, sender: ActorRef) { if (sender eq null) throw new IllegalArgumentException("The 'sender' argument to 'forward' can't be null") - else forward(message)(Some(sender)) + else forward(message)(sender) } /** @@ -415,17 +328,6 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal */ def startLink(actorRef: ActorRef): ActorRef - /** - * Returns the mailbox size. - */ - def mailboxSize = dispatcher.mailboxSize(this) - - /** - * Akka Java API.

- * Returns the mailbox size. - */ - def getMailboxSize: Int = mailboxSize - /** * Returns the supervisor, if there is one. */ @@ -453,36 +355,36 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal /** * Abstraction for unification of sender and senderFuture for later reply */ - def channel: Channel[Any] = { - if (senderFuture.isDefined) { - new Channel[Any] { - val future = senderFuture.get - def !(msg: Any) = future completeWithResult msg - } - } else if (sender.isDefined) { - val someSelf = Some(this) - new Channel[Any] { - val client = sender.get - def !(msg: Any) = client.!(msg)(someSelf) - } - } else throw new IllegalActorStateException("No channel available") + def channel: UntypedChannel = { + val msg = currentMessage + if (msg ne null) msg.channel + else NullChannel } + /* + * Implementation of ForwardableChannel + */ + + def sendException(ex: Throwable) {} + def isUsableOnlyOnce = false + def isUsable = true + def isReplyable = true + def canSendException = false + /** * Java API.

* Abstraction for unification of sender and senderFuture for later reply */ - def getChannel: Channel[Any] = channel + def getChannel: UntypedChannel = channel protected[akka] def invoke(messageHandle: MessageInvocation) - protected[akka] def postMessageToMailbox(message: Any, senderOption: Option[ActorRef]) + protected[akka] def postMessageToMailbox(message: Any, channel: UntypedChannel): Unit - protected[akka] def postMessageToMailboxAndCreateFutureResultWithTimeout[T]( + protected[akka] def postMessageToMailboxAndCreateFutureResultWithTimeout( message: Any, timeout: Long, - senderOption: Option[ActorRef], - senderFuture: Option[Promise[T]]): Promise[T] + channel: UntypedChannel): Future[Any] protected[akka] def actorInstance: AtomicReference[Actor] @@ -506,7 +408,7 @@ trait ActorRef extends ActorRefShared with java.lang.Comparable[ActorRef] { scal that.asInstanceOf[ActorRef].uuid == uuid } - override def toString = "Actor[" + address + ":" + uuid + "]" + override def toString = "Actor[%s:%s]".format(address, uuid) } /** @@ -514,27 +416,82 @@ 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, + replicationScheme: ReplicationScheme) extends ActorRef with ScalaActorRef { + protected[akka] val guard = new ReentrantGuard @volatile protected[akka] var _futureTimeout: Option[ScheduledFuture[AnyRef]] = None + @volatile private[akka] lazy val _linkedActors = new ConcurrentHashMap[Uuid, ActorRef] + @volatile private[akka] var _supervisor: Option[ActorRef] = None + @volatile private var maxNrOfRetriesCount: Int = 0 + @volatile private var restartTimeWindowStartNanos: Long = 0L + @volatile private var _mailbox: AnyRef = _ + @volatile private[akka] var _dispatcher: MessageDispatcher = Dispatchers.defaultGlobalDispatcher protected[akka] val actorInstance = guard.withGuard { new AtomicReference[Actor](newActor) } + private val isReplicated: Boolean = replicationScheme match { + case _: Transient | Transient ⇒ false + case _ ⇒ true + } + + // FIXME how to get the matching serializerClassName? Now default is used. Needed for transaction log snapshot + // private val serializer = Actor.serializerFor(address, Format.defaultSerializerName) + + def serializerErrorDueTo(reason: String) = + throw new akka.config.ConfigurationException( + "Could not create Serializer object [" + this.getClass.getName + + "]") + + private val serializer: Serializer = + akka.serialization.Serialization.getSerializer(this.getClass).fold(x ⇒ serializerErrorDueTo(x.toString), s ⇒ s) + + private lazy val replicationStorage: Either[TransactionLog, AnyRef] = { + replicationScheme match { + case _: Transient | Transient ⇒ + throw new IllegalStateException("Can not replicate 'transient' actor [" + toString + "]") + + case Replication(storage, strategy) ⇒ + val isWriteBehind = strategy match { + case _: WriteBehind | WriteBehind ⇒ true + case _: WriteThrough | WriteThrough ⇒ false + } + + storage match { + case _: DeploymentConfig.TransactionLog | DeploymentConfig.TransactionLog ⇒ + EventHandler.debug(this, + "Creating a transaction log for Actor [%s] with replication strategy [%s]" + .format(address, replicationScheme)) + // Left(transactionLog.newLogFor(_uuid.toString, isWriteBehind, replicationScheme, serializer)) + // to fix null + Left(transactionLog.newLogFor(_uuid.toString, isWriteBehind, replicationScheme, null)) + + case _: DeploymentConfig.DataGrid | DeploymentConfig.DataGrid ⇒ + throw new ConfigurationException("Replication storage type \"data-grid\" is not yet supported") + + case unknown ⇒ + throw new ConfigurationException("Unknown replication storage type [" + unknown + "]") + } + } + } + //If it was started inside "newActor", initialize it if (isRunning) initializeActorInstance @@ -547,8 +504,11 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () ⇒ Actor, __lifeCycle: LifeCycle, __supervisor: Option[ActorRef], __hotswap: Stack[PartialFunction[Any, Unit]], - __factory: () ⇒ Actor) = { - this(__factory, __address) + __factory: () ⇒ Actor, + __replicationStrategy: ReplicationScheme) = { + + this(__factory, __address, __replicationStrategy) + _uuid = __uuid timeout = __timeout receiveTimeout = __receiveTimeout @@ -620,6 +580,10 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () ⇒ Actor, setActorSelfFields(actorInstance.get, null) } } //else if (isBeingRestarted) throw new ActorKilledException("Actor [" + toString + "] is being restarted.") + + if (isReplicated) { + if (replicationStorage.isLeft) replicationStorage.left.get.delete() + } } } @@ -656,7 +620,6 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () ⇒ Actor, guard.withGuard { if (_linkedActors.remove(actorRef.uuid) eq null) throw new IllegalActorStateException("Actor [" + actorRef + "] is not a linked actor, can't unlink") - actorRef.supervisor = None } } @@ -685,24 +648,31 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () ⇒ Actor, def supervisor: Option[ActorRef] = _supervisor // ========= AKKA PROTECTED FUNCTIONS ========= + @throws(classOf[java.io.ObjectStreamException]) + private def writeReplace(): AnyRef = { + val inetaddr = + if (ReflectiveAccess.RemoteModule.isEnabled) Actor.remote.address + else ReflectiveAccess.RemoteModule.configDefaultAddress + SerializedActorRef(uuid, address, inetaddr.getAddress.getHostAddress, inetaddr.getPort, timeout) + } protected[akka] def supervisor_=(sup: Option[ActorRef]) { _supervisor = sup } - protected[akka] def postMessageToMailbox(message: Any, senderOption: Option[ActorRef]) { - dispatcher dispatchMessage new MessageInvocation(this, message, senderOption, None) - } + protected[akka] def postMessageToMailbox(message: Any, channel: UntypedChannel): Unit = + dispatcher dispatchMessage new MessageInvocation(this, message, channel) - protected[akka] def postMessageToMailboxAndCreateFutureResultWithTimeout[T]( + protected[akka] def postMessageToMailboxAndCreateFutureResultWithTimeout( message: Any, timeout: Long, - senderOption: Option[ActorRef], - senderFuture: Option[Promise[T]]): Promise[T] = { - val future = if (senderFuture.isDefined) senderFuture else Some(new DefaultPromise[T](timeout)) - dispatcher dispatchMessage new MessageInvocation( - this, message, senderOption, future.asInstanceOf[Some[Promise[Any]]]) - future.get + channel: UntypedChannel): Future[Any] = { + val future = channel match { + case f: ActorPromise ⇒ f + case _ ⇒ new ActorPromise(timeout) + } + dispatcher dispatchMessage new MessageInvocation(this, message, future) + future } /** @@ -733,7 +703,12 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () ⇒ Actor, throw e } } - } finally { guard.lock.unlock() } + } finally { + guard.lock.unlock() + if (isReplicated) { + if (replicationStorage.isLeft) replicationStorage.left.get.recordEntry(messageHandle, this) + } + } } protected[akka] def handleTrapExit(dead: ActorRef, reason: Throwable) { @@ -785,27 +760,17 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () ⇒ Actor, protected[akka] def restart(reason: Throwable, maxNrOfRetries: Option[Int], withinTimeRange: Option[Int]) { def performRestart() { val failedActor = actorInstance.get - - failedActor match { - case p: Proxyable ⇒ - failedActor.preRestart(reason) - failedActor.postRestart(reason) - 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 - freshActor.preStart() - freshActor.postRestart(reason) - } + 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 + freshActor.preStart() + freshActor.postRestart(reason) } def tooManyRestarts() { - _supervisor.foreach { sup ⇒ - // can supervisor handle the notification? - val notification = MaximumNumberOfRestartsWithinTimeRangeReached(this, maxNrOfRetries, withinTimeRange, reason) - if (sup.isDefinedAt(notification)) notifySupervisorWithMessage(notification) - } + notifySupervisorWithMessage( + MaximumNumberOfRestartsWithinTimeRangeReached(this, maxNrOfRetries, withinTimeRange, reason)) stop() } @@ -869,14 +834,19 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () ⇒ Actor, // ========= PRIVATE FUNCTIONS ========= private[this] def newActor: Actor = { + import Actor.{ actorRefInCreation ⇒ refStack } + val stackBefore = refStack.get + refStack.set(stackBefore.push(this)) try { - Actor.actorRefInCreation.set(Some(this)) - val a = actorFactory() - if (a eq null) throw new ActorInitializationException("Actor instance passed to ActorRef can not be 'null'") - a + actorFactory() } finally { - Actor.actorRefInCreation.set(None) + val stackAfter = refStack.get + if (stackAfter.nonEmpty) + refStack.set(if (stackAfter.head eq null) stackAfter.pop.pop else stackAfter.pop) //pop null marker plus self } + } match { + case null ⇒ throw new ActorInitializationException("Actor instance passed to ActorRef can not be 'null'") + case valid ⇒ valid } private def shutDownTemporaryActor(temporaryActor: ActorRef) { @@ -893,7 +863,7 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () ⇒ Actor, //Prevent any further messages to be processed until the actor has been restarted dispatcher.suspend(this) - senderFuture.foreach(_.completeWithException(reason)) + channel.sendException(reason) if (supervisor.isDefined) notifySupervisorWithMessage(Exit(this, reason)) else { @@ -957,7 +927,7 @@ class LocalActorRef private[akka] (private[this] val actorFactory: () ⇒ Actor, protected[akka] def checkReceiveTimeout() { cancelReceiveTimeout() - if (receiveTimeout.isDefined && dispatcher.mailboxSize(this) <= 0) { //Only reschedule if desired and there are currently no more messages to be processed + if (receiveTimeout.isDefined && dispatcher.mailboxIsEmpty(this)) { //Only reschedule if desired and there are currently no more messages to be processed _futureTimeout = Some(Scheduler.scheduleOnce(this, ReceiveTimeout, receiveTimeout.get, TimeUnit.MILLISECONDS)) } } @@ -996,23 +966,30 @@ private[akka] case class RemoteActorRef private[akka] ( timeout = _timeout - // FIXME BAD, we should not have different ActorRefs - start() - def postMessageToMailbox(message: Any, senderOption: Option[ActorRef]) { - Actor.remote.send[Any](message, senderOption, None, remoteAddress, timeout, true, this, loader) + def postMessageToMailbox(message: Any, channel: UntypedChannel): Unit = { + val chSender = channel match { + case ref: ActorRef ⇒ Some(ref) + case _ ⇒ None + } + Actor.remote.send[Any](message, chSender, None, remoteAddress, timeout, true, this, loader) } - def postMessageToMailboxAndCreateFutureResultWithTimeout[T]( + def postMessageToMailboxAndCreateFutureResultWithTimeout( message: Any, timeout: Long, - senderOption: Option[ActorRef], - senderFuture: Option[Promise[T]]): Promise[T] = { - val future = Actor.remote.send[T]( - message, senderOption, senderFuture, - remoteAddress, timeout, false, this, loader) - if (future.isDefined) future.get + channel: UntypedChannel): Future[Any] = { + val chSender = channel match { + case ref: ActorRef ⇒ Some(ref) + case _ ⇒ None + } + val chFuture = channel match { + case f: Promise[Any] ⇒ Some(f) + case _ ⇒ None + } + val future = Actor.remote.send[Any](message, chSender, chFuture, remoteAddress, timeout, false, this, loader) + if (future.isDefined) ActorPromise(future.get) else throw new IllegalActorStateException("Expected a future from remote call to actor " + toString) } @@ -1030,9 +1007,12 @@ private[akka] case class RemoteActorRef private[akka] ( } } + @throws(classOf[java.io.ObjectStreamException]) + private def writeReplace(): AnyRef = { + SerializedActorRef(uuid, address, remoteAddress.getAddress.getHostAddress, remoteAddress.getPort, timeout) + } + // ==== NOT SUPPORTED ==== - @deprecated("Will be removed without replacement, doesn't make any sense to have in the face of `become` and `unbecome`", "1.1") - def actorClass: Class[_ <: Actor] = unsupported def dispatcher_=(md: MessageDispatcher) { unsupported } @@ -1095,7 +1075,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 with ForwardableChannel { ref: ActorRef ⇒ /** * Address for actor, must be a unique one. @@ -1133,20 +1113,28 @@ trait ScalaActorRef extends ActorRefShared { ref: ActorRef ⇒ * The reference sender Actor of the last received message. * Is defined if the message was sent from another Actor, else None. */ + @deprecated("will be removed in 2.0, use channel instead", "1.2") def sender: Option[ActorRef] = { val msg = currentMessage if (msg eq null) None - else msg.sender + else msg.channel match { + case ref: ActorRef ⇒ Some(ref) + case _ ⇒ None + } } /** * The reference sender future of the last received message. - * Is defined if the message was sent with sent with '!!' or '!!!', else None. + * Is defined if the message was sent with sent with '?'/'ask', else None. */ + @deprecated("will be removed in 2.0, use channel instead", "1.2") def senderFuture(): Option[Promise[Any]] = { val msg = currentMessage if (msg eq null) None - else msg.senderFuture + else msg.channel match { + case f: ActorPromise ⇒ Some(f) + case _ ⇒ None + } } /** @@ -1163,8 +1151,8 @@ trait ScalaActorRef extends ActorRefShared { ref: ActorRef ⇒ * *

*/ - def !(message: Any)(implicit sender: Option[ActorRef] = None) { - if (isRunning) postMessageToMailbox(message, sender) + def !(message: Any)(implicit channel: UntypedChannel = NullChannel): Unit = { + if (isRunning) postMessageToMailbox(message, channel) else throw new ActorInitializationException( "Actor has not been started, you need to invoke 'actor.start()' before using it") } @@ -1181,9 +1169,10 @@ trait ScalaActorRef extends ActorRefShared { ref: ActorRef ⇒ * If you are sending messages using !! then you have to use self.reply(..) * to send a reply message to the original sender. If not then the sender will block until the timeout expires. */ - def !!(message: Any, timeout: Long = this.timeout)(implicit sender: Option[ActorRef] = None): Option[Any] = { + @deprecated("use `(actor ? msg).as[T]` instead", "1.2") + def !!(message: Any, timeout: Long = this.timeout)(implicit channel: UntypedChannel = NullChannel): Option[Any] = { if (isRunning) { - val future = postMessageToMailboxAndCreateFutureResultWithTimeout[Any](message, timeout, sender, None) + val future = postMessageToMailboxAndCreateFutureResultWithTimeout(message, timeout, channel) try { future.await.resultOrException } catch { case e: FutureTimeoutException ⇒ None } } else throw new ActorInitializationException( @@ -1191,16 +1180,11 @@ trait ScalaActorRef extends ActorRefShared { ref: ActorRef ⇒ } /** - * Sends a message asynchronously returns a future holding the eventual reply message. - *

- * NOTE: - * Use this method with care. In most cases it is better to use '!' together with the 'sender' member field to - * implement request/response message exchanges. - * If you are sending messages using !!! then you have to use self.reply(..) - * to send a reply message to the original sender. If not then the sender will block until the timeout expires. + * Sends a message asynchronously, returning a future which may eventually hold the reply. */ - def !!![T](message: Any, timeout: Long = this.timeout)(implicit sender: Option[ActorRef] = None): Future[T] = { - if (isRunning) postMessageToMailboxAndCreateFutureResultWithTimeout[T](message, timeout, sender, None) + def ?(message: Any, timeout: Actor.Timeout = Actor.noTimeoutGiven)(implicit channel: UntypedChannel = NullChannel, implicitTimeout: Actor.Timeout = Actor.defaultTimeout): Future[Any] = { + val realTimeout = if (timeout eq Actor.noTimeoutGiven) implicitTimeout else timeout + if (isRunning) postMessageToMailboxAndCreateFutureResultWithTimeout(message, realTimeout.duration.toMillis, channel) else throw new ActorInitializationException( "Actor has not been started, you need to invoke 'actor.start()' before using it") } @@ -1208,15 +1192,13 @@ trait ScalaActorRef extends ActorRefShared { ref: ActorRef ⇒ /** * Forwards the message and passes the original sender actor as the sender. *

- * Works with '!', '!!' and '!!!'. + * Works with '!' and '?'/'ask'. */ - def forward(message: Any)(implicit sender: Some[ActorRef]) = { + def forward(message: Any)(implicit channel: ForwardableChannel) = { if (isRunning) { - if (sender.get.senderFuture.isDefined) - postMessageToMailboxAndCreateFutureResultWithTimeout(message, timeout, sender.get.sender, sender.get.senderFuture) - else - postMessageToMailbox(message, sender.get.sender) - } else throw new ActorInitializationException("Actor has not been started, you need to invoke 'actor.start()' before using it") + postMessageToMailbox(message, channel.channel) + } else throw new ActorInitializationException( + "Actor has not been started, you need to invoke 'actor.start()' before using it") } /** @@ -1225,14 +1207,7 @@ trait ScalaActorRef extends ActorRefShared { ref: ActorRef ⇒ *

* Throws an IllegalStateException if unable to determine what to reply to. */ - def reply(message: Any) { - if (!reply_?(message)) throw new IllegalActorStateException( - "\n\tNo sender in scope, can't reply. " + - "\n\tYou have probably: " + - "\n\t\t1. Sent a message to an Actor from an instance that is NOT an Actor." + - "\n\t\t2. Invoked a method on an TypedActor from an instance NOT an TypedActor." + - "\n\tElse you might want to use 'reply_?' which returns Boolean(true) if succes and Boolean(false) if no sender in scope") - } + def reply(message: Any) = channel.!(message)(this) /** * Use reply_?(..) to reply with a message to the original sender of the message currently @@ -1240,14 +1215,23 @@ trait ScalaActorRef extends ActorRefShared { ref: ActorRef ⇒ *

* Returns true if reply was sent, and false if unable to determine what to reply to. */ - def reply_?(message: Any): Boolean = { - if (senderFuture.isDefined) { - senderFuture.get completeWithResult message - true - } else if (sender.isDefined) { - //TODO: optimize away this allocation, perhaps by having implicit self: Option[ActorRef] in signature - sender.get.!(message)(Some(this)) - true - } else false + def reply_?(message: Any): Boolean = channel.safe_!(message)(this) +} + +case class SerializedActorRef(val uuid: Uuid, + val address: String, + val hostname: String, + val port: Int, + val timeout: Long) { + @throws(classOf[java.io.ObjectStreamException]) + def readResolve(): AnyRef = Actor.registry.local.actorFor(uuid) match { + case Some(actor) ⇒ actor + case None ⇒ + if (ReflectiveAccess.RemoteModule.isEnabled) + RemoteActorRef(new InetSocketAddress(hostname, port), address, timeout, None) + else + throw new IllegalStateException( + "Trying to deserialize ActorRef (" + this + + ") but it's not found in the local registry and remoting is not enabled!") } } diff --git a/akka-actor/src/main/scala/akka/actor/ActorRegistry.scala b/akka-actor/src/main/scala/akka/actor/ActorRegistry.scala index f3c38887fb..53a48969af 100644 --- a/akka-actor/src/main/scala/akka/actor/ActorRegistry.scala +++ b/akka-actor/src/main/scala/akka/actor/ActorRegistry.scala @@ -12,7 +12,7 @@ import java.util.concurrent.{ ConcurrentSkipListSet, ConcurrentHashMap } import java.util.{ Set ⇒ JSet } import akka.util.ReflectiveAccess._ -import akka.util.{ ReflectiveAccess, ReadWriteGuard, ListenerManagement } +import akka.util.ListenerManagement import akka.serialization._ /** @@ -21,8 +21,8 @@ import akka.serialization._ * @author Jonas Bonér */ sealed trait ActorRegistryEvent -case class ActorRegistered(address: String, actor: ActorRef) extends ActorRegistryEvent -case class ActorUnregistered(address: String, actor: ActorRef) extends ActorRegistryEvent +case class ActorRegistered(address: String, actor: ActorRef, typedActor: Option[AnyRef]) extends ActorRegistryEvent +case class ActorUnregistered(address: String, actor: ActorRef, typedActor: Option[AnyRef]) extends ActorRegistryEvent /** * Registry holding all Actor instances in the whole system. @@ -36,7 +36,6 @@ private[actor] final class ActorRegistry private[actor] () extends ListenerManag private val actorsByAddress = new ConcurrentHashMap[String, ActorRef] private val actorsByUuid = new ConcurrentHashMap[Uuid, ActorRef] private val typedActorsByUuid = new ConcurrentHashMap[Uuid, AnyRef] - private val guard = new ReadWriteGuard val local = new LocalActorRegistry(actorsByAddress, actorsByUuid, typedActorsByUuid) @@ -45,7 +44,6 @@ 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 } @@ -67,11 +65,12 @@ private[actor] final class ActorRegistry private[actor] () extends ListenerManag actorsByAddress.put(address, actor) actorsByUuid.put(actor.uuid, actor) - notifyListeners(ActorRegistered(address, actor)) + notifyListeners(ActorRegistered(address, actor, Option(typedActorsByUuid get actor.uuid))) } private[akka] def registerTypedActor(actorRef: ActorRef, interface: AnyRef) { typedActorsByUuid.put(actorRef.uuid, interface) + actorRef.start // register actorRef } /** @@ -80,7 +79,7 @@ private[actor] final class ActorRegistry private[actor] () extends ListenerManag private[akka] def unregister(address: String) { val actor = actorsByAddress remove address actorsByUuid remove actor.uuid - notifyListeners(ActorUnregistered(address, actor)) + notifyListeners(ActorUnregistered(address, actor, None)) } /** @@ -90,8 +89,7 @@ private[actor] final class ActorRegistry private[actor] () extends ListenerManag val address = actor.address actorsByAddress remove address actorsByUuid remove actor.uuid - typedActorsByUuid remove actor.uuid - notifyListeners(ActorUnregistered(address, actor)) + notifyListeners(ActorUnregistered(address, actor, Option(typedActorsByUuid remove actor.uuid))) } /** @@ -117,7 +115,7 @@ private[actor] final class ActorRegistry private[actor] () extends ListenerManag } /** - * View over the local actor registry. + * Projection over the local actor registry. */ class LocalActorRegistry( private val actorsByAddress: ConcurrentHashMap[String, ActorRef], @@ -135,9 +133,9 @@ class LocalActorRegistry( def shutdownAll() { foreach(_.stop) if (ClusterModule.isEnabled) Actor.remote.clear //FIXME: Should this be here? - actorsByAddress.clear - actorsByUuid.clear - typedActorsByUuid.clear + actorsByAddress.clear() + actorsByUuid.clear() + typedActorsByUuid.clear() } //============== ACTORS ============== @@ -341,9 +339,7 @@ class Index[K <: AnyRef, V <: AnyRef: Manifest] { */ 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, _)) } } /** diff --git a/akka-actor/src/main/scala/akka/actor/Channel.scala b/akka-actor/src/main/scala/akka/actor/Channel.scala new file mode 100644 index 0000000000..80134f2df8 --- /dev/null +++ b/akka-actor/src/main/scala/akka/actor/Channel.scala @@ -0,0 +1,173 @@ +/** + * Copyright (C) 2009-2011 Scalable Solutions AB + */ + +package akka.actor + +/** + * Abstraction for unification of sender and senderFuture for later reply. + * Can be stored away and used at a later point in time. + * + * Channel cannot be contravariant because of Future providing its value in + * covariant position. + * + * The possible reply channel which can be passed into ! and safe_! is always + * untyped, as there is no way to utilize its real static type without + * requiring runtime-costly manifests. + */ +trait Channel[T] { + + /** + * Scala API.

+ * Sends the specified message to the channel. + */ + def !(msg: T)(implicit channel: UntypedChannel = NullChannel): Unit + + /** + * Try to send an exception. Not all channel types support this, one notable + * positive example is Future. Failure to send is silent. + */ + def sendException(ex: Throwable): Unit + + /** + * Scala API.

+ * Try to send message to the channel, return whether successful. + */ + def safe_!(msg: T)(implicit channel: UntypedChannel = NullChannel): Boolean + + /** + * Indicates whether this channel may be used only once, e.g. a Future. + */ + def isUsableOnlyOnce: Boolean + + /** + * Indicates whether this channel may still be used (only useful if + * isUsableOnlyOnce returns true). + */ + def isUsable: Boolean + + /** + * Indicates whether this channel carries reply information, e.g. an + * ActorRef. + */ + def isReplyable: Boolean + + /** + * Indicates whether this channel is capable of sending exceptions to its + * recipient. + */ + def canSendException: Boolean + + /** + * Java API.

+ * Sends the specified message to the channel, i.e. fire-and-forget semantics.

+ *

+   * actor.sendOneWay(message);
+   * 
+ */ + def sendOneWay(msg: T): Unit = this.!(msg) + + /** + * Java API.

+ * Sends the specified message to the channel, i.e. fire-and-forget + * semantics, including the sender reference if possible (not supported on + * all channels).

+ *

+   * actor.sendOneWay(message, context);
+   * 
+ */ + def sendOneWay(msg: T, sender: UntypedChannel): Unit = this.!(msg)(sender) + + /** + * Java API.

+ * Try to send the specified message to the channel, i.e. fire-and-forget semantics.

+ *

+   * actor.sendOneWay(message);
+   * 
+ */ + def sendOneWaySafe(msg: T): Boolean = this.safe_!(msg) + + /** + * Java API.

+ * Try to send the specified message to the channel, i.e. fire-and-forget + * semantics, including the sender reference if possible (not supported on + * all channels).

+ *

+   * actor.sendOneWay(message, context);
+   * 
+ */ + def sendOneWaySafe(msg: T, sender: UntypedChannel): Boolean = this.safe_!(msg)(sender) + +} + +/** + * This trait represents a channel that a priori does have sending capability, + * i.e. ! is not guaranteed to fail (e.g. NullChannel would be a + * counter-example). + */ +trait AvailableChannel[T] { self: Channel[T] ⇒ + def safe_!(msg: T)(implicit channel: UntypedChannel = NullChannel): Boolean = { + if (isUsable) { + try { + this ! msg + true + } catch { + case _ ⇒ false + } + } else false + } +} + +/** + * All channels used in conjunction with MessageInvocation are untyped by + * design, so make this explicit. + */ +trait UntypedChannel extends Channel[Any] + +object UntypedChannel { + implicit def senderOption2Channel(sender: Option[ActorRef]): UntypedChannel = + sender match { + case Some(actor) ⇒ actor + case None ⇒ NullChannel + } +} + +/** + * Default channel when none available. + */ +case object NullChannel extends UntypedChannel { + def !(msg: Any)(implicit channel: UntypedChannel = NullChannel) { + throw new IllegalActorStateException(""" + No sender in scope, can't reply. + You have probably: + 1. Sent a message to an Actor from an instance that is NOT an Actor. + 2. Invoked a method on an TypedActor from an instance NOT an TypedActor. + You may want to have a look at safe_! for a variant returning a Boolean""") + } + def safe_!(msg: Any)(implicit channel: UntypedChannel = NullChannel): Boolean = false + def sendException(ex: Throwable) {} + def isUsableOnlyOnce = false + def isUsable = false + def isReplyable = false + def canSendException = false +} + +/** + * A channel which may be forwarded: a message received with such a reply + * channel attached can be passed on transparently such that a reply from a + * later processing stage is sent directly back to the origin. Keep in mind + * that not all channels can be used multiple times. + */ +trait ForwardableChannel extends UntypedChannel with AvailableChannel[Any] { + /** + * Get channel by which this channel would reply (ActorRef.forward takes an + * implicit ForwardableChannel and uses its .channel as message origin) + */ + def channel: UntypedChannel +} + +object ForwardableChannel { + implicit def someS2FC(sender: Some[ActorRef]): ForwardableChannel = sender.get + implicit def someIS2FC(implicit sender: Some[ActorRef]): ForwardableChannel = sender.get +} + diff --git a/akka-actor/src/main/scala/akka/actor/Deployer.scala b/akka-actor/src/main/scala/akka/actor/Deployer.scala index 706cf29b6f..685197820b 100644 --- a/akka-actor/src/main/scala/akka/actor/Deployer.scala +++ b/akka-actor/src/main/scala/akka/actor/Deployer.scala @@ -13,7 +13,7 @@ import akka.actor.DeploymentConfig._ import akka.config.{ ConfigurationException, Config } import akka.routing.RouterType import akka.util.ReflectiveAccess._ -import akka.serialization.Format +import akka.serialization._ import akka.AkkaException /** @@ -31,7 +31,7 @@ object DeploymentConfig { case class Deploy( address: String, routing: Routing = Direct, - format: String = Format.defaultSerializerName, + format: String = Serializer.defaultSerializerName, // Format.defaultSerializerName, scope: Scope = Local) // -------------------------------- @@ -62,8 +62,8 @@ object DeploymentConfig { sealed trait Scope case class Clustered( home: Home = Host("localhost"), - replication: Replication = NoReplicas, - state: State = Stateful) extends Scope + replicas: Replicas = NoReplicas, + replication: ReplicationScheme = Transient) extends Scope // For Java API case class Local() extends Scope @@ -80,33 +80,60 @@ object DeploymentConfig { case class IP(ipAddress: String) extends Home // -------------------------------- - // --- Replication + // --- Replicas // -------------------------------- - sealed trait Replication - case class Replicate(factor: Int) extends Replication { - if (factor < 1) throw new IllegalArgumentException("Replication factor can not be negative or zero") + sealed trait Replicas + case class Replicate(factor: Int) extends Replicas { + if (factor < 1) throw new IllegalArgumentException("Replicas factor can not be negative or zero") } // For Java API - case class AutoReplicate() extends Replication - case class NoReplicas() extends Replication + case class AutoReplicate() extends Replicas + case class NoReplicas() extends Replicas // For Scala API - case object AutoReplicate extends Replication - case object NoReplicas extends Replication + case object AutoReplicate extends Replicas + case object NoReplicas extends Replicas // -------------------------------- - // --- State + // --- Replication // -------------------------------- - sealed trait State + sealed trait ReplicationScheme // For Java API - case class Stateless() extends State - case class Stateful() extends State + case class Transient() extends ReplicationScheme // For Scala API - case object Stateless extends State - case object Stateful extends State + case object Transient extends ReplicationScheme + case class Replication( + storage: ReplicationStorage, + strategy: ReplicationStrategy) extends ReplicationScheme + + // -------------------------------- + // --- ReplicationStorage + // -------------------------------- + sealed trait ReplicationStorage + + // For Java API + case class TransactionLog() extends ReplicationStorage + case class DataGrid() extends ReplicationStorage + + // For Scala API + case object TransactionLog extends ReplicationStorage + case object DataGrid extends ReplicationStorage + + // -------------------------------- + // --- ReplicationStrategy + // -------------------------------- + sealed trait ReplicationStrategy + + // For Java API + case class WriteBehind() extends ReplicationStrategy + case class WriteThrough() extends ReplicationStrategy + + // For Scala API + case object WriteBehind extends ReplicationStrategy + case object WriteThrough extends ReplicationStrategy // -------------------------------- // --- Helper methods for parsing @@ -114,11 +141,11 @@ object DeploymentConfig { def isHomeNode(home: Home): Boolean = home match { case Host(hostname) ⇒ hostname == Config.hostname - case IP(address) ⇒ address == "0.0.0.0" // FIXME checking if IP address is on home node is missing + case IP(address) ⇒ address == "0.0.0.0" || address == "127.0.0.1" // FIXME look up IP address from the system case Node(nodename) ⇒ nodename == Config.nodename } - def replicaValueFor(replication: Replication): Int = replication match { + def replicaValueFor(replicas: Replicas): Int = replicas match { case Replicate(replicas) ⇒ replicas case AutoReplicate ⇒ -1 case AutoReplicate() ⇒ -1 @@ -139,6 +166,12 @@ object DeploymentConfig { case LeastRAM() ⇒ RouterType.LeastRAM case LeastMessages ⇒ RouterType.LeastMessages case LeastMessages() ⇒ RouterType.LeastMessages + case c: CustomRouter ⇒ throw new UnsupportedOperationException("routerTypeFor: " + c) + } + + def isReplicationAsync(strategy: ReplicationStrategy): Boolean = strategy match { + case _: WriteBehind | WriteBehind ⇒ true + case _: WriteThrough | WriteThrough ⇒ false } } @@ -262,7 +295,7 @@ object Deployer { // -------------------------------- val addressPath = "akka.actor.deployment." + address Config.config.getSection(addressPath) match { - case None ⇒ Some(Deploy(address, Direct, Format.defaultSerializerName, Local)) + case None ⇒ Some(Deploy(address, Direct, Serializer.defaultSerializerName, Local)) case Some(addressConfig) ⇒ // -------------------------------- @@ -289,14 +322,14 @@ object Deployer { // -------------------------------- // akka.actor.deployment.
.format // -------------------------------- - val format = addressConfig.getString("format", Format.defaultSerializerName) + val format = addressConfig.getString("format", Serializer.defaultSerializerName) // -------------------------------- // akka.actor.deployment.
.clustered // -------------------------------- addressConfig.getSection("clustered") match { case None ⇒ - Some(Deploy(address, router, Format.defaultSerializerName, Local)) // deploy locally + Some(Deploy(address, router, Serializer.defaultSerializerName, Local)) // deploy locally case Some(clusteredConfig) ⇒ @@ -345,18 +378,36 @@ object Deployer { } // -------------------------------- - // akka.actor.deployment.
.clustered.stateless + // akka.actor.deployment.
.clustered.replication // -------------------------------- - val state = - if (clusteredConfig.getBool("stateless", false)) Stateless - else Stateful + clusteredConfig.getSection("replication") match { + case None ⇒ + Some(Deploy(address, router, format, Clustered(home, replicas, Transient))) - Some(Deploy(address, router, format, Clustered(home, replicas, state))) + case Some(replicationConfig) ⇒ + val storage = replicationConfig.getString("storage", "transaction-log") match { + case "transaction-log" ⇒ TransactionLog + case "data-grid" ⇒ DataGrid + case unknown ⇒ + throw new ConfigurationException("Config option [" + addressPath + + ".clustered.replication.storage] needs to be either [\"transaction-log\"] or [\"data-grid\"] - was [" + + unknown + "]") + } + val strategy = replicationConfig.getString("strategy", "write-through") match { + case "write-through" ⇒ WriteThrough + case "write-behind" ⇒ WriteBehind + case unknown ⇒ + throw new ConfigurationException("Config option [" + addressPath + + ".clustered.replication.strategy] needs to be either [\"write-through\"] or [\"write-behind\"] - was [" + + unknown + "]") + } + Some(Deploy(address, router, format, Clustered(home, replicas, Replication(storage, strategy)))) + } } } } - private def throwDeploymentBoundException(deployment: Deploy): Nothing = { + private[akka] def throwDeploymentBoundException(deployment: Deploy): Nothing = { val e = new DeploymentAlreadyBoundException( "Address [" + deployment.address + "] already bound to [" + deployment + @@ -365,7 +416,7 @@ object Deployer { throw e } - private def thrownNoDeploymentBoundException(address: String): Nothing = { + private[akka] def thrownNoDeploymentBoundException(address: String): Nothing = { val e = new NoDeploymentBoundException("Address [" + address + "] is not bound to a deployment") EventHandler.error(e, this, e.getMessage) throw e @@ -392,8 +443,7 @@ object LocalDeployer { private[akka] def deploy(deployment: Deploy) { if (deployments.putIfAbsent(deployment.address, deployment) != deployment) { - // FIXME do automatic 'undeploy' and redeploy (perhaps have it configurable if redeploy should be done or exception thrown) - // throwDeploymentBoundException(deployment) + //Deployer.throwDeploymentBoundException(deployment) // FIXME uncomment this and fix the issue with multiple deployments } } @@ -415,7 +465,8 @@ object Address { def validate(address: String) { if (validAddressPattern.matcher(address).matches) true else { - val e = new IllegalArgumentException("Address [" + address + "] is not valid, need to follow pattern [0-9a-zA-Z\\-\\_\\$]+") + val e = new IllegalArgumentException( + "Address [" + address + "] is not valid, need to follow pattern [0-9a-zA-Z\\-\\_\\$]+") EventHandler.error(e, this, e.getMessage) throw e } diff --git a/akka-actor/src/main/scala/akka/actor/FSM.scala b/akka-actor/src/main/scala/akka/actor/FSM.scala index 60e2b10c67..8317fc5fe3 100644 --- a/akka-actor/src/main/scala/akka/actor/FSM.scala +++ b/akka-actor/src/main/scala/akka/actor/FSM.scala @@ -494,10 +494,7 @@ trait FSM[S, D] extends ListenerManagement { * @return this state transition descriptor */ def replying(replyValue: Any): State = { - self.sender match { - case Some(sender) ⇒ sender ! replyValue - case None ⇒ - } + self.channel safe_! replyValue this } diff --git a/akka-actor/src/main/scala/akka/actor/Supervisor.scala b/akka-actor/src/main/scala/akka/actor/Supervisor.scala index 2d7531a33f..fbcf0862f2 100644 --- a/akka-actor/src/main/scala/akka/actor/Supervisor.scala +++ b/akka-actor/src/main/scala/akka/actor/Supervisor.scala @@ -44,7 +44,7 @@ class SupervisorException private[akka] (message: String, cause: Throwable = nul * @author Jonas Bonér */ object Supervisor { - def apply(config: SupervisorConfig): Supervisor = SupervisorFactory(config).newInstance.start + def apply(config: SupervisorConfig): Supervisor = SupervisorFactory(config).newInstance.start() } /** @@ -108,7 +108,7 @@ sealed class Supervisor(handler: FaultHandlingStrategy, maxRestartsHandler: (Act def uuid = supervisor.uuid - def start: Supervisor = { + def start(): Supervisor = { this } diff --git a/akka-actor/src/main/scala/akka/actor/TypedActor.scala b/akka-actor/src/main/scala/akka/actor/TypedActor.scala index 78f234c91a..0ba0e44d5c 100644 --- a/akka-actor/src/main/scala/akka/actor/TypedActor.scala +++ b/akka-actor/src/main/scala/akka/actor/TypedActor.scala @@ -5,13 +5,13 @@ package akka.actor */ import akka.japi.{ Creator, Option ⇒ JOption } -import akka.actor.Actor.{ actorOf, futureToAnyOptionAsTypedOption } -import akka.dispatch.{ MessageDispatcher, Dispatchers, Future } +import akka.actor.Actor._ +import akka.dispatch.{ MessageDispatcher, Dispatchers, Future, FutureTimeoutException } import java.lang.reflect.{ InvocationTargetException, Method, InvocationHandler, Proxy } import akka.util.{ Duration } import java.util.concurrent.atomic.{ AtomicReference ⇒ AtomVar } -import collection.immutable +//TODO Document this class, not only in Scaladoc, but also in a dedicated typed-actor.rst, for both java and scala object TypedActor { private val selfReference = new ThreadLocal[AnyRef] @@ -20,7 +20,7 @@ object TypedActor { case some ⇒ some } - private class TypedActor[R <: AnyRef, T <: R](val proxyRef: AtomVar[R], createInstance: ⇒ T) extends Actor { + private[akka] class TypedActor[R <: AnyRef, T <: R](val proxyRef: AtomVar[R], createInstance: ⇒ T) extends Actor { val me = createInstance def receive = { case m: MethodCall ⇒ @@ -41,24 +41,28 @@ object TypedActor { case "equals" ⇒ (args.length == 1 && (proxy eq args(0)) || actor == getActorRefFor(args(0))).asInstanceOf[AnyRef] //Force boxing of the boolean case "hashCode" ⇒ actor.hashCode.asInstanceOf[AnyRef] case _ ⇒ + implicit val timeout = Actor.Timeout(actor.timeout) MethodCall(method, args) match { case m if m.isOneWay ⇒ actor ! m null case m if m.returnsFuture_? ⇒ - actor !!! m + actor ? m case m if m.returnsJOption_? || m.returnsOption_? ⇒ - (actor !!! m).as[AnyRef] match { - case Some(null) | None ⇒ if (m.returnsJOption_?) JOption.none[Any] else None - case Some(joption) ⇒ joption + val f = actor ? m + try { f.await } catch { case _: FutureTimeoutException ⇒ } + f.value match { + case None | Some(Right(null)) ⇒ if (m.returnsJOption_?) JOption.none[Any] else None + case Some(Right(joption: AnyRef)) ⇒ joption + case Some(Left(ex)) ⇒ throw ex } case m ⇒ - (actor !!! m).get + (actor ? m).get.asInstanceOf[AnyRef] } } } - object Configuration { + object Configuration { //TODO: Replace this with the new ActorConfiguration when it exists val defaultTimeout = Duration(Actor.TIMEOUT, "millis") val defaultConfiguration = new Configuration(defaultTimeout, Dispatchers.defaultGlobalDispatcher) def apply(): Configuration = defaultConfiguration @@ -83,6 +87,8 @@ object TypedActor { } case class SerializedMethodCall(ownerType: Class[_], methodName: String, parameterTypes: Array[Class[_]], parameterValues: Array[AnyRef]) { + //TODO implement writeObject and readObject to serialize + //TODO Possible optimization is to special encode the parameter-types to conserve space private def readResolve(): AnyRef = MethodCall(ownerType.getDeclaredMethod(methodName, parameterTypes: _*), parameterValues) } @@ -157,9 +163,9 @@ object TypedActor { val proxy: T = Proxy.newProxyInstance(loader, interfaces, new TypedActorInvocationHandler(ref)).asInstanceOf[T] proxyRef.set(proxy) // Chicken and egg situation we needed to solve, set the proxy so that we can set the self-reference inside each receive - Actor.registry.registerTypedActor(ref.start, proxy) //We only have access to the proxy from the outside, so register it with the ActorRegistry, will be removed on actor.stop + Actor.registry.registerTypedActor(ref, proxy) //We only have access to the proxy from the outside, so register it with the ActorRegistry, will be removed on actor.stop proxy } private[akka] def extractInterfaces(clazz: Class[_]): Array[Class[_]] = if (clazz.isInterface) Array[Class[_]](clazz) else clazz.getInterfaces -} \ No newline at end of file +} diff --git a/akka-actor/src/main/scala/akka/cluster/ClusterInterface.scala b/akka-actor/src/main/scala/akka/cluster/ClusterInterface.scala index 7f7da6d29c..82155ebc90 100644 --- a/akka-actor/src/main/scala/akka/cluster/ClusterInterface.scala +++ b/akka-actor/src/main/scala/akka/cluster/ClusterInterface.scala @@ -7,6 +7,7 @@ package akka.cluster import akka.remoteinterface.RemoteSupport import akka.serialization.Serializer import akka.actor._ +import DeploymentConfig._ import akka.dispatch.Future import akka.config.Config import akka.util._ @@ -129,13 +130,13 @@ object NodeAddress { trait ClusterNode { import ChangeListener._ - val nodeAddress: NodeAddress - val zkServerAddresses: String + def nodeAddress: NodeAddress + def zkServerAddresses: String - val remoteClientLifeCycleListener: ActorRef - val remoteDaemon: ActorRef - val remoteService: RemoteSupport - val remoteServerAddress: InetSocketAddress + def remoteClientLifeCycleListener: ActorRef + def remoteDaemon: ActorRef + def remoteService: RemoteSupport + def remoteServerAddress: InetSocketAddress val isConnected = new Switch(false) val isLeader = new AtomicBoolean(false) @@ -179,6 +180,13 @@ trait ClusterNode { */ def store[T <: Actor](address: String, actorClass: Class[T], format: Serializer): ClusterNode + /** + * 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](address: String, actorClass: Class[T], replicationScheme: ReplicationScheme, format: Serializer): ClusterNode + /** * 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 @@ -186,6 +194,13 @@ trait ClusterNode { */ def store[T <: Actor](address: String, actorClass: Class[T], replicationFactor: Int, format: Serializer): ClusterNode + /** + * 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](address: String, actorClass: Class[T], replicationFactor: Int, replicationScheme: ReplicationScheme, format: Serializer): ClusterNode + /** * 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 @@ -193,6 +208,13 @@ trait ClusterNode { */ def store[T <: Actor](address: String, actorClass: Class[T], serializeMailbox: Boolean, format: Serializer): ClusterNode + /** + * 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](address: String, actorClass: Class[T], replicationScheme: ReplicationScheme, serializeMailbox: Boolean, format: Serializer): ClusterNode + /** * 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 @@ -200,6 +222,13 @@ trait ClusterNode { */ def store[T <: Actor](address: String, actorClass: Class[T], replicationFactor: Int, serializeMailbox: Boolean, format: Serializer): ClusterNode + /** + * 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](address: String, actorClass: Class[T], replicationFactor: Int, replicationScheme: ReplicationScheme, serializeMailbox: Boolean, format: Serializer): ClusterNode + /** * 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 @@ -207,6 +236,13 @@ trait ClusterNode { */ def store(actorRef: ActorRef, format: Serializer): ClusterNode + /** + * 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(actorRef: ActorRef, replicationScheme: ReplicationScheme, format: Serializer): ClusterNode + /** * 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 @@ -214,6 +250,13 @@ trait ClusterNode { */ def store(actorRef: ActorRef, replicationFactor: Int, format: Serializer): ClusterNode + /** + * 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(actorRef: ActorRef, replicationFactor: Int, replicationScheme: ReplicationScheme, format: Serializer): ClusterNode + /** * 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 @@ -221,11 +264,23 @@ trait ClusterNode { */ def store(actorRef: ActorRef, serializeMailbox: Boolean, format: Serializer): ClusterNode + /** + * 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(actorRef: ActorRef, replicationScheme: ReplicationScheme, serializeMailbox: Boolean, format: Serializer): ClusterNode + /** * Needed to have reflection through structural typing work. */ def store(actorRef: ActorRef, replicationFactor: Int, serializeMailbox: Boolean, format: AnyRef): ClusterNode + /** + * Needed to have reflection through structural typing work. + */ + def store(actorRef: ActorRef, replicationFactor: Int, replicationScheme: ReplicationScheme, serializeMailbox: Boolean, format: AnyRef): ClusterNode + /** * 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 @@ -233,6 +288,13 @@ trait ClusterNode { */ def store(actorRef: ActorRef, replicationFactor: Int, serializeMailbox: Boolean, format: Serializer): ClusterNode + /** + * 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(actorRef: ActorRef, replicationFactor: Int, replicationScheme: ReplicationScheme, serializeMailbox: Boolean, format: Serializer): ClusterNode + /** * Removes actor with uuid from the cluster. */ @@ -262,13 +324,13 @@ trait ClusterNode { * Checks out an actor for use on this node, e.g. checked out as a 'LocalActorRef' but it makes it available * for remote access through lookup by its UUID. */ - def use[T <: Actor](actorAddress: String): Option[LocalActorRef] + def use[T <: Actor](actorAddress: String): Option[ActorRef] /** * Checks out an actor for use on this node, e.g. checked out as a 'LocalActorRef' but it makes it available * for remote access through lookup by its UUID. */ - def use[T <: Actor](actorAddress: String, format: Serializer): Option[LocalActorRef] + def use[T <: Actor](actorAddress: String, format: Serializer): Option[ActorRef] /** * Using (checking out) all actors with a specific UUID on all nodes in the cluster. diff --git a/akka-actor/src/main/scala/akka/config/Config.scala b/akka-actor/src/main/scala/akka/config/Config.scala index 16daea4c88..d1f8412d1a 100644 --- a/akka-actor/src/main/scala/akka/config/Config.scala +++ b/akka-actor/src/main/scala/akka/config/Config.scala @@ -119,4 +119,12 @@ object Config { val startTime = System.currentTimeMillis def uptime = (System.currentTimeMillis - startTime) / 1000 + + val serializers = config.getSection("akka.actor.serializers").map(_.map).getOrElse(Map("default" -> "akka.serialization.JavaSerializer")) + + val bindings = config.getSection("akka.actor.bindings") + .map(_.map) + .map(m ⇒ Map() ++ m.map { case (k, v: List[String]) ⇒ Map() ++ v.map((_, k)) }.flatten) + + val serializerMap = bindings.map(m ⇒ m.map { case (k, v: String) ⇒ (k, serializers(v)) }).getOrElse(Map()) } diff --git a/akka-actor/src/main/scala/akka/dispatch/BalancingDispatcher.scala b/akka-actor/src/main/scala/akka/dispatch/BalancingDispatcher.scala index 0460720a73..98b7465e5a 100644 --- a/akka-actor/src/main/scala/akka/dispatch/BalancingDispatcher.scala +++ b/akka-actor/src/main/scala/akka/dispatch/BalancingDispatcher.scala @@ -129,10 +129,7 @@ class BalancingDispatcher( */ protected def donate(organ: MessageInvocation, recipient: ActorRef): Boolean = { if (organ ne null) { - if (organ.senderFuture.isDefined) recipient.postMessageToMailboxAndCreateFutureResultWithTimeout[Any]( - organ.message, recipient.timeout, organ.sender, organ.senderFuture) - else if (organ.sender.isDefined) recipient.postMessageToMailbox(organ.message, organ.sender) - else recipient.postMessageToMailbox(organ.message, None) + recipient.postMessageToMailbox(organ.message, organ.channel) true } else false } diff --git a/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala b/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala index ab2287a589..d00b579610 100644 --- a/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala +++ b/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala @@ -5,10 +5,9 @@ package akka.dispatch import akka.event.EventHandler -import akka.actor.{ ActorRef } - import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.{ TimeUnit, ExecutorService, RejectedExecutionException, ConcurrentLinkedQueue } +import akka.actor.{ ActorKilledException, ActorRef } /** * Default settings are: @@ -111,6 +110,8 @@ class Dispatcher( */ protected def getMailbox(receiver: ActorRef) = receiver.mailbox.asInstanceOf[MessageQueue with ExecutableMailbox] + def mailboxIsEmpty(actorRef: ActorRef): Boolean = getMailbox(actorRef).isEmpty + override def mailboxSize(actorRef: ActorRef) = getMailbox(actorRef).size def createMailbox(actorRef: ActorRef): AnyRef = mailboxType match { @@ -159,6 +160,18 @@ class Dispatcher( private[akka] def reRegisterForExecution(mbox: MessageQueue with ExecutableMailbox): Unit = registerForExecution(mbox) + protected override def cleanUpMailboxFor(actorRef: ActorRef) { + val m = getMailbox(actorRef) + if (!m.isEmpty) { + var invocation = m.dequeue + lazy val exception = new ActorKilledException("Actor has been stopped") + while (invocation ne null) { + invocation.channel.sendException(exception) + invocation = m.dequeue + } + } + } + override val toString = getClass.getSimpleName + "[" + name + "]" def suspend(actorRef: ActorRef) { diff --git a/akka-actor/src/main/scala/akka/dispatch/Future.scala b/akka-actor/src/main/scala/akka/dispatch/Future.scala index e431503727..c45068a2f2 100644 --- a/akka-actor/src/main/scala/akka/dispatch/Future.scala +++ b/akka-actor/src/main/scala/akka/dispatch/Future.scala @@ -6,8 +6,8 @@ package akka.dispatch import akka.AkkaException import akka.event.EventHandler -import akka.actor.{ Actor, Channel } -import akka.util.Duration +import akka.actor.{ Actor, Channel, ForwardableChannel, NullChannel, UntypedChannel, ActorRef } +import akka.util.{ Duration, BoxedType } import akka.japi.{ Procedure, Function ⇒ JFunc } import scala.util.continuations._ @@ -217,19 +217,6 @@ object Future { def apply[T](body: ⇒ T, timeout: Long = Actor.TIMEOUT)(implicit dispatcher: MessageDispatcher): Future[T] = dispatcher.dispatchFuture(() ⇒ body, timeout) - /** - * Construct a completable channel - */ - def channel(timeout: Long = Actor.TIMEOUT) = new Channel[Any] { - val future = empty[Any](timeout) - def !(msg: Any) = future completeWithResult msg - } - - /** - * Create an empty Future with default timeout - */ - def empty[T](timeout: Long = Actor.TIMEOUT) = new DefaultPromise[T](timeout) - import scala.collection.mutable.Builder import scala.collection.generic.CanBuildFrom @@ -272,9 +259,11 @@ object Future { */ def flow[A](body: ⇒ A @cps[Future[Any]], timeout: Long = Actor.TIMEOUT): Future[A] = { val future = Promise[A](timeout) - (reset(future.asInstanceOf[Promise[Any]].completeWithResult(body)): Future[Any]) onComplete { f ⇒ - val opte = f.exception - if (opte.isDefined) future completeWithException (opte.get) + (reset(future.asInstanceOf[Promise[Any]].completeWithResult(body)): Future[Any]) onComplete { + _.exception match { + case Some(e) ⇒ future completeWithException e + case None ⇒ + } } future } @@ -289,7 +278,7 @@ sealed trait Future[+T] { * continuation until the result is available. * * If this Future is untyped (a Future[Nothing]), a type parameter must be explicitly provided or - * execution will fail. The normal result of getting a Future from an ActorRef using !!! will return + * 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])) @@ -320,12 +309,21 @@ sealed trait Future[+T] { def await(atMost: Duration): Future[T] /** - * Blocks the current thread until the Future has been completed. Use - * caution with this method as it ignores the timeout and will block - * indefinitely if the Future is never completed. + * Await completion of this Future (as `await`) and return its value if it + * conforms to A's erased type. + * + * def as[A](implicit m: Manifest[A]): Option[A] = + * try { + * await + * value match { + * case None ⇒ None + * case Some(_: Left[_, _]) ⇒ None + * case Some(Right(v)) ⇒ Some(BoxedType(m.erasure).cast(v).asInstanceOf[A]) + * } + * } catch { + * case _: Exception ⇒ None + * } */ - @deprecated("Will be removed after 1.1, it's dangerous and can cause deadlocks, agony and insanity.", "1.1") - def awaitBlocking: Future[T] /** * Tests whether this Future has been completed. @@ -376,23 +374,41 @@ 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): this.type /** * When the future is completed with a valid result, apply the provided * PartialFunction to the result. *
-   *   val result = future receive {
+   *   val result = future onResult {
    *     case Foo => "foo"
    *     case Bar => "bar"
-   *   }.await.result
+   *   }
    * 
*/ - final def receive(pf: PartialFunction[Any, Unit]): Future[T] = onComplete { f ⇒ + final def onResult(pf: PartialFunction[Any, Unit]): this.type = onComplete { f ⇒ val optr = f.result if (optr.isDefined) { val r = optr.get - if (pf.isDefinedAt(r)) pf(r) + if (pf isDefinedAt r) pf(r) + } + } + + /** + * When the future is completed with an exception, apply the provided + * PartialFunction to the exception. + *
+   *   val result = future onException {
+   *     case Foo => "foo"
+   *     case Bar => "bar"
+   *   }
+   * 
+ */ + final def onException(pf: PartialFunction[Throwable, Unit]): Future[T] = onComplete { f ⇒ + val opte = f.exception + if (opte.isDefined) { + val e = opte.get + if (pf isDefinedAt e) pf(e) } } @@ -404,9 +420,9 @@ sealed trait Future[+T] { * Example: *
    * val future1 = for {
-   *   a <- actor !!! Req("Hello") collect { case Res(x: Int)    => x }
-   *   b <- actor !!! Req(a)       collect { case Res(x: String) => x }
-   *   c <- actor !!! Req(7)       collect { case Res(x: String) => x }
+   *   a <- actor ? Req("Hello") collect { case Res(x: Int)    => x }
+   *   b <- actor ? Req(a)       collect { case Res(x: String) => x }
+   *   c <- actor ? Req(7)       collect { case Res(x: String) => x }
    * } yield b + "-" + c
    * 
*/ @@ -418,12 +434,12 @@ sealed trait Future[+T] { * a valid result then the new Future will contain the same. * Example: *
-   * Future(6 / 0) failure { case e: ArithmeticException => 0 } // result: 0
-   * Future(6 / 0) failure { case e: NotFoundException   => 0 } // result: exception
-   * Future(6 / 2) failure { case e: ArithmeticException => 0 } // result: 3
+   * Future(6 / 0) recover { case e: ArithmeticException => 0 } // result: 0
+   * Future(6 / 0) recover { case e: NotFoundException   => 0 } // result: exception
+   * Future(6 / 2) recover { case e: ArithmeticException => 0 } // result: 3
    * 
*/ - def failure[A >: T](pf: PartialFunction[Throwable, A]): Future[A] + def recover[A >: T](pf: PartialFunction[Throwable, A]): Future[A] /** * Creates a new Future by applying a function to the successful result of @@ -432,14 +448,34 @@ sealed trait Future[+T] { * Example: *
    * val future1 = for {
-   *   a: Int    <- actor !!! "Hello" // returns 5
-   *   b: String <- actor !!! a       // returns "10"
-   *   c: String <- actor !!! 7       // returns "14"
+   *   a: Int    <- actor ? "Hello" // returns 5
+   *   b: String <- actor ? a       // returns "10"
+   *   c: String <- actor ? 7       // returns "14"
    * } yield b + "-" + c
    * 
*/ def map[A](f: T ⇒ A): Future[A] + /** + * Creates a new Future[A] which is completed with this Future's result if + * that conforms to A's erased type or a ClassCastException otherwise. + */ + final def mapTo[A](implicit m: Manifest[A]): Future[A] = { + val fa = new DefaultPromise[A](timeoutInNanos, NANOS) + onComplete { ft ⇒ + fa complete (ft.value.get match { + case l: Left[_, _] ⇒ l.asInstanceOf[Either[Throwable, A]] + case Right(t) ⇒ + try { + Right(BoxedType(m.erasure).cast(t).asInstanceOf[A]) + } catch { + case e: ClassCastException ⇒ Left(e) + } + }) + } + fa + } + /** * Creates a new Future by applying a function to the successful result of * this Future, and returns the result of the function as the new Future. @@ -448,21 +484,31 @@ sealed trait Future[+T] { * Example: *
    * val future1 = for {
-   *   a: Int    <- actor !!! "Hello" // returns 5
-   *   b: String <- actor !!! a       // returns "10"
-   *   c: String <- actor !!! 7       // returns "14"
+   *   a: Int    <- actor ? "Hello" // returns 5
+   *   b: String <- actor ? a       // returns "10"
+   *   c: String <- actor ? 7       // returns "14"
    * } yield b + "-" + c
    * 
*/ def flatMap[A](f: T ⇒ Future[A]): Future[A] - final def foreach(f: T ⇒ Unit): Unit = onComplete { ft ⇒ - val optr = ft.result - if (optr.isDefined) - f(optr.get) + final def foreach(f: T ⇒ Unit): Unit = onComplete { + _.result match { + case Some(v) ⇒ f(v) + case None ⇒ + } } - def filter(p: Any ⇒ Boolean): Future[Any] + final def withFilter(p: T ⇒ Boolean) = new FutureWithFilter[T](this, p) + + final class FutureWithFilter[+A](self: Future[A], p: A ⇒ Boolean) { + def foreach(f: A ⇒ Unit): Unit = self filter p foreach f + def map[B](f: A ⇒ B): Future[B] = self filter p map f + def flatMap[B](f: A ⇒ Future[B]): Future[B] = self filter p flatMap f + def withFilter(q: A ⇒ Boolean): FutureWithFilter[A] = new FutureWithFilter[A](self, x ⇒ p(x) && q(x)) + } + + def filter(p: T ⇒ Boolean): Future[T] /** * Returns the current result, throws the exception is one has been raised, else returns None @@ -477,7 +523,7 @@ sealed trait Future[+T] { } /* Java API */ - final def onComplete[A >: T](proc: Procedure[Future[A]]): Future[T] = onComplete(proc(_)) + final def onComplete[A >: T](proc: Procedure[Future[A]]): this.type = onComplete(proc(_)) final def map[A >: T, B](f: JFunc[A, B]): Future[B] = map(f(_)) @@ -495,6 +541,11 @@ object Promise { def apply[A](): Promise[A] = apply(Actor.TIMEOUT) + /** + * Construct a completable channel + */ + def channel(timeout: Long = Actor.TIMEOUT): ActorPromise = new ActorPromise(timeout) + private[akka] val callbacksPendingExecution = new ThreadLocal[Option[Stack[() ⇒ Unit]]]() { override def initialValue = None } @@ -508,26 +559,26 @@ trait Promise[T] extends Future[T] { * Completes this Future with the specified result, if not already completed. * @return this */ - def complete(value: Either[Throwable, T]): Future[T] + def complete(value: Either[Throwable, T]): this.type /** * Completes this Future with the specified result, if not already completed. * @return this */ - final def completeWithResult(result: T): Future[T] = complete(Right(result)) + final def completeWithResult(result: T): this.type = complete(Right(result)) /** * Completes this Future with the specified exception, if not already completed. * @return this */ - final def completeWithException(exception: Throwable): Future[T] = complete(Left(exception)) + final def completeWithException(exception: Throwable): this.type = complete(Left(exception)) /** * Completes this Future with the specified other Future, when that Future is completed, * unless this Future has already been completed. * @return this. */ - final def completeWith(other: Future[T]): Future[T] = { + final def completeWith(other: Future[T]): this.type = { other onComplete { f ⇒ complete(f.value.get) } this } @@ -611,18 +662,6 @@ class DefaultPromise[T](timeout: Long, timeunit: TimeUnit) extends Promise[T] { else throw new FutureTimeoutException("Futures timed out after [" + NANOS.toMillis(timeoutInNanos) + "] milliseconds") } - def awaitBlocking = { - _lock.lock - try { - while (_value.isEmpty) { - _signal.await - } - this - } finally { - _lock.unlock - } - } - def isExpired: Boolean = timeLeft() <= 0 def value: Option[Either[Throwable, T]] = { @@ -634,14 +673,19 @@ class DefaultPromise[T](timeout: Long, timeunit: TimeUnit) extends Promise[T] { } } - def complete(value: Either[Throwable, T]): DefaultPromise[T] = { + def complete(value: Either[Throwable, T]): this.type = { _lock.lock val notifyTheseListeners = try { - if (_value.isEmpty && !isExpired) { //Only complete if we aren't expired - _value = Some(value) - val existingListeners = _listeners - _listeners = Nil - existingListeners + if (_value.isEmpty) { //Only complete if we aren't expired + if (!isExpired) { + _value = Some(value) + val existingListeners = _listeners + _listeners = Nil + existingListeners + } else { + _listeners = Nil + Nil + } } else Nil } finally { _signal.signalAll @@ -676,7 +720,7 @@ class DefaultPromise[T](timeout: Long, timeunit: TimeUnit) extends Promise[T] { this } - def onComplete(func: Future[T] ⇒ Unit): Promise[T] = { + def onComplete(func: Future[T] ⇒ Unit): this.type = { _lock.lock val notifyNow = try { if (_value.isEmpty) { @@ -723,7 +767,7 @@ class DefaultPromise[T](timeout: Long, timeunit: TimeUnit) extends Promise[T] { future } - final def failure[A >: T](pf: PartialFunction[Throwable, A]): Future[A] = { + final def recover[A >: T](pf: PartialFunction[Throwable, A]): Future[A] = { val future = new DefaultPromise[A](timeoutInNanos, NANOS) onComplete { self ⇒ future complete { @@ -734,7 +778,6 @@ class DefaultPromise[T](timeout: Long, timeunit: TimeUnit) extends Promise[T] { else Left(e) } catch { case x: Exception ⇒ - EventHandler.error(e, this, e.getMessage) Left(x) } case v ⇒ v @@ -782,7 +825,7 @@ class DefaultPromise[T](timeout: Long, timeunit: TimeUnit) extends Promise[T] { future } - final def filter(p: Any ⇒ Boolean): Future[Any] = { + final def filter(p: T ⇒ Boolean): Future[T] = { val future = new DefaultPromise[T](timeoutInNanos, NANOS) onComplete { self ⇒ future complete { @@ -811,6 +854,36 @@ class DefaultPromise[T](timeout: Long, timeunit: TimeUnit) extends Promise[T] { private def timeLeft(): Long = timeoutInNanos - (currentTimeInNanos - _startTimeInNanos) } +class ActorPromise(timeout: Long, timeunit: TimeUnit) + extends DefaultPromise[Any](timeout, timeunit) + with ForwardableChannel { + def this() = this(0, MILLIS) + def this(timeout: Long) = this(timeout, MILLIS) + + def !(message: Any)(implicit channel: UntypedChannel = NullChannel) = completeWithResult(message) + + def sendException(ex: Throwable) = completeWithException(ex) + + def channel: UntypedChannel = this + + def isUsableOnlyOnce = true + def isUsable = !isCompleted + def isReplyable = false + def canSendException = true + + @deprecated("ActorPromise merged with Channel[Any], just use 'this'", "1.2") + def future = this +} + +object ActorPromise { + def apply(f: Promise[Any]): ActorPromise = + new ActorPromise(f.timeoutInNanos, NANOS) { + completeWith(f) + override def !(message: Any)(implicit channel: UntypedChannel) = f completeWithResult message + override def sendException(ex: Throwable) = f completeWithException ex + } +} + /** * An already completed Future is seeded with it's result at creation, is useful for when you are participating in * a Future-composition but you already have a value to contribute. @@ -818,11 +891,10 @@ class DefaultPromise[T](timeout: Long, timeunit: TimeUnit) extends Promise[T] { sealed class KeptPromise[T](suppliedValue: Either[Throwable, T]) extends Promise[T] { val value = Some(suppliedValue) - def complete(value: Either[Throwable, T]): Promise[T] = 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 complete(value: Either[Throwable, T]): this.type = this + def onComplete(func: Future[T] ⇒ Unit): this.type = { func(this); this } + def await(atMost: Duration): this.type = this + def await: this.type = this def isExpired: Boolean = true def timeoutInNanos: Long = 0 @@ -841,7 +913,7 @@ sealed class KeptPromise[T](suppliedValue: Either[Throwable, T]) extends Promise case _ ⇒ this.asInstanceOf[KeptPromise[A]] } - final def failure[A >: T](pf: PartialFunction[Throwable, A]): Future[A] = value.get match { + final def recover[A >: T](pf: PartialFunction[Throwable, A]): Future[A] = value.get match { case Left(e) ⇒ try { if (pf isDefinedAt e) @@ -880,7 +952,7 @@ sealed class KeptPromise[T](suppliedValue: Either[Throwable, T]) extends Promise case _ ⇒ this.asInstanceOf[KeptPromise[A]] } - final def filter(p: Any ⇒ Boolean): Future[Any] = value.get match { + final def filter(p: T ⇒ Boolean): Future[T] = value.get match { case Right(r) ⇒ try { if (p(r)) diff --git a/akka-actor/src/main/scala/akka/dispatch/MessageHandling.scala b/akka-actor/src/main/scala/akka/dispatch/MessageHandling.scala index f5cda388c2..b5c50ea939 100644 --- a/akka-actor/src/main/scala/akka/dispatch/MessageHandling.scala +++ b/akka-actor/src/main/scala/akka/dispatch/MessageHandling.scala @@ -16,19 +16,13 @@ import akka.actor._ /** * @author Jonas Bonér */ -final case class MessageInvocation(receiver: ActorRef, - message: Any, - sender: Option[ActorRef], - senderFuture: Option[Promise[Any]]) { +final case class MessageInvocation(val receiver: ActorRef, + val message: Any, + val channel: UntypedChannel) { if (receiver eq null) throw new IllegalArgumentException("Receiver can't be null") - def invoke() { - try { - receiver.invoke(this) - } catch { - 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 def invoke() { + receiver invoke this } } @@ -147,6 +141,7 @@ trait MessageDispatcher { private[akka] def unregister(actorRef: ActorRef) = { if (uuids remove actorRef.uuid) { + cleanUpMailboxFor(actorRef) actorRef.mailbox = null if (uuids.isEmpty && futures.get == 0) { shutdownSchedule match { @@ -161,6 +156,12 @@ trait MessageDispatcher { } } + /** + * Overridable callback to clean up the mailbox for a given actor, + * called when an actor is unregistered. + */ + protected def cleanUpMailboxFor(actorRef: ActorRef) {} + /** * Traverses the list of actors (uuids) currently being attached to this dispatcher and stops those actors */ @@ -170,7 +171,7 @@ trait MessageDispatcher { val uuid = i.next() Actor.registry.local.actorFor(uuid) match { case Some(actor) ⇒ actor.stop() - case None ⇒ {} + case None ⇒ } } } @@ -233,6 +234,11 @@ trait MessageDispatcher { */ def mailboxSize(actorRef: ActorRef): Int + /** + * Returns the "current" emptiness status of the mailbox for the specified actor + */ + def mailboxIsEmpty(actorRef: ActorRef): Boolean + /** * Returns the amount of futures queued for execution */ diff --git a/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala b/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala index f260cf39b4..b1c0f6e747 100644 --- a/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala +++ b/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala @@ -154,7 +154,7 @@ class MonitorableThreadFactory(val name: String) extends ThreadFactory { * @author Jonas Bonér */ object MonitorableThread { - val DEFAULT_NAME = "MonitorableThread" + val DEFAULT_NAME = "MonitorableThread".intern // FIXME use MonitorableThread.created and MonitorableThread.alive in monitoring val created = new AtomicInteger diff --git a/akka-actor/src/main/scala/akka/package.scala b/akka-actor/src/main/scala/akka/package.scala new file mode 100644 index 0000000000..269e3e068e --- /dev/null +++ b/akka-actor/src/main/scala/akka/package.scala @@ -0,0 +1,39 @@ +/** + * Copyright (C) 2009-2011 Scalable Solutions AB + */ + +import akka.dispatch.{ FutureTimeoutException, Future } +import akka.util.Helpers.{ narrow, narrowSilently } + +package object akka { + /** + * Implicitly converts the given Option[Any] to a AnyOptionAsTypedOption which offers the method as[T] + * to convert an Option[Any] to an Option[T]. + */ + implicit def toAnyOptionAsTypedOption(anyOption: Option[Any]) = new AnyOptionAsTypedOption(anyOption) + + /** + * Implicitly converts the given Future[_] to a AnyOptionAsTypedOption which offers the method as[T] + * to convert an Option[Any] to an Option[T]. + * This means that the following code is equivalent: + * (actor ? "foo").as[Int] (Recommended) + */ + implicit def futureToAnyOptionAsTypedOption(anyFuture: Future[_]) = new AnyOptionAsTypedOption({ + try { anyFuture.await } catch { case t: FutureTimeoutException ⇒ } + anyFuture.resultOrException + }) + + private[akka] class AnyOptionAsTypedOption(anyOption: Option[Any]) { + /** + * Convenience helper to cast the given Option of Any to an Option of the given type. Will throw a ClassCastException + * if the actual type is not assignable from the given one. + */ + def as[T]: Option[T] = narrow[T](anyOption) + + /** + * Convenience helper to cast the given Option of Any to an Option of the given type. Will swallow a possible + * ClassCastException and return None in that case. + */ + def asSilently[T: Manifest]: Option[T] = narrowSilently[T](anyOption) + } +} diff --git a/akka-actor/src/main/scala/akka/routing/Pool.scala b/akka-actor/src/main/scala/akka/routing/Pool.scala index c036616521..249d087ed6 100644 --- a/akka-actor/src/main/scala/akka/routing/Pool.scala +++ b/akka-actor/src/main/scala/akka/routing/Pool.scala @@ -5,6 +5,7 @@ package akka.routing import akka.actor.{ Actor, ActorRef, PoisonPill } +import akka.dispatch.{ Promise } /** * Actor pooling @@ -116,7 +117,7 @@ trait SmallestMailboxSelector { var take = if (partialFill) math.min(selectionCount, delegates.length) else selectionCount while (take > 0) { - set = delegates.sortWith(_.mailboxSize < _.mailboxSize).take(take) ++ set //Question, doesn't this risk selecting the same actor multiple times? + set = delegates.sortWith((a, b) ⇒ a.dispatcher.mailboxSize(a) < b.dispatcher.mailboxSize(b)).take(take) ++ set //Question, doesn't this risk selecting the same actor multiple times? take -= set.size } @@ -187,7 +188,7 @@ trait BoundedCapacitor { trait MailboxPressureCapacitor { def pressureThreshold: Int def pressure(delegates: Seq[ActorRef]): Int = - delegates count { _.mailboxSize > pressureThreshold } + delegates count { a ⇒ a.dispatcher.mailboxSize(a) > pressureThreshold } } /** @@ -195,7 +196,7 @@ trait MailboxPressureCapacitor { */ trait ActiveFuturesPressureCapacitor { def pressure(delegates: Seq[ActorRef]): Int = - delegates count { _.senderFuture.isDefined } + delegates count { _.channel.isInstanceOf[Promise[Any]] } } /** diff --git a/akka-actor/src/main/scala/akka/routing/Routing.scala b/akka-actor/src/main/scala/akka/routing/Routing.scala index 83fd45a5cb..e707e23f23 100644 --- a/akka-actor/src/main/scala/akka/routing/Routing.scala +++ b/akka-actor/src/main/scala/akka/routing/Routing.scala @@ -90,8 +90,6 @@ trait LoadBalancer extends Router { self: Actor ⇒ } override def broadcast(message: Any) = seq.items.foreach(_ ! message) - - override def isDefinedAt(msg: Any) = seq.exists(_.isDefinedAt(msg)) } /** @@ -106,8 +104,6 @@ abstract class UntypedLoadBalancer extends UntypedRouter { else null override def broadcast(message: Any) = seq.items.foreach(_ ! message) - - override def isDefinedAt(msg: Any) = seq.exists(_.isDefinedAt(msg)) } object Routing { @@ -210,7 +206,7 @@ case class SmallestMailboxFirstIterator(val items: Seq[ActorRef]) extends Infini 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.dispatcher.mailboxSize(a1) < a2.dispatcher.mailboxSize(a2)) a1 else a2) override def exists(f: ActorRef ⇒ Boolean): Boolean = items.exists(f) } diff --git a/akka-actor/src/main/scala/akka/serialization/Format.scala b/akka-actor/src/main/scala/akka/serialization/Format.scala index 40b0d5dbc2..0e221c9b01 100644 --- a/akka-actor/src/main/scala/akka/serialization/Format.scala +++ b/akka-actor/src/main/scala/akka/serialization/Format.scala @@ -10,44 +10,44 @@ import java.io.{ ObjectOutputStream, ByteArrayOutputStream, ObjectInputStream, B /** * @author Jonas Bonér + * trait Serializer extends scala.Serializable { + * @volatile + * var classLoader: Option[ClassLoader] = None + * def deepClone(obj: AnyRef): AnyRef = fromBinary(toBinary(obj), Some(obj.getClass)) + * + * def toBinary(obj: AnyRef): Array[Byte] + * def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef + * } */ -trait Serializer extends scala.Serializable { - @volatile - var classLoader: Option[ClassLoader] = None - def deepClone(obj: AnyRef): AnyRef = fromBinary(toBinary(obj), Some(obj.getClass)) - - def toBinary(obj: AnyRef): Array[Byte] - def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef -} /** * + * object Format { + * implicit object Default extends Serializer { + * import java.io.{ ObjectOutputStream, ByteArrayOutputStream, ObjectInputStream, ByteArrayInputStream } + * //import org.apache.commons.io.input.ClassLoaderObjectInputStream + * + * def toBinary(obj: AnyRef): Array[Byte] = { + * val bos = new ByteArrayOutputStream + * val out = new ObjectOutputStream(bos) + * out.writeObject(obj) + * out.close() + * bos.toByteArray + * } + * + * def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]], classLoader: Option[ClassLoader] = None): AnyRef = { + * val in = + * //if (classLoader.isDefined) new ClassLoaderObjectInputStream(classLoader.get, new ByteArrayInputStream(bytes)) else + * new ObjectInputStream(new ByteArrayInputStream(bytes)) + * val obj = in.readObject + * in.close() + * obj + * } + * } + * + * val defaultSerializerName = Default.getClass.getName + * } */ -object Format { - implicit object Default extends Serializer { - import java.io.{ ObjectOutputStream, ByteArrayOutputStream, ObjectInputStream, ByteArrayInputStream } - //import org.apache.commons.io.input.ClassLoaderObjectInputStream - - def toBinary(obj: AnyRef): Array[Byte] = { - val bos = new ByteArrayOutputStream - val out = new ObjectOutputStream(bos) - out.writeObject(obj) - out.close() - bos.toByteArray - } - - def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = { - val in = - //if (classLoader.isDefined) new ClassLoaderObjectInputStream(classLoader.get, new ByteArrayInputStream(bytes)) else - new ObjectInputStream(new ByteArrayInputStream(bytes)) - val obj = in.readObject - in.close() - obj - } - } - - val defaultSerializerName = Default.getClass.getName -} trait FromBinary[T <: Actor] { def fromBinary(bytes: Array[Byte], act: T): T diff --git a/akka-actor/src/main/scala/akka/serialization/Serialization.scala b/akka-actor/src/main/scala/akka/serialization/Serialization.scala new file mode 100644 index 0000000000..c1859f120b --- /dev/null +++ b/akka-actor/src/main/scala/akka/serialization/Serialization.scala @@ -0,0 +1,71 @@ +package akka.serialization + +/** + * Copyright (C) 2009-2011 Scalable Solutions AB + */ + +import akka.util.ReflectiveAccess._ +import akka.config.Config +import akka.config.Config._ +import akka.actor.{ ActorRef, Actor } + +object Serialization { + case class NoSerializerFoundException(m: String) extends Exception(m) + + def serialize(o: AnyRef): Either[Exception, Array[Byte]] = + getSerializer(o.getClass).fold((ex) ⇒ Left(ex), (ser) ⇒ Right(ser.toBinary(o))) + + def deserialize( + bytes: Array[Byte], + clazz: Class[_], + classLoader: Option[ClassLoader]): Either[Exception, AnyRef] = + getSerializer(clazz) + .fold((ex) ⇒ Left(ex), + (ser) ⇒ Right(ser.fromBinary(bytes, Some(clazz), classLoader))) + + def getSerializer(clazz: Class[_]): Either[Exception, Serializer] = { + Config.serializerMap.get(clazz.getName) match { + case Some(serializerName: String) ⇒ + getClassFor(serializerName) match { + case Right(serializer) ⇒ Right(serializer.newInstance.asInstanceOf[Serializer]) + case Left(exception) ⇒ Left(exception) + } + case _ ⇒ + getDefaultSerializer match { + case Some(s: Serializer) ⇒ Right(s) + case None ⇒ Left(new Exception("No default serializer found for " + clazz)) + } + } + } + + private def getDefaultSerializer = { + Config.serializers.get("default") match { + case Some(ser: String) ⇒ + getClassFor(ser) match { + case Right(srializer) ⇒ Some(srializer.newInstance.asInstanceOf[Serializer]) + case Left(exception) ⇒ None + } + case None ⇒ None + } + } + + private def getSerializerInstanceForBestMatchClass( + configMap: collection.mutable.Map[String, String], + cl: Class[_]) = { + configMap + .find { + case (clazzName, ser) ⇒ + getClassFor(clazzName) match { + case Right(clazz) ⇒ clazz.isAssignableFrom(cl) + case _ ⇒ false + } + } + .map { + case (_, ser) ⇒ + getClassFor(ser) match { + case Right(s) ⇒ Right(s.newInstance.asInstanceOf[Serializer]) + case _ ⇒ Left(new Exception("Error instantiating " + ser)) + } + }.getOrElse(Left(NoSerializerFoundException("No mapping serializer found for " + cl))) + } +} diff --git a/akka-actor/src/main/scala/akka/serialization/Serializer.scala b/akka-actor/src/main/scala/akka/serialization/Serializer.scala new file mode 100644 index 0000000000..7ac3eea2df --- /dev/null +++ b/akka-actor/src/main/scala/akka/serialization/Serializer.scala @@ -0,0 +1,39 @@ +package akka.serialization + +/** + * Copyright (C) 2009-2011 Scalable Solutions AB + */ + +import java.io.{ ObjectOutputStream, ByteArrayOutputStream, ObjectInputStream, ByteArrayInputStream } +import akka.util.ClassLoaderObjectInputStream +import akka.actor.ActorRef + +trait Serializer extends scala.Serializable { + def toBinary(o: AnyRef): Array[Byte] + def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]] = None, classLoader: Option[ClassLoader] = None): AnyRef +} + +class JavaSerializer extends Serializer { + def toBinary(o: AnyRef): Array[Byte] = { + val bos = new ByteArrayOutputStream + val out = new ObjectOutputStream(bos) + out.writeObject(o) + out.close() + bos.toByteArray + } + + def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]] = None, + classLoader: Option[ClassLoader] = None): AnyRef = { + val in = + if (classLoader.isDefined) new ClassLoaderObjectInputStream(classLoader.get, new ByteArrayInputStream(bytes)) else + new ObjectInputStream(new ByteArrayInputStream(bytes)) + val obj = in.readObject + in.close() + obj + } +} + +object JavaSerializer extends JavaSerializer +object Serializer { + val defaultSerializerName = JavaSerializer.getClass.getName +} diff --git a/akka-actor/src/main/scala/akka/util/BoxedType.scala b/akka-actor/src/main/scala/akka/util/BoxedType.scala new file mode 100644 index 0000000000..7bcacaa5f9 --- /dev/null +++ b/akka-actor/src/main/scala/akka/util/BoxedType.scala @@ -0,0 +1,25 @@ +/** + * Copyright (C) 2009-2011 Scalable Solutions AB + */ +package akka.util + +import java.{ lang ⇒ jl } + +object BoxedType { + + private val toBoxed = Map[Class[_], Class[_]]( + classOf[Boolean] -> classOf[jl.Boolean], + classOf[Byte] -> classOf[jl.Byte], + classOf[Char] -> classOf[jl.Character], + classOf[Short] -> classOf[jl.Short], + classOf[Int] -> classOf[jl.Integer], + classOf[Long] -> classOf[jl.Long], + classOf[Float] -> classOf[jl.Float], + classOf[Double] -> classOf[jl.Double], + classOf[Unit] -> classOf[scala.runtime.BoxedUnit]) + + def apply(c: Class[_]): Class[_] = { + if (c.isPrimitive) toBoxed(c) else c + } + +} diff --git a/akka-actor/src/main/scala/akka/util/ClassLoaderObjectInputStream.scala b/akka-actor/src/main/scala/akka/util/ClassLoaderObjectInputStream.scala new file mode 100644 index 0000000000..1749c118d0 --- /dev/null +++ b/akka-actor/src/main/scala/akka/util/ClassLoaderObjectInputStream.scala @@ -0,0 +1,16 @@ +/** + * Copyright (C) 2009-2011 Scalable Solutions AB + */ + +package akka.util + +import java.io.{ InputStream, ObjectInputStream, ObjectStreamClass } + +class ClassLoaderObjectInputStream(classLoader: ClassLoader, is: InputStream) extends ObjectInputStream(is) { + override protected def resolveClass(objectStreamClass: ObjectStreamClass): Class[_] = { + Class.forName(objectStreamClass.getName, false, classLoader) match { + case null ⇒ super.resolveClass(objectStreamClass) + case clazz ⇒ clazz + } + } +} diff --git a/akka-actor/src/main/scala/akka/util/ReflectiveAccess.scala b/akka-actor/src/main/scala/akka/util/ReflectiveAccess.scala index a75d65ddd9..42fd88a78f 100644 --- a/akka-actor/src/main/scala/akka/util/ReflectiveAccess.scala +++ b/akka-actor/src/main/scala/akka/util/ReflectiveAccess.scala @@ -8,7 +8,7 @@ import akka.dispatch.{ Future, Promise, MessageInvocation } import akka.config.{ Config, ModuleNotAvailableException } import akka.remoteinterface.RemoteSupport import akka.actor._ -import DeploymentConfig.Deploy +import DeploymentConfig.{ Deploy, ReplicationScheme, ReplicationStrategy } import akka.event.EventHandler import akka.serialization.Format import akka.cluster.ClusterNode @@ -62,6 +62,13 @@ object ReflectiveAccess { None } + lazy val transactionLogInstance: Option[TransactionLogObject] = getObjectFor("akka.cluster.TransactionLog$") match { + case Right(value) ⇒ Some(value) + case Left(exception) ⇒ + EventHandler.debug(this, exception.toString) + None + } + lazy val node: ClusterNode = { ensureEnabled() clusterInstance.get.node @@ -72,6 +79,11 @@ object ReflectiveAccess { clusterDeployerInstance.get } + lazy val transactionLog: TransactionLogObject = { + ensureEnabled() + transactionLogInstance.get + } + type ClusterDeployer = { def init(deployments: List[Deploy]) def shutdown() @@ -94,6 +106,35 @@ object ReflectiveAccess { def toBinary(obj: AnyRef): Array[Byte] def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef } + + type TransactionLogObject = { + def newLogFor( + id: String, + isAsync: Boolean, + replicationScheme: ReplicationScheme, + format: Serializer): TransactionLog + + def logFor( + id: String, + isAsync: Boolean, + replicationScheme: ReplicationScheme, + format: Serializer): TransactionLog + + def shutdown() + } + + type TransactionLog = { + def recordEntry(messageHandle: MessageInvocation, actorRef: ActorRef) + def recordEntry(entry: Array[Byte]) + def recordSnapshot(snapshot: Array[Byte]) + def entries: Vector[Array[Byte]] + def entriesFromLatestSnapshot: Tuple2[Array[Byte], Vector[Array[Byte]]] + def entriesInRange(from: Long, to: Long): Vector[Array[Byte]] + def latestEntryId: Long + def latestSnapshotId: Long + def delete() + def close() + } } /** @@ -104,7 +145,7 @@ object ReflectiveAccess { object RemoteModule { val TRANSPORT = Config.config.getString("akka.remote.layer", "akka.remote.netty.NettyRemoteSupport") - private[akka] val configDefaultAddress = new InetSocketAddress(Config.hostname, Config.remoteServerPort) + val configDefaultAddress = new InetSocketAddress(Config.hostname, Config.remoteServerPort) lazy val isEnabled = remoteSupportClass.isDefined @@ -166,7 +207,7 @@ object ReflectiveAccess { classloader: ClassLoader = loader): Either[Exception, T] = try { assert(params ne null) assert(args ne null) - getClassFor(fqn) match { + getClassFor(fqn, classloader) match { case Right(value) ⇒ val ctor = value.getDeclaredConstructor(params: _*) ctor.setAccessible(true) @@ -180,7 +221,7 @@ object ReflectiveAccess { //Obtains a reference to fqn.MODULE$ def getObjectFor[T](fqn: String, classloader: ClassLoader = loader): Either[Exception, T] = try { - getClassFor(fqn) match { + getClassFor(fqn, classloader) match { case Right(value) ⇒ val instance = value.getDeclaredField("MODULE$") instance.setAccessible(true) diff --git a/akka-camel-typed/src/main/scala/akka/camel/TypedConsumer.scala b/akka-camel-typed/src/main/scala/akka/camel/TypedConsumer.scala index c315742f3a..8df76dadbe 100644 --- a/akka-camel-typed/src/main/scala/akka/camel/TypedConsumer.scala +++ b/akka-camel-typed/src/main/scala/akka/camel/TypedConsumer.scala @@ -5,13 +5,16 @@ package akka.camel import java.lang.reflect.Method +import java.lang.reflect.Proxy._ import akka.actor.{ TypedActor, ActorRef } +import akka.actor.TypedActor._ /** * @author Martin Krasser */ private[camel] object TypedConsumer { + /** * Applies a function f to actorRef if actorRef * references a typed consumer actor. A valid reference to a typed consumer actor is a @@ -21,18 +24,35 @@ private[camel] object TypedConsumer { * is called with the corresponding method instance and the return value is * added to a list which is then returned by this method. */ - def withTypedConsumer[T](actorRef: ActorRef)(f: Method ⇒ T): List[T] = { - if (!actorRef.actor.isInstanceOf[TypedActor]) Nil - else if (actorRef.homeAddress.isDefined) Nil - else { - val typedActor = actorRef.actor.asInstanceOf[TypedActor] - // TODO: support consumer annotation inheritance - // - visit overridden methods in superclasses - // - visit implemented method declarations in interfaces - val intfClass = typedActor.proxy.getClass - val implClass = typedActor.getClass - (for (m ← intfClass.getMethods.toList; if (m.isAnnotationPresent(classOf[consume]))) yield f(m)) ++ - (for (m ← implClass.getMethods.toList; if (m.isAnnotationPresent(classOf[consume]))) yield f(m)) + def withTypedConsumer[T](actorRef: ActorRef, typedActor: Option[AnyRef])(f: (AnyRef, Method) ⇒ T): List[T] = { + typedActor match { + case None ⇒ Nil + case Some(tc) ⇒ { + withConsumeAnnotatedMethodsOnInterfaces(tc, f) ++ + withConsumeAnnotatedMethodsonImplClass(tc, actorRef, f) + } + } + } + + private implicit def class2ProxyClass(c: Class[_]) = new ProxyClass(c) + + private def withConsumeAnnotatedMethodsOnInterfaces[T](tc: AnyRef, f: (AnyRef, Method) ⇒ T): List[T] = for { + i ← tc.getClass.allInterfaces + m ← i.getDeclaredMethods.toList + if (m.isAnnotationPresent(classOf[consume])) + } yield f(tc, m) + + private def withConsumeAnnotatedMethodsonImplClass[T](tc: AnyRef, actorRef: ActorRef, f: (AnyRef, Method) ⇒ T): List[T] = { + val implClass = actorRef.actor.asInstanceOf[TypedActor.TypedActor[AnyRef, AnyRef]].me.getClass + for (m ← implClass.getDeclaredMethods.toList; if (m.isAnnotationPresent(classOf[consume]))) yield f(tc, m) + + } + + private class ProxyClass(c: Class[_]) { + def allInterfaces: List[Class[_]] = allInterfaces(c.getInterfaces.toList) + def allInterfaces(is: List[Class[_]]): List[Class[_]] = is match { + case Nil ⇒ Nil + case x :: xs ⇒ x :: allInterfaces(x.getInterfaces.toList) ::: allInterfaces(xs) } } } diff --git a/akka-camel-typed/src/main/scala/akka/camel/TypedConsumerPublisher.scala b/akka-camel-typed/src/main/scala/akka/camel/TypedConsumerPublisher.scala index 883b98afce..fae8426cbe 100644 --- a/akka-camel-typed/src/main/scala/akka/camel/TypedConsumerPublisher.scala +++ b/akka-camel-typed/src/main/scala/akka/camel/TypedConsumerPublisher.scala @@ -7,8 +7,8 @@ package akka.camel import java.lang.reflect.Method import akka.actor._ -import akka.event.EventHandler import akka.camel.component.TypedActorComponent +import akka.event.EventHandler /** * Concrete publish requestor that requests publication of typed consumer actor methods on @@ -19,8 +19,8 @@ import akka.camel.component.TypedActorComponent */ private[camel] class TypedConsumerPublishRequestor extends PublishRequestor { def receiveActorRegistryEvent = { - case ActorRegistered(actor) ⇒ for (event ← ConsumerMethodRegistered.eventsFor(actor)) deliverCurrentEvent(event) - case ActorUnregistered(actor) ⇒ for (event ← ConsumerMethodUnregistered.eventsFor(actor)) deliverCurrentEvent(event) + case ActorRegistered(_, actor, typedActor) ⇒ for (event ← ConsumerMethodRegistered.eventsFor(actor, typedActor)) deliverCurrentEvent(event) + case ActorUnregistered(_, actor, typedActor) ⇒ for (event ← ConsumerMethodUnregistered.eventsFor(actor, typedActor)) deliverCurrentEvent(event) } } @@ -84,12 +84,12 @@ private[camel] class ConsumerMethodRouteBuilder(event: ConsumerMethodRegistered) */ private[camel] trait ConsumerMethodEvent extends ConsumerEvent { val actorRef: ActorRef + val typedActor: AnyRef val method: Method val uuid = actorRef.uuid.toString val methodName = method.getName val methodUuid = "%s_%s" format (uuid, methodName) - val typedActor = actorRef.actor.asInstanceOf[TypedActor].proxy lazy val routeDefinitionHandler = consumeAnnotation.routeDefinitionHandler.newInstance lazy val consumeAnnotation = method.getAnnotation(classOf[consume]) @@ -100,13 +100,13 @@ private[camel] trait ConsumerMethodEvent extends ConsumerEvent { * Event indicating that a typed consumer actor has been registered at the actor registry. For * each @consume annotated typed actor method a separate event is created. */ -private[camel] case class ConsumerMethodRegistered(actorRef: ActorRef, method: Method) extends ConsumerMethodEvent +private[camel] case class ConsumerMethodRegistered(actorRef: ActorRef, typedActor: AnyRef, method: Method) extends ConsumerMethodEvent /** * Event indicating that a typed consumer actor has been unregistered from the actor registry. For * each @consume annotated typed actor method a separate event is created. */ -private[camel] case class ConsumerMethodUnregistered(actorRef: ActorRef, method: Method) extends ConsumerMethodEvent +private[camel] case class ConsumerMethodUnregistered(actorRef: ActorRef, typedActor: AnyRef, method: Method) extends ConsumerMethodEvent /** * @author Martin Krasser @@ -116,9 +116,9 @@ private[camel] object ConsumerMethodRegistered { * Creates a list of ConsumerMethodRegistered event messages for a typed consumer actor or an empty * list if actorRef doesn't reference a typed consumer actor. */ - def eventsFor(actorRef: ActorRef): List[ConsumerMethodRegistered] = { - TypedConsumer.withTypedConsumer(actorRef: ActorRef) { m ⇒ - ConsumerMethodRegistered(actorRef, m) + def eventsFor(actorRef: ActorRef, typedActor: Option[AnyRef]): List[ConsumerMethodRegistered] = { + TypedConsumer.withTypedConsumer(actorRef, typedActor) { (tc, m) ⇒ + ConsumerMethodRegistered(actorRef, tc, m) } } } @@ -131,9 +131,9 @@ private[camel] object ConsumerMethodUnregistered { * Creates a list of ConsumerMethodUnregistered event messages for a typed consumer actor or an empty * list if actorRef doesn't reference a typed consumer actor. */ - def eventsFor(actorRef: ActorRef): List[ConsumerMethodUnregistered] = { - TypedConsumer.withTypedConsumer(actorRef) { m ⇒ - ConsumerMethodUnregistered(actorRef, m) + def eventsFor(actorRef: ActorRef, typedActor: Option[AnyRef]): List[ConsumerMethodUnregistered] = { + TypedConsumer.withTypedConsumer(actorRef, typedActor) { (tc, m) ⇒ + ConsumerMethodUnregistered(actorRef, tc, m) } } } diff --git a/akka-camel-typed/src/main/scala/akka/camel/component/TypedActorComponent.scala b/akka-camel-typed/src/main/scala/akka/camel/component/TypedActorComponent.scala index 5110867fa7..36d6c50516 100644 --- a/akka-camel-typed/src/main/scala/akka/camel/component/TypedActorComponent.scala +++ b/akka-camel-typed/src/main/scala/akka/camel/component/TypedActorComponent.scala @@ -65,10 +65,10 @@ class TypedActorHolder(uri: String, context: CamelContext, name: String) extends RegistryBean(context, name) { /** - * Returns an akka.camel.component.TypedActorInfo instance. + * Returns an akka.camel.component.BeanInfo instance. */ override def getBeanInfo: BeanInfo = - new TypedActorInfo(getContext, getBean.getClass, getParameterMappingStrategy) + new BeanInfo(getContext, getBean.getClass, getParameterMappingStrategy) /** * Obtains a typed actor from Actor.registry if the schema is @@ -80,39 +80,6 @@ class TypedActorHolder(uri: String, context: CamelContext, name: String) */ override def getBean: AnyRef = { val internal = uri.startsWith(TypedActorComponent.InternalSchema) - if (internal) Actor.registry.typedActorFor(uuidFrom(getName)) getOrElse null else super.getBean - } -} - -/** - * Typed actor meta information. - * - * @author Martin Krasser - */ -class TypedActorInfo(context: CamelContext, clazz: Class[_], strategy: ParameterMappingStrategy) - extends BeanInfo(context, clazz, strategy) { - - /** - * Introspects AspectWerkz proxy classes. - * - * @param clazz AspectWerkz proxy class. - */ - protected override def introspect(clazz: Class[_]): Unit = { - - // TODO: fix target class detection in BeanInfo.introspect(Class) - // Camel assumes that classes containing a '$$' in the class name - // are classes generated with CGLIB. This conflicts with proxies - // created from interfaces with AspectWerkz. Once the fix is in - // place this method can be removed. - - for (method ← clazz.getDeclaredMethods) { - if (isValidMethod(clazz, method)) { - introspect(clazz, method) - } - } - val superclass = clazz.getSuperclass - if ((superclass ne null) && !superclass.equals(classOf[AnyRef])) { - introspect(superclass) - } + if (internal) Actor.registry.local.typedActorFor(uuidFrom(getName)) getOrElse null else super.getBean } } diff --git a/akka-camel-typed/src/test/java/akka/camel/SampleErrorHandlingTypedConsumerImpl.java b/akka-camel-typed/src/test/java/akka/camel/SampleErrorHandlingTypedConsumerImpl.java index cfa42a7521..89b3948b00 100644 --- a/akka-camel-typed/src/test/java/akka/camel/SampleErrorHandlingTypedConsumerImpl.java +++ b/akka-camel-typed/src/test/java/akka/camel/SampleErrorHandlingTypedConsumerImpl.java @@ -1,11 +1,9 @@ package akka.camel; -import akka.actor.TypedActor; - /** * @author Martin Krasser */ -public class SampleErrorHandlingTypedConsumerImpl extends TypedActor implements SampleErrorHandlingTypedConsumer { +public class SampleErrorHandlingTypedConsumerImpl implements SampleErrorHandlingTypedConsumer { public String willFail(String s) { throw new RuntimeException(String.format("error: %s", s)); diff --git a/akka-camel-typed/src/test/java/akka/camel/SampleRemoteTypedConsumerImpl.java b/akka-camel-typed/src/test/java/akka/camel/SampleRemoteTypedConsumerImpl.java index d7fb463b44..067fb4eda6 100644 --- a/akka-camel-typed/src/test/java/akka/camel/SampleRemoteTypedConsumerImpl.java +++ b/akka-camel-typed/src/test/java/akka/camel/SampleRemoteTypedConsumerImpl.java @@ -1,11 +1,9 @@ package akka.camel; -import akka.actor.TypedActor; - /** * @author Martin Krasser */ -public class SampleRemoteTypedConsumerImpl extends TypedActor implements SampleRemoteTypedConsumer { +public class SampleRemoteTypedConsumerImpl implements SampleRemoteTypedConsumer { public String foo(String s) { return String.format("remote typed actor: %s", s); diff --git a/akka-camel-typed/src/test/java/akka/camel/SampleTypedActorImpl.java b/akka-camel-typed/src/test/java/akka/camel/SampleTypedActorImpl.java index 773e3ec3ec..93d6cd9395 100644 --- a/akka-camel-typed/src/test/java/akka/camel/SampleTypedActorImpl.java +++ b/akka-camel-typed/src/test/java/akka/camel/SampleTypedActorImpl.java @@ -5,7 +5,7 @@ import akka.actor.TypedActor; /** * @author Martin Krasser */ -public class SampleTypedActorImpl extends TypedActor implements SampleTypedActor { +public class SampleTypedActorImpl implements SampleTypedActor { public String foo(String s) { return String.format("foo: %s", s); diff --git a/akka-camel-typed/src/test/java/akka/camel/SampleTypedConsumerImpl.java b/akka-camel-typed/src/test/java/akka/camel/SampleTypedConsumerImpl.java index 3bbe7a9442..8a402133f6 100644 --- a/akka-camel-typed/src/test/java/akka/camel/SampleTypedConsumerImpl.java +++ b/akka-camel-typed/src/test/java/akka/camel/SampleTypedConsumerImpl.java @@ -1,11 +1,9 @@ package akka.camel; -import akka.actor.TypedActor; - /** * @author Martin Krasser */ -public class SampleTypedConsumerImpl extends TypedActor implements SampleTypedConsumer { +public class SampleTypedConsumerImpl implements SampleTypedConsumer { public String m1(String b, String h) { return "m1: " + b + " " + h; diff --git a/akka-camel-typed/src/test/java/akka/camel/SampleTypedSingleConsumerImpl.java b/akka-camel-typed/src/test/java/akka/camel/SampleTypedSingleConsumerImpl.java index 27fbfdaa0d..fa4807eec4 100644 --- a/akka-camel-typed/src/test/java/akka/camel/SampleTypedSingleConsumerImpl.java +++ b/akka-camel-typed/src/test/java/akka/camel/SampleTypedSingleConsumerImpl.java @@ -1,11 +1,9 @@ package akka.camel; -import akka.actor.TypedActor; - /** * @author Martin Krasser */ -public class SampleTypedSingleConsumerImpl extends TypedActor implements SampleTypedSingleConsumer { +public class SampleTypedSingleConsumerImpl implements SampleTypedSingleConsumer { public void foo(String b) { } diff --git a/akka-camel-typed/src/test/java/akka/camel/TypedConsumerJavaTestBase.java b/akka-camel-typed/src/test/java/akka/camel/TypedConsumerJavaTestBase.java index 64e8197de8..64aa29ed54 100644 --- a/akka-camel-typed/src/test/java/akka/camel/TypedConsumerJavaTestBase.java +++ b/akka-camel-typed/src/test/java/akka/camel/TypedConsumerJavaTestBase.java @@ -1,7 +1,11 @@ package akka.camel; +import akka.actor.Actor; import akka.actor.TypedActor; +import akka.actor.TypedActor.Configuration; +import akka.dispatch.Dispatchers; import akka.japi.SideEffect; +import akka.util.FiniteDuration; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -28,16 +32,18 @@ public class TypedConsumerJavaTestBase { @AfterClass public static void tearDownAfterClass() { stopCamelService(); - registry().shutdownAll(); + registry().local().shutdownAll(); } @Test public void shouldHandleExceptionThrownByTypedActorAndGenerateCustomResponse() { getMandatoryService().awaitEndpointActivation(1, new SideEffect() { public void apply() { - consumer = TypedActor.newInstance( + consumer = TypedActor.typedActorOf( SampleErrorHandlingTypedConsumer.class, - SampleErrorHandlingTypedConsumerImpl.class); + SampleErrorHandlingTypedConsumerImpl.class, + new Configuration(new FiniteDuration(5000, "millis"), Dispatchers.defaultGlobalDispatcher() + )); } }); String result = getMandatoryTemplate().requestBody("direct:error-handler-test-java-typed", "hello", String.class); diff --git a/akka-camel-typed/src/test/scala/akka/camel/TypedConsumerPublishRequestorTest.scala b/akka-camel-typed/src/test/scala/akka/camel/TypedConsumerPublishRequestorTest.scala index 406c5656c1..03c727834b 100644 --- a/akka-camel-typed/src/test/scala/akka/camel/TypedConsumerPublishRequestorTest.scala +++ b/akka-camel-typed/src/test/scala/akka/camel/TypedConsumerPublishRequestorTest.scala @@ -7,6 +7,7 @@ import org.scalatest.junit.JUnitSuite import akka.actor._ import akka.actor.Actor._ +import akka.actor.TypedActor.Configuration._ import akka.camel.TypedCamelTestSupport.{ SetExpectedMessageCount ⇒ SetExpectedTestMessageCount, _ } class TypedConsumerPublishRequestorTest extends JUnitSuite { @@ -33,16 +34,16 @@ class TypedConsumerPublishRequestorTest extends JUnitSuite { @After def tearDown = { Actor.registry.removeListener(requestor); - Actor.registry.shutdownAll + Actor.registry.local.shutdownAll } @Test def shouldReceiveOneConsumerMethodRegisteredEvent = { Actor.registry.addListener(requestor) - val latch = (publisher !! SetExpectedTestMessageCount(1)).as[CountDownLatch].get - val obj = TypedActor.newInstance(classOf[SampleTypedSingleConsumer], classOf[SampleTypedSingleConsumerImpl]) + val latch = (publisher ? SetExpectedTestMessageCount(1)).as[CountDownLatch].get + val obj = TypedActor.typedActorOf(classOf[SampleTypedSingleConsumer], classOf[SampleTypedSingleConsumerImpl], defaultConfiguration) assert(latch.await(5000, TimeUnit.MILLISECONDS)) - val event = (publisher !! GetRetainedMessage).as[ConsumerMethodRegistered].get + val event = (publisher ? GetRetainedMessage).as[ConsumerMethodRegistered].get assert(event.endpointUri === "direct:foo") assert(event.typedActor === obj) assert(event.methodName === "foo") @@ -50,12 +51,12 @@ class TypedConsumerPublishRequestorTest extends JUnitSuite { @Test def shouldReceiveOneConsumerMethodUnregisteredEvent = { - val obj = TypedActor.newInstance(classOf[SampleTypedSingleConsumer], classOf[SampleTypedSingleConsumerImpl]) - val latch = (publisher !! SetExpectedTestMessageCount(1)).as[CountDownLatch].get + val obj = TypedActor.typedActorOf(classOf[SampleTypedSingleConsumer], classOf[SampleTypedSingleConsumerImpl], defaultConfiguration) + val latch = (publisher ? SetExpectedTestMessageCount(1)).as[CountDownLatch].get Actor.registry.addListener(requestor) TypedActor.stop(obj) assert(latch.await(5000, TimeUnit.MILLISECONDS)) - val event = (publisher !! GetRetainedMessage).as[ConsumerMethodUnregistered].get + val event = (publisher ? GetRetainedMessage).as[ConsumerMethodUnregistered].get assert(event.endpointUri === "direct:foo") assert(event.typedActor === obj) assert(event.methodName === "foo") @@ -64,23 +65,23 @@ class TypedConsumerPublishRequestorTest extends JUnitSuite { @Test def shouldReceiveThreeConsumerMethodRegisteredEvents = { Actor.registry.addListener(requestor) - val latch = (publisher !! SetExpectedTestMessageCount(3)).as[CountDownLatch].get - val obj = TypedActor.newInstance(classOf[SampleTypedConsumer], classOf[SampleTypedConsumerImpl]) + val latch = (publisher ? SetExpectedTestMessageCount(3)).as[CountDownLatch].get + val obj = TypedActor.typedActorOf(classOf[SampleTypedConsumer], classOf[SampleTypedConsumerImpl], defaultConfiguration) assert(latch.await(5000, TimeUnit.MILLISECONDS)) val request = GetRetainedMessages(_.isInstanceOf[ConsumerMethodRegistered]) - val events = (publisher !! request).as[List[ConsumerMethodRegistered]].get + val events = (publisher ? request).as[List[ConsumerMethodRegistered]].get assert(events.map(_.method.getName).sortWith(_ < _) === List("m2", "m3", "m4")) } @Test def shouldReceiveThreeConsumerMethodUnregisteredEvents = { - val obj = TypedActor.newInstance(classOf[SampleTypedConsumer], classOf[SampleTypedConsumerImpl]) - val latch = (publisher !! SetExpectedTestMessageCount(3)).as[CountDownLatch].get + val obj = TypedActor.typedActorOf(classOf[SampleTypedConsumer], classOf[SampleTypedConsumerImpl], defaultConfiguration) + val latch = (publisher ? SetExpectedTestMessageCount(3)).as[CountDownLatch].get Actor.registry.addListener(requestor) TypedActor.stop(obj) assert(latch.await(5000, TimeUnit.MILLISECONDS)) val request = GetRetainedMessages(_.isInstanceOf[ConsumerMethodUnregistered]) - val events = (publisher !! request).as[List[ConsumerMethodUnregistered]].get + val events = (publisher ? request).as[List[ConsumerMethodUnregistered]].get assert(events.map(_.method.getName).sortWith(_ < _) === List("m2", "m3", "m4")) } } diff --git a/akka-camel-typed/src/test/scala/akka/camel/TypedConsumerScalaTest.scala b/akka-camel-typed/src/test/scala/akka/camel/TypedConsumerScalaTest.scala index 0cc0073e2d..1692c8e6fc 100644 --- a/akka-camel-typed/src/test/scala/akka/camel/TypedConsumerScalaTest.scala +++ b/akka-camel-typed/src/test/scala/akka/camel/TypedConsumerScalaTest.scala @@ -7,6 +7,7 @@ import org.scalatest.matchers.MustMatchers import akka.actor.Actor._ import akka.actor._ +import akka.actor.TypedActor.Configuration._ /** * @author Martin Krasser @@ -18,13 +19,13 @@ class TypedConsumerScalaTest extends WordSpec with BeforeAndAfterAll with MustMa var service: CamelService = _ override protected def beforeAll = { - registry.shutdownAll + registry.local.shutdownAll service = CamelServiceManager.startCamelService } override protected def afterAll = { service.stop - registry.shutdownAll + registry.local.shutdownAll } "A responding, typed consumer" when { @@ -32,7 +33,7 @@ class TypedConsumerScalaTest extends WordSpec with BeforeAndAfterAll with MustMa "started" must { "support in-out message exchanges via its endpoints" in { service.awaitEndpointActivation(3) { - actor = TypedActor.newInstance(classOf[SampleTypedConsumer], classOf[SampleTypedConsumerImpl]) + actor = TypedActor.typedActorOf(classOf[SampleTypedConsumer], classOf[SampleTypedConsumerImpl], defaultConfiguration) } must be(true) mandatoryTemplate.requestBodyAndHeader("direct:m2", "x", "test", "y") must equal("m2: x y") mandatoryTemplate.requestBodyAndHeader("direct:m3", "x", "test", "y") must equal("m3: x y") @@ -62,7 +63,7 @@ class TypedConsumerScalaTest extends WordSpec with BeforeAndAfterAll with MustMa "started" must { "support in-out message exchanges via its endpoints" in { service.awaitEndpointActivation(2) { - actor = TypedActor.newInstance(classOf[TestTypedConsumer], classOf[TestTypedConsumerImpl]) + actor = TypedActor.typedActorOf(classOf[TestTypedConsumer], classOf[TestTypedConsumerImpl], defaultConfiguration) } must be(true) mandatoryTemplate.requestBody("direct:publish-test-3", "x") must equal("foo: x") mandatoryTemplate.requestBody("direct:publish-test-4", "x") must equal("bar: x") @@ -91,7 +92,7 @@ object TypedConsumerScalaTest { def bar(s: String): String } - class TestTypedConsumerImpl extends TypedActor with TestTypedConsumer { + class TestTypedConsumerImpl extends TestTypedConsumer { def foo(s: String) = "foo: %s" format s @consume("direct:publish-test-4") def bar(s: String) = "bar: %s" format s diff --git a/akka-camel-typed/src/test/scala/akka/camel/component/TypedActorComponentFeatureTest.scala b/akka-camel-typed/src/test/scala/akka/camel/component/TypedActorComponentFeatureTest.scala index 04d08023a3..91058e3109 100644 --- a/akka-camel-typed/src/test/scala/akka/camel/component/TypedActorComponentFeatureTest.scala +++ b/akka-camel-typed/src/test/scala/akka/camel/component/TypedActorComponentFeatureTest.scala @@ -6,8 +6,8 @@ import org.apache.camel.impl.{ DefaultCamelContext, SimpleRegistry } import org.scalatest.{ BeforeAndAfterEach, BeforeAndAfterAll, FeatureSpec } import akka.actor.{ Actor, TypedActor } +import akka.actor.TypedActor.Configuration._ import akka.camel._ -import akka.util.ReflectiveAccess.TypedActorModule /** * @author Martin Krasser @@ -19,10 +19,14 @@ class TypedActorComponentFeatureTest extends FeatureSpec with BeforeAndAfterAll var typedConsumerUuid: String = _ override protected def beforeAll = { - val typedActor = TypedActor.newInstance(classOf[SampleTypedActor], classOf[SampleTypedActorImpl]) // not a consumer - val typedConsumer = TypedActor.newInstance(classOf[SampleTypedConsumer], classOf[SampleTypedConsumerImpl]) + val typedActor = TypedActor.typedActorOf( + classOf[SampleTypedActor], + classOf[SampleTypedActorImpl], defaultConfiguration) // not a consumer + val typedConsumer = TypedActor.typedActorOf( + classOf[SampleTypedConsumer], + classOf[SampleTypedConsumerImpl], defaultConfiguration) - typedConsumerUuid = TypedActorModule.typedActorObjectInstance.get.actorFor(typedConsumer).get.uuid.toString + typedConsumerUuid = TypedActor.getActorRefFor(typedConsumer).uuid.toString val registry = new SimpleRegistry // external registration @@ -35,7 +39,7 @@ class TypedActorComponentFeatureTest extends FeatureSpec with BeforeAndAfterAll override protected def afterAll = { CamelContextManager.stop - Actor.registry.shutdownAll + Actor.registry.local.shutdownAll } feature("Communicate with an internally-registered typed actor using typed-actor-internal endpoint URIs") { diff --git a/akka-camel/src/main/scala/akka/camel/ConsumerPublisher.scala b/akka-camel/src/main/scala/akka/camel/ConsumerPublisher.scala index fb15c9d1fc..507124ba2f 100644 --- a/akka-camel/src/main/scala/akka/camel/ConsumerPublisher.scala +++ b/akka-camel/src/main/scala/akka/camel/ConsumerPublisher.scala @@ -20,8 +20,8 @@ import akka.event.EventHandler */ private[camel] class ConsumerPublishRequestor extends PublishRequestor { def receiveActorRegistryEvent = { - case ActorRegistered(_, actor) ⇒ for (event ← ConsumerActorRegistered.eventFor(actor)) deliverCurrentEvent(event) - case ActorUnregistered(_, actor) ⇒ for (event ← ConsumerActorUnregistered.eventFor(actor)) deliverCurrentEvent(event) + case ActorRegistered(_, actor, None) ⇒ for (event ← ConsumerActorRegistered.eventFor(actor)) deliverCurrentEvent(event) + case ActorUnregistered(_, actor, None) ⇒ for (event ← ConsumerActorUnregistered.eventFor(actor)) deliverCurrentEvent(event) } } diff --git a/akka-camel/src/main/scala/akka/camel/Producer.scala b/akka-camel/src/main/scala/akka/camel/Producer.scala index f4f745a294..041f3397ff 100644 --- a/akka-camel/src/main/scala/akka/camel/Producer.scala +++ b/akka-camel/src/main/scala/akka/camel/Producer.scala @@ -10,6 +10,7 @@ import org.apache.camel._ import org.apache.camel.processor.SendProcessor import akka.actor.{ Actor, ActorRef, UntypedActor } +import akka.dispatch.ActorPromise /** * Support trait for producing messages to Camel endpoints. @@ -96,10 +97,9 @@ trait ProducerSupport { this: Actor ⇒ val exchange = createExchange(pattern).fromRequestMessage(cmsg) processor.process(exchange, new AsyncCallback { val producer = self - // Need copies of sender and senderFuture references here - // since the callback could be done later by another thread. - val sender = self.sender - val senderFuture = self.senderFuture + // Need copies of channel reference here since the callback could be done + // later by another thread. + val channel = self.channel def done(doneSync: Boolean): Unit = { (doneSync, exchange.isFailed) match { @@ -114,10 +114,12 @@ trait ProducerSupport { this: Actor ⇒ receiveAfterProduce(result) private def dispatchAsync(result: Any) = { - if (senderFuture.isDefined) - producer.postMessageToMailboxAndCreateFutureResultWithTimeout(result, producer.timeout, sender, senderFuture) - else - producer.postMessageToMailbox(result, sender) + channel match { + case _: ActorPromise ⇒ + producer.postMessageToMailboxAndCreateFutureResultWithTimeout(result, producer.timeout, channel) + case _ ⇒ + producer.postMessageToMailbox(result, channel) + } } }) } diff --git a/akka-camel/src/main/scala/akka/camel/PublisherRequestor.scala b/akka-camel/src/main/scala/akka/camel/PublisherRequestor.scala index 7083cdbe6e..7c1ace2b77 100644 --- a/akka-camel/src/main/scala/akka/camel/PublisherRequestor.scala +++ b/akka-camel/src/main/scala/akka/camel/PublisherRequestor.scala @@ -54,7 +54,7 @@ private[camel] abstract class PublishRequestor extends Actor { * @author Martin Krasser */ private[camel] object PublishRequestor { - def pastActorRegisteredEvents = for (actor ← Actor.registry.local.actors) yield ActorRegistered(actor.address, actor) + def pastActorRegisteredEvents = for (actor ← Actor.registry.local.actors) yield ActorRegistered(actor.address, actor, None) } /** diff --git a/akka-camel/src/main/scala/akka/camel/component/ActorComponent.scala b/akka-camel/src/main/scala/akka/camel/component/ActorComponent.scala index f1a643fc1a..0000a74503 100644 --- a/akka-camel/src/main/scala/akka/camel/component/ActorComponent.scala +++ b/akka-camel/src/main/scala/akka/camel/component/ActorComponent.scala @@ -285,7 +285,7 @@ private[akka] class AsyncCallbackAdapter(exchange: Exchange, callback: AsyncCall * @param message reply message * @param sender ignored */ - protected[akka] def postMessageToMailbox(message: Any, senderOption: Option[ActorRef]) = { + protected[akka] def postMessageToMailbox(message: Any, channel: UntypedChannel) = { message match { case Ack ⇒ { /* no response message to set */ } case msg: Failure ⇒ exchange.fromFailureMessage(msg) @@ -295,7 +295,6 @@ private[akka] class AsyncCallbackAdapter(exchange: Exchange, callback: AsyncCall } def actorClass: Class[_ <: Actor] = unsupported - def actorClassName = unsupported def dispatcher_=(md: MessageDispatcher): Unit = unsupported def dispatcher: MessageDispatcher = unsupported def makeRemote(hostname: String, port: Int): Unit = unsupported @@ -313,7 +312,7 @@ private[akka] class AsyncCallbackAdapter(exchange: Exchange, callback: AsyncCall def shutdownLinkedActors: Unit = unsupported def supervisor: Option[ActorRef] = unsupported def homeAddress: Option[InetSocketAddress] = None - protected[akka] def postMessageToMailboxAndCreateFutureResultWithTimeout[T](message: Any, timeout: Long, senderOption: Option[ActorRef], senderFuture: Option[Promise[T]]) = unsupported + protected[akka] def postMessageToMailboxAndCreateFutureResultWithTimeout(message: Any, timeout: Long, channel: UntypedChannel) = unsupported protected[akka] def mailbox: AnyRef = unsupported protected[akka] def mailbox_=(msg: AnyRef): AnyRef = unsupported protected[akka] def restart(reason: Throwable, maxNrOfRetries: Option[Int], withinTimeRange: Option[Int]): Unit = unsupported diff --git a/akka-camel/src/test/scala/akka/camel/ConsumerPublishRequestorTest.scala b/akka-camel/src/test/scala/akka/camel/ConsumerPublishRequestorTest.scala index 4de98f335f..2cf4e3400f 100644 --- a/akka-camel/src/test/scala/akka/camel/ConsumerPublishRequestorTest.scala +++ b/akka-camel/src/test/scala/akka/camel/ConsumerPublishRequestorTest.scala @@ -36,7 +36,7 @@ class ConsumerPublishRequestorTest extends JUnitSuite { @Test def shouldReceiveOneConsumerRegisteredEvent = { val latch = (publisher !! SetExpectedTestMessageCount(1)).as[CountDownLatch].get - requestor ! ActorRegistered(consumer.address, consumer) + requestor ! ActorRegistered(consumer.address, consumer, None) assert(latch.await(5000, TimeUnit.MILLISECONDS)) assert((publisher !! GetRetainedMessage) === Some(ConsumerActorRegistered(consumer, consumer.actor.asInstanceOf[Consumer]))) @@ -45,7 +45,7 @@ class ConsumerPublishRequestorTest extends JUnitSuite { @Test def shouldReceiveOneConsumerUnregisteredEvent = { val latch = (publisher !! SetExpectedTestMessageCount(1)).as[CountDownLatch].get - requestor ! ActorUnregistered(consumer.address, consumer) + requestor ! ActorUnregistered(consumer.address, consumer, None) assert(latch.await(5000, TimeUnit.MILLISECONDS)) assert((publisher !! GetRetainedMessage) === Some(ConsumerActorUnregistered(consumer, consumer.actor.asInstanceOf[Consumer]))) diff --git a/akka-cluster/src/main/java/akka/cluster/ClusterProtocol.java b/akka-cluster/src/main/java/akka/cluster/ClusterProtocol.java index ebf240b200..54ca02a15f 100644 --- a/akka-cluster/src/main/java/akka/cluster/ClusterProtocol.java +++ b/akka-cluster/src/main/java/akka/cluster/ClusterProtocol.java @@ -26,6 +26,21 @@ public final class ClusterProtocol { FUNCTION_FUN1_ARG_ANY(13, 14), ; + public static final int START_VALUE = 1; + public static final int STOP_VALUE = 2; + public static final int USE_VALUE = 3; + public static final int RELEASE_VALUE = 4; + public static final int MAKE_AVAILABLE_VALUE = 5; + public static final int MAKE_UNAVAILABLE_VALUE = 6; + public static final int DISCONNECT_VALUE = 7; + public static final int RECONNECT_VALUE = 8; + public static final int RESIGN_VALUE = 9; + public static final int FAIL_OVER_CONNECTIONS_VALUE = 10; + public static final int FUNCTION_FUN0_UNIT_VALUE = 11; + public static final int FUNCTION_FUN0_ANY_VALUE = 12; + public static final int FUNCTION_FUN1_ARG_UNIT_VALUE = 13; + public static final int FUNCTION_FUN1_ARG_ANY_VALUE = 14; + public final int getNumber() { return value; } @@ -57,8 +72,8 @@ public final class ClusterProtocol { internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { public RemoteDaemonMessageType findValueByNumber(int number) { - return RemoteDaemonMessageType.valueOf(number) - ; } + return RemoteDaemonMessageType.valueOf(number); + } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor @@ -77,6 +92,7 @@ public final class ClusterProtocol { private static final RemoteDaemonMessageType[] VALUES = { START, STOP, USE, RELEASE, MAKE_AVAILABLE, MAKE_UNAVAILABLE, DISCONNECT, RECONNECT, RESIGN, FAIL_OVER_CONNECTIONS, FUNCTION_FUN0_UNIT, FUNCTION_FUN0_ANY, FUNCTION_FUN1_ARG_UNIT, FUNCTION_FUN1_ARG_ANY, }; + public static RemoteDaemonMessageType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { @@ -85,25 +101,44 @@ public final class ClusterProtocol { } return VALUES[desc.getIndex()]; } + private final int index; private final int value; + private RemoteDaemonMessageType(int index, int value) { this.index = index; this.value = value; } - static { - akka.cluster.ClusterProtocol.getDescriptor(); - } - // @@protoc_insertion_point(enum_scope:RemoteDaemonMessageType) } + public interface RemoteDaemonMessageProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required .RemoteDaemonMessageType messageType = 1; + boolean hasMessageType(); + akka.cluster.ClusterProtocol.RemoteDaemonMessageType getMessageType(); + + // optional .UuidProtocol actorUuid = 2; + boolean hasActorUuid(); + akka.cluster.ClusterProtocol.UuidProtocol getActorUuid(); + akka.cluster.ClusterProtocol.UuidProtocolOrBuilder getActorUuidOrBuilder(); + + // optional string actorAddress = 3; + boolean hasActorAddress(); + String getActorAddress(); + + // optional bytes payload = 5; + boolean hasPayload(); + com.google.protobuf.ByteString getPayload(); + } public static final class RemoteDaemonMessageProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements RemoteDaemonMessageProtocolOrBuilder { // Use RemoteDaemonMessageProtocol.newBuilder() to construct. - private RemoteDaemonMessageProtocol() { - initFields(); + private RemoteDaemonMessageProtocol(Builder builder) { + super(builder); } private RemoteDaemonMessageProtocol(boolean noInit) {} @@ -126,60 +161,111 @@ public final class ClusterProtocol { return akka.cluster.ClusterProtocol.internal_static_RemoteDaemonMessageProtocol_fieldAccessorTable; } + private int bitField0_; // required .RemoteDaemonMessageType messageType = 1; public static final int MESSAGETYPE_FIELD_NUMBER = 1; - private boolean hasMessageType; private akka.cluster.ClusterProtocol.RemoteDaemonMessageType messageType_; - public boolean hasMessageType() { return hasMessageType; } - public akka.cluster.ClusterProtocol.RemoteDaemonMessageType getMessageType() { return messageType_; } + public boolean hasMessageType() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public akka.cluster.ClusterProtocol.RemoteDaemonMessageType getMessageType() { + return messageType_; + } // optional .UuidProtocol actorUuid = 2; public static final int ACTORUUID_FIELD_NUMBER = 2; - private boolean hasActorUuid; private akka.cluster.ClusterProtocol.UuidProtocol actorUuid_; - public boolean hasActorUuid() { return hasActorUuid; } - public akka.cluster.ClusterProtocol.UuidProtocol getActorUuid() { return actorUuid_; } + public boolean hasActorUuid() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public akka.cluster.ClusterProtocol.UuidProtocol getActorUuid() { + return actorUuid_; + } + public akka.cluster.ClusterProtocol.UuidProtocolOrBuilder getActorUuidOrBuilder() { + return actorUuid_; + } // optional string actorAddress = 3; public static final int ACTORADDRESS_FIELD_NUMBER = 3; - private boolean hasActorAddress; - private java.lang.String actorAddress_ = ""; - public boolean hasActorAddress() { return hasActorAddress; } - public java.lang.String getActorAddress() { return actorAddress_; } + private java.lang.Object actorAddress_; + public boolean hasActorAddress() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public String getActorAddress() { + java.lang.Object ref = actorAddress_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + actorAddress_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getActorAddressBytes() { + java.lang.Object ref = actorAddress_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + actorAddress_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } // optional bytes payload = 5; public static final int PAYLOAD_FIELD_NUMBER = 5; - private boolean hasPayload; - private com.google.protobuf.ByteString payload_ = com.google.protobuf.ByteString.EMPTY; - public boolean hasPayload() { return hasPayload; } - public com.google.protobuf.ByteString getPayload() { return payload_; } + private com.google.protobuf.ByteString payload_; + public boolean hasPayload() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public com.google.protobuf.ByteString getPayload() { + return payload_; + } private void initFields() { messageType_ = akka.cluster.ClusterProtocol.RemoteDaemonMessageType.START; actorUuid_ = akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance(); + actorAddress_ = ""; + payload_ = com.google.protobuf.ByteString.EMPTY; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasMessageType) return false; - if (hasActorUuid()) { - if (!getActorUuid().isInitialized()) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasMessageType()) { + memoizedIsInitialized = 0; + return false; } + if (hasActorUuid()) { + if (!getActorUuid().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasMessageType()) { - output.writeEnum(1, getMessageType().getNumber()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeEnum(1, messageType_.getNumber()); } - if (hasActorUuid()) { - output.writeMessage(2, getActorUuid()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeMessage(2, actorUuid_); } - if (hasActorAddress()) { - output.writeString(3, getActorAddress()); + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeBytes(3, getActorAddressBytes()); } - if (hasPayload()) { - output.writeBytes(5, getPayload()); + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeBytes(5, payload_); } getUnknownFields().writeTo(output); } @@ -190,27 +276,34 @@ public final class ClusterProtocol { if (size != -1) return size; size = 0; - if (hasMessageType()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeEnumSize(1, getMessageType().getNumber()); + .computeEnumSize(1, messageType_.getNumber()); } - if (hasActorUuid()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(2, getActorUuid()); + .computeMessageSize(2, actorUuid_); } - if (hasActorAddress()) { + if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(3, getActorAddress()); + .computeBytesSize(3, getActorAddressBytes()); } - if (hasPayload()) { + if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream - .computeBytesSize(5, getPayload()); + .computeBytesSize(5, payload_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -285,34 +378,62 @@ public final class ClusterProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol result; - - // Construct using akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.cluster.ClusterProtocol.internal_static_RemoteDaemonMessageProtocol_descriptor; } - protected akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.cluster.ClusterProtocol.internal_static_RemoteDaemonMessageProtocol_fieldAccessorTable; + } + + // Construct using akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getActorUuidFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); + super.clear(); + messageType_ = akka.cluster.ClusterProtocol.RemoteDaemonMessageType.START; + bitField0_ = (bitField0_ & ~0x00000001); + if (actorUuidBuilder_ == null) { + actorUuid_ = akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance(); + } else { + actorUuidBuilder_.clear(); } - result = new akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol(); + bitField0_ = (bitField0_ & ~0x00000002); + actorAddress_ = ""; + bitField0_ = (bitField0_ & ~0x00000004); + payload_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000008); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -324,33 +445,51 @@ public final class ClusterProtocol { return akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol build() { - if (result != null && !isInitialized()) { + akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol result = new akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.cluster.ClusterProtocol.RemoteDaemonMessageProtocol returnMe = result; - result = null; - return returnMe; + result.messageType_ = messageType_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + if (actorUuidBuilder_ == null) { + result.actorUuid_ = actorUuid_; + } else { + result.actorUuid_ = actorUuidBuilder_.build(); + } + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.actorAddress_ = actorAddress_; + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + result.payload_ = payload_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -380,6 +519,20 @@ public final class ClusterProtocol { return this; } + public final boolean isInitialized() { + if (!hasMessageType()) { + + return false; + } + if (hasActorUuid()) { + if (!getActorUuid().isInitialized()) { + + return false; + } + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -392,11 +545,13 @@ public final class ClusterProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; @@ -407,7 +562,8 @@ public final class ClusterProtocol { if (value == null) { unknownFields.mergeVarintField(1, rawValue); } else { - setMessageType(value); + bitField0_ |= 0x00000001; + messageType_ = value; } break; } @@ -421,115 +577,192 @@ public final class ClusterProtocol { break; } case 26: { - setActorAddress(input.readString()); + bitField0_ |= 0x00000004; + actorAddress_ = input.readBytes(); break; } case 42: { - setPayload(input.readBytes()); + bitField0_ |= 0x00000008; + payload_ = input.readBytes(); break; } } } } + private int bitField0_; // required .RemoteDaemonMessageType messageType = 1; + private akka.cluster.ClusterProtocol.RemoteDaemonMessageType messageType_ = akka.cluster.ClusterProtocol.RemoteDaemonMessageType.START; public boolean hasMessageType() { - return result.hasMessageType(); + return ((bitField0_ & 0x00000001) == 0x00000001); } public akka.cluster.ClusterProtocol.RemoteDaemonMessageType getMessageType() { - return result.getMessageType(); + return messageType_; } public Builder setMessageType(akka.cluster.ClusterProtocol.RemoteDaemonMessageType value) { if (value == null) { throw new NullPointerException(); } - result.hasMessageType = true; - result.messageType_ = value; + bitField0_ |= 0x00000001; + messageType_ = value; + onChanged(); return this; } public Builder clearMessageType() { - result.hasMessageType = false; - result.messageType_ = akka.cluster.ClusterProtocol.RemoteDaemonMessageType.START; + bitField0_ = (bitField0_ & ~0x00000001); + messageType_ = akka.cluster.ClusterProtocol.RemoteDaemonMessageType.START; + onChanged(); return this; } // optional .UuidProtocol actorUuid = 2; + private akka.cluster.ClusterProtocol.UuidProtocol actorUuid_ = akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.cluster.ClusterProtocol.UuidProtocol, akka.cluster.ClusterProtocol.UuidProtocol.Builder, akka.cluster.ClusterProtocol.UuidProtocolOrBuilder> actorUuidBuilder_; public boolean hasActorUuid() { - return result.hasActorUuid(); + return ((bitField0_ & 0x00000002) == 0x00000002); } public akka.cluster.ClusterProtocol.UuidProtocol getActorUuid() { - return result.getActorUuid(); + if (actorUuidBuilder_ == null) { + return actorUuid_; + } else { + return actorUuidBuilder_.getMessage(); + } } public Builder setActorUuid(akka.cluster.ClusterProtocol.UuidProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (actorUuidBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + actorUuid_ = value; + onChanged(); + } else { + actorUuidBuilder_.setMessage(value); } - result.hasActorUuid = true; - result.actorUuid_ = value; + bitField0_ |= 0x00000002; return this; } - public Builder setActorUuid(akka.cluster.ClusterProtocol.UuidProtocol.Builder builderForValue) { - result.hasActorUuid = true; - result.actorUuid_ = builderForValue.build(); + public Builder setActorUuid( + akka.cluster.ClusterProtocol.UuidProtocol.Builder builderForValue) { + if (actorUuidBuilder_ == null) { + actorUuid_ = builderForValue.build(); + onChanged(); + } else { + actorUuidBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000002; return this; } public Builder mergeActorUuid(akka.cluster.ClusterProtocol.UuidProtocol value) { - if (result.hasActorUuid() && - result.actorUuid_ != akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance()) { - result.actorUuid_ = - akka.cluster.ClusterProtocol.UuidProtocol.newBuilder(result.actorUuid_).mergeFrom(value).buildPartial(); + if (actorUuidBuilder_ == null) { + if (((bitField0_ & 0x00000002) == 0x00000002) && + actorUuid_ != akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance()) { + actorUuid_ = + akka.cluster.ClusterProtocol.UuidProtocol.newBuilder(actorUuid_).mergeFrom(value).buildPartial(); + } else { + actorUuid_ = value; + } + onChanged(); } else { - result.actorUuid_ = value; + actorUuidBuilder_.mergeFrom(value); } - result.hasActorUuid = true; + bitField0_ |= 0x00000002; return this; } public Builder clearActorUuid() { - result.hasActorUuid = false; - result.actorUuid_ = akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance(); + if (actorUuidBuilder_ == null) { + actorUuid_ = akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance(); + onChanged(); + } else { + actorUuidBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); return this; } + public akka.cluster.ClusterProtocol.UuidProtocol.Builder getActorUuidBuilder() { + bitField0_ |= 0x00000002; + onChanged(); + return getActorUuidFieldBuilder().getBuilder(); + } + public akka.cluster.ClusterProtocol.UuidProtocolOrBuilder getActorUuidOrBuilder() { + if (actorUuidBuilder_ != null) { + return actorUuidBuilder_.getMessageOrBuilder(); + } else { + return actorUuid_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.cluster.ClusterProtocol.UuidProtocol, akka.cluster.ClusterProtocol.UuidProtocol.Builder, akka.cluster.ClusterProtocol.UuidProtocolOrBuilder> + getActorUuidFieldBuilder() { + if (actorUuidBuilder_ == null) { + actorUuidBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.cluster.ClusterProtocol.UuidProtocol, akka.cluster.ClusterProtocol.UuidProtocol.Builder, akka.cluster.ClusterProtocol.UuidProtocolOrBuilder>( + actorUuid_, + getParentForChildren(), + isClean()); + actorUuid_ = null; + } + return actorUuidBuilder_; + } // optional string actorAddress = 3; + private java.lang.Object actorAddress_ = ""; public boolean hasActorAddress() { - return result.hasActorAddress(); + return ((bitField0_ & 0x00000004) == 0x00000004); } - public java.lang.String getActorAddress() { - return result.getActorAddress(); + public String getActorAddress() { + java.lang.Object ref = actorAddress_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + actorAddress_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setActorAddress(java.lang.String value) { + public Builder setActorAddress(String value) { if (value == null) { throw new NullPointerException(); } - result.hasActorAddress = true; - result.actorAddress_ = value; + bitField0_ |= 0x00000004; + actorAddress_ = value; + onChanged(); return this; } public Builder clearActorAddress() { - result.hasActorAddress = false; - result.actorAddress_ = getDefaultInstance().getActorAddress(); + bitField0_ = (bitField0_ & ~0x00000004); + actorAddress_ = getDefaultInstance().getActorAddress(); + onChanged(); return this; } + void setActorAddress(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000004; + actorAddress_ = value; + onChanged(); + } // optional bytes payload = 5; + private com.google.protobuf.ByteString payload_ = com.google.protobuf.ByteString.EMPTY; public boolean hasPayload() { - return result.hasPayload(); + return ((bitField0_ & 0x00000008) == 0x00000008); } public com.google.protobuf.ByteString getPayload() { - return result.getPayload(); + return payload_; } public Builder setPayload(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } - result.hasPayload = true; - result.payload_ = value; + bitField0_ |= 0x00000008; + payload_ = value; + onChanged(); return this; } public Builder clearPayload() { - result.hasPayload = false; - result.payload_ = getDefaultInstance().getPayload(); + bitField0_ = (bitField0_ & ~0x00000008); + payload_ = getDefaultInstance().getPayload(); + onChanged(); return this; } @@ -538,18 +771,38 @@ public final class ClusterProtocol { static { defaultInstance = new RemoteDaemonMessageProtocol(true); - akka.cluster.ClusterProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:RemoteDaemonMessageProtocol) } + public interface DurableMailboxMessageProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required string ownerActorAddress = 1; + boolean hasOwnerActorAddress(); + String getOwnerActorAddress(); + + // optional string senderActorAddress = 2; + boolean hasSenderActorAddress(); + String getSenderActorAddress(); + + // optional .UuidProtocol futureUuid = 3; + boolean hasFutureUuid(); + akka.cluster.ClusterProtocol.UuidProtocol getFutureUuid(); + akka.cluster.ClusterProtocol.UuidProtocolOrBuilder getFutureUuidOrBuilder(); + + // required bytes message = 4; + boolean hasMessage(); + com.google.protobuf.ByteString getMessage(); + } public static final class DurableMailboxMessageProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements DurableMailboxMessageProtocolOrBuilder { // Use DurableMailboxMessageProtocol.newBuilder() to construct. - private DurableMailboxMessageProtocol() { - initFields(); + private DurableMailboxMessageProtocol(Builder builder) { + super(builder); } private DurableMailboxMessageProtocol(boolean noInit) {} @@ -572,60 +825,137 @@ public final class ClusterProtocol { return akka.cluster.ClusterProtocol.internal_static_DurableMailboxMessageProtocol_fieldAccessorTable; } + private int bitField0_; // required string ownerActorAddress = 1; public static final int OWNERACTORADDRESS_FIELD_NUMBER = 1; - private boolean hasOwnerActorAddress; - private java.lang.String ownerActorAddress_ = ""; - public boolean hasOwnerActorAddress() { return hasOwnerActorAddress; } - public java.lang.String getOwnerActorAddress() { return ownerActorAddress_; } + private java.lang.Object ownerActorAddress_; + public boolean hasOwnerActorAddress() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public String getOwnerActorAddress() { + java.lang.Object ref = ownerActorAddress_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + ownerActorAddress_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getOwnerActorAddressBytes() { + java.lang.Object ref = ownerActorAddress_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + ownerActorAddress_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } // optional string senderActorAddress = 2; public static final int SENDERACTORADDRESS_FIELD_NUMBER = 2; - private boolean hasSenderActorAddress; - private java.lang.String senderActorAddress_ = ""; - public boolean hasSenderActorAddress() { return hasSenderActorAddress; } - public java.lang.String getSenderActorAddress() { return senderActorAddress_; } + private java.lang.Object senderActorAddress_; + public boolean hasSenderActorAddress() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public String getSenderActorAddress() { + java.lang.Object ref = senderActorAddress_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + senderActorAddress_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getSenderActorAddressBytes() { + java.lang.Object ref = senderActorAddress_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + senderActorAddress_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } // optional .UuidProtocol futureUuid = 3; public static final int FUTUREUUID_FIELD_NUMBER = 3; - private boolean hasFutureUuid; private akka.cluster.ClusterProtocol.UuidProtocol futureUuid_; - public boolean hasFutureUuid() { return hasFutureUuid; } - public akka.cluster.ClusterProtocol.UuidProtocol getFutureUuid() { return futureUuid_; } + public boolean hasFutureUuid() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public akka.cluster.ClusterProtocol.UuidProtocol getFutureUuid() { + return futureUuid_; + } + public akka.cluster.ClusterProtocol.UuidProtocolOrBuilder getFutureUuidOrBuilder() { + return futureUuid_; + } // required bytes message = 4; public static final int MESSAGE_FIELD_NUMBER = 4; - private boolean hasMessage; - private com.google.protobuf.ByteString message_ = com.google.protobuf.ByteString.EMPTY; - public boolean hasMessage() { return hasMessage; } - public com.google.protobuf.ByteString getMessage() { return message_; } + private com.google.protobuf.ByteString message_; + public boolean hasMessage() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public com.google.protobuf.ByteString getMessage() { + return message_; + } private void initFields() { + ownerActorAddress_ = ""; + senderActorAddress_ = ""; futureUuid_ = akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance(); + message_ = com.google.protobuf.ByteString.EMPTY; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasOwnerActorAddress) return false; - if (!hasMessage) return false; - if (hasFutureUuid()) { - if (!getFutureUuid().isInitialized()) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasOwnerActorAddress()) { + memoizedIsInitialized = 0; + return false; } + if (!hasMessage()) { + memoizedIsInitialized = 0; + return false; + } + if (hasFutureUuid()) { + if (!getFutureUuid().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasOwnerActorAddress()) { - output.writeString(1, getOwnerActorAddress()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeBytes(1, getOwnerActorAddressBytes()); } - if (hasSenderActorAddress()) { - output.writeString(2, getSenderActorAddress()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, getSenderActorAddressBytes()); } - if (hasFutureUuid()) { - output.writeMessage(3, getFutureUuid()); + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeMessage(3, futureUuid_); } - if (hasMessage()) { - output.writeBytes(4, getMessage()); + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeBytes(4, message_); } getUnknownFields().writeTo(output); } @@ -636,27 +966,34 @@ public final class ClusterProtocol { if (size != -1) return size; size = 0; - if (hasOwnerActorAddress()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(1, getOwnerActorAddress()); + .computeBytesSize(1, getOwnerActorAddressBytes()); } - if (hasSenderActorAddress()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(2, getSenderActorAddress()); + .computeBytesSize(2, getSenderActorAddressBytes()); } - if (hasFutureUuid()) { + if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(3, getFutureUuid()); + .computeMessageSize(3, futureUuid_); } - if (hasMessage()) { + if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream - .computeBytesSize(4, getMessage()); + .computeBytesSize(4, message_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -731,34 +1068,62 @@ public final class ClusterProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol result; - - // Construct using akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.cluster.ClusterProtocol.DurableMailboxMessageProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.cluster.ClusterProtocol.internal_static_DurableMailboxMessageProtocol_descriptor; } - protected akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.cluster.ClusterProtocol.internal_static_DurableMailboxMessageProtocol_fieldAccessorTable; + } + + // Construct using akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getFutureUuidFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); + super.clear(); + ownerActorAddress_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + senderActorAddress_ = ""; + bitField0_ = (bitField0_ & ~0x00000002); + if (futureUuidBuilder_ == null) { + futureUuid_ = akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance(); + } else { + futureUuidBuilder_.clear(); } - result = new akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol(); + bitField0_ = (bitField0_ & ~0x00000004); + message_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000008); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -770,33 +1135,51 @@ public final class ClusterProtocol { return akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol build() { - if (result != null && !isInitialized()) { + akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol result = new akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.cluster.ClusterProtocol.DurableMailboxMessageProtocol returnMe = result; - result = null; - return returnMe; + result.ownerActorAddress_ = ownerActorAddress_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.senderActorAddress_ = senderActorAddress_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + if (futureUuidBuilder_ == null) { + result.futureUuid_ = futureUuid_; + } else { + result.futureUuid_ = futureUuidBuilder_.build(); + } + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + result.message_ = message_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -826,6 +1209,24 @@ public final class ClusterProtocol { return this; } + public final boolean isInitialized() { + if (!hasOwnerActorAddress()) { + + return false; + } + if (!hasMessage()) { + + return false; + } + if (hasFutureUuid()) { + if (!getFutureUuid().isInitialized()) { + + return false; + } + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -838,21 +1239,25 @@ public final class ClusterProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; } case 10: { - setOwnerActorAddress(input.readString()); + bitField0_ |= 0x00000001; + ownerActorAddress_ = input.readBytes(); break; } case 18: { - setSenderActorAddress(input.readString()); + bitField0_ |= 0x00000002; + senderActorAddress_ = input.readBytes(); break; } case 26: { @@ -865,111 +1270,199 @@ public final class ClusterProtocol { break; } case 34: { - setMessage(input.readBytes()); + bitField0_ |= 0x00000008; + message_ = input.readBytes(); break; } } } } + private int bitField0_; // required string ownerActorAddress = 1; + private java.lang.Object ownerActorAddress_ = ""; public boolean hasOwnerActorAddress() { - return result.hasOwnerActorAddress(); + return ((bitField0_ & 0x00000001) == 0x00000001); } - public java.lang.String getOwnerActorAddress() { - return result.getOwnerActorAddress(); + public String getOwnerActorAddress() { + java.lang.Object ref = ownerActorAddress_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + ownerActorAddress_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setOwnerActorAddress(java.lang.String value) { + public Builder setOwnerActorAddress(String value) { if (value == null) { throw new NullPointerException(); } - result.hasOwnerActorAddress = true; - result.ownerActorAddress_ = value; + bitField0_ |= 0x00000001; + ownerActorAddress_ = value; + onChanged(); return this; } public Builder clearOwnerActorAddress() { - result.hasOwnerActorAddress = false; - result.ownerActorAddress_ = getDefaultInstance().getOwnerActorAddress(); + bitField0_ = (bitField0_ & ~0x00000001); + ownerActorAddress_ = getDefaultInstance().getOwnerActorAddress(); + onChanged(); return this; } + void setOwnerActorAddress(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000001; + ownerActorAddress_ = value; + onChanged(); + } // optional string senderActorAddress = 2; + private java.lang.Object senderActorAddress_ = ""; public boolean hasSenderActorAddress() { - return result.hasSenderActorAddress(); + return ((bitField0_ & 0x00000002) == 0x00000002); } - public java.lang.String getSenderActorAddress() { - return result.getSenderActorAddress(); + public String getSenderActorAddress() { + java.lang.Object ref = senderActorAddress_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + senderActorAddress_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setSenderActorAddress(java.lang.String value) { + public Builder setSenderActorAddress(String value) { if (value == null) { throw new NullPointerException(); } - result.hasSenderActorAddress = true; - result.senderActorAddress_ = value; + bitField0_ |= 0x00000002; + senderActorAddress_ = value; + onChanged(); return this; } public Builder clearSenderActorAddress() { - result.hasSenderActorAddress = false; - result.senderActorAddress_ = getDefaultInstance().getSenderActorAddress(); + bitField0_ = (bitField0_ & ~0x00000002); + senderActorAddress_ = getDefaultInstance().getSenderActorAddress(); + onChanged(); return this; } + void setSenderActorAddress(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000002; + senderActorAddress_ = value; + onChanged(); + } // optional .UuidProtocol futureUuid = 3; + private akka.cluster.ClusterProtocol.UuidProtocol futureUuid_ = akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.cluster.ClusterProtocol.UuidProtocol, akka.cluster.ClusterProtocol.UuidProtocol.Builder, akka.cluster.ClusterProtocol.UuidProtocolOrBuilder> futureUuidBuilder_; public boolean hasFutureUuid() { - return result.hasFutureUuid(); + return ((bitField0_ & 0x00000004) == 0x00000004); } public akka.cluster.ClusterProtocol.UuidProtocol getFutureUuid() { - return result.getFutureUuid(); + if (futureUuidBuilder_ == null) { + return futureUuid_; + } else { + return futureUuidBuilder_.getMessage(); + } } public Builder setFutureUuid(akka.cluster.ClusterProtocol.UuidProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (futureUuidBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + futureUuid_ = value; + onChanged(); + } else { + futureUuidBuilder_.setMessage(value); } - result.hasFutureUuid = true; - result.futureUuid_ = value; + bitField0_ |= 0x00000004; return this; } - public Builder setFutureUuid(akka.cluster.ClusterProtocol.UuidProtocol.Builder builderForValue) { - result.hasFutureUuid = true; - result.futureUuid_ = builderForValue.build(); + public Builder setFutureUuid( + akka.cluster.ClusterProtocol.UuidProtocol.Builder builderForValue) { + if (futureUuidBuilder_ == null) { + futureUuid_ = builderForValue.build(); + onChanged(); + } else { + futureUuidBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000004; return this; } public Builder mergeFutureUuid(akka.cluster.ClusterProtocol.UuidProtocol value) { - if (result.hasFutureUuid() && - result.futureUuid_ != akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance()) { - result.futureUuid_ = - akka.cluster.ClusterProtocol.UuidProtocol.newBuilder(result.futureUuid_).mergeFrom(value).buildPartial(); + if (futureUuidBuilder_ == null) { + if (((bitField0_ & 0x00000004) == 0x00000004) && + futureUuid_ != akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance()) { + futureUuid_ = + akka.cluster.ClusterProtocol.UuidProtocol.newBuilder(futureUuid_).mergeFrom(value).buildPartial(); + } else { + futureUuid_ = value; + } + onChanged(); } else { - result.futureUuid_ = value; + futureUuidBuilder_.mergeFrom(value); } - result.hasFutureUuid = true; + bitField0_ |= 0x00000004; return this; } public Builder clearFutureUuid() { - result.hasFutureUuid = false; - result.futureUuid_ = akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance(); + if (futureUuidBuilder_ == null) { + futureUuid_ = akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance(); + onChanged(); + } else { + futureUuidBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); return this; } + public akka.cluster.ClusterProtocol.UuidProtocol.Builder getFutureUuidBuilder() { + bitField0_ |= 0x00000004; + onChanged(); + return getFutureUuidFieldBuilder().getBuilder(); + } + public akka.cluster.ClusterProtocol.UuidProtocolOrBuilder getFutureUuidOrBuilder() { + if (futureUuidBuilder_ != null) { + return futureUuidBuilder_.getMessageOrBuilder(); + } else { + return futureUuid_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.cluster.ClusterProtocol.UuidProtocol, akka.cluster.ClusterProtocol.UuidProtocol.Builder, akka.cluster.ClusterProtocol.UuidProtocolOrBuilder> + getFutureUuidFieldBuilder() { + if (futureUuidBuilder_ == null) { + futureUuidBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.cluster.ClusterProtocol.UuidProtocol, akka.cluster.ClusterProtocol.UuidProtocol.Builder, akka.cluster.ClusterProtocol.UuidProtocolOrBuilder>( + futureUuid_, + getParentForChildren(), + isClean()); + futureUuid_ = null; + } + return futureUuidBuilder_; + } // required bytes message = 4; + private com.google.protobuf.ByteString message_ = com.google.protobuf.ByteString.EMPTY; public boolean hasMessage() { - return result.hasMessage(); + return ((bitField0_ & 0x00000008) == 0x00000008); } public com.google.protobuf.ByteString getMessage() { - return result.getMessage(); + return message_; } public Builder setMessage(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } - result.hasMessage = true; - result.message_ = value; + bitField0_ |= 0x00000008; + message_ = value; + onChanged(); return this; } public Builder clearMessage() { - result.hasMessage = false; - result.message_ = getDefaultInstance().getMessage(); + bitField0_ = (bitField0_ & ~0x00000008); + message_ = getDefaultInstance().getMessage(); + onChanged(); return this; } @@ -978,18 +1471,29 @@ public final class ClusterProtocol { static { defaultInstance = new DurableMailboxMessageProtocol(true); - akka.cluster.ClusterProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:DurableMailboxMessageProtocol) } + public interface UuidProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required uint64 high = 1; + boolean hasHigh(); + long getHigh(); + + // required uint64 low = 2; + boolean hasLow(); + long getLow(); + } public static final class UuidProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements UuidProtocolOrBuilder { // Use UuidProtocol.newBuilder() to construct. - private UuidProtocol() { - initFields(); + private UuidProtocol(Builder builder) { + super(builder); } private UuidProtocol(boolean noInit) {} @@ -1012,36 +1516,56 @@ public final class ClusterProtocol { return akka.cluster.ClusterProtocol.internal_static_UuidProtocol_fieldAccessorTable; } + private int bitField0_; // required uint64 high = 1; public static final int HIGH_FIELD_NUMBER = 1; - private boolean hasHigh; - private long high_ = 0L; - public boolean hasHigh() { return hasHigh; } - public long getHigh() { return high_; } + private long high_; + public boolean hasHigh() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public long getHigh() { + return high_; + } // required uint64 low = 2; public static final int LOW_FIELD_NUMBER = 2; - private boolean hasLow; - private long low_ = 0L; - public boolean hasLow() { return hasLow; } - public long getLow() { return low_; } + private long low_; + public boolean hasLow() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public long getLow() { + return low_; + } private void initFields() { + high_ = 0L; + low_ = 0L; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasHigh) return false; - if (!hasLow) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasHigh()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasLow()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasHigh()) { - output.writeUInt64(1, getHigh()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeUInt64(1, high_); } - if (hasLow()) { - output.writeUInt64(2, getLow()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeUInt64(2, low_); } getUnknownFields().writeTo(output); } @@ -1052,19 +1576,26 @@ public final class ClusterProtocol { if (size != -1) return size; size = 0; - if (hasHigh()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeUInt64Size(1, getHigh()); + .computeUInt64Size(1, high_); } - if (hasLow()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeUInt64Size(2, getLow()); + .computeUInt64Size(2, low_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.cluster.ClusterProtocol.UuidProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -1139,34 +1670,53 @@ public final class ClusterProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.cluster.ClusterProtocol.UuidProtocol result; - - // Construct using akka.cluster.ClusterProtocol.UuidProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.cluster.ClusterProtocol.UuidProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.cluster.ClusterProtocol.UuidProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.cluster.ClusterProtocol.internal_static_UuidProtocol_descriptor; } - protected akka.cluster.ClusterProtocol.UuidProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.cluster.ClusterProtocol.internal_static_UuidProtocol_fieldAccessorTable; + } + + // Construct using akka.cluster.ClusterProtocol.UuidProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); - } - result = new akka.cluster.ClusterProtocol.UuidProtocol(); + super.clear(); + high_ = 0L; + bitField0_ = (bitField0_ & ~0x00000001); + low_ = 0L; + bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -1178,33 +1728,39 @@ public final class ClusterProtocol { return akka.cluster.ClusterProtocol.UuidProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.cluster.ClusterProtocol.UuidProtocol build() { - if (result != null && !isInitialized()) { + akka.cluster.ClusterProtocol.UuidProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.cluster.ClusterProtocol.UuidProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.cluster.ClusterProtocol.UuidProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.cluster.ClusterProtocol.UuidProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.cluster.ClusterProtocol.UuidProtocol result = new akka.cluster.ClusterProtocol.UuidProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.cluster.ClusterProtocol.UuidProtocol returnMe = result; - result = null; - return returnMe; + result.high_ = high_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.low_ = low_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -1228,6 +1784,18 @@ public final class ClusterProtocol { return this; } + public final boolean isInitialized() { + if (!hasHigh()) { + + return false; + } + if (!hasLow()) { + + return false; + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -1240,61 +1808,72 @@ public final class ClusterProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; } case 8: { - setHigh(input.readUInt64()); + bitField0_ |= 0x00000001; + high_ = input.readUInt64(); break; } case 16: { - setLow(input.readUInt64()); + bitField0_ |= 0x00000002; + low_ = input.readUInt64(); break; } } } } + private int bitField0_; // required uint64 high = 1; + private long high_ ; public boolean hasHigh() { - return result.hasHigh(); + return ((bitField0_ & 0x00000001) == 0x00000001); } public long getHigh() { - return result.getHigh(); + return high_; } public Builder setHigh(long value) { - result.hasHigh = true; - result.high_ = value; + bitField0_ |= 0x00000001; + high_ = value; + onChanged(); return this; } public Builder clearHigh() { - result.hasHigh = false; - result.high_ = 0L; + bitField0_ = (bitField0_ & ~0x00000001); + high_ = 0L; + onChanged(); return this; } // required uint64 low = 2; + private long low_ ; public boolean hasLow() { - return result.hasLow(); + return ((bitField0_ & 0x00000002) == 0x00000002); } public long getLow() { - return result.getLow(); + return low_; } public Builder setLow(long value) { - result.hasLow = true; - result.low_ = value; + bitField0_ |= 0x00000002; + low_ = value; + onChanged(); return this; } public Builder clearLow() { - result.hasLow = false; - result.low_ = 0L; + bitField0_ = (bitField0_ & ~0x00000002); + low_ = 0L; + onChanged(); return this; } @@ -1303,7 +1882,6 @@ public final class ClusterProtocol { static { defaultInstance = new UuidProtocol(true); - akka.cluster.ClusterProtocol.internalForceInit(); defaultInstance.initFields(); } @@ -1390,7 +1968,5 @@ public final class ClusterProtocol { }, assigner); } - public static void internalForceInit() {} - // @@protoc_insertion_point(outer_class_scope) } diff --git a/akka-cluster/src/main/scala/akka/cluster/Cluster.scala b/akka-cluster/src/main/scala/akka/cluster/Cluster.scala index 1403295a49..c8fd8698f3 100644 --- a/akka-cluster/src/main/scala/akka/cluster/Cluster.scala +++ b/akka-cluster/src/main/scala/akka/cluster/Cluster.scala @@ -12,6 +12,7 @@ import org.I0Itec.zkclient._ import org.I0Itec.zkclient.serialize._ import org.I0Itec.zkclient.exception._ +import java.util.{ List ⇒ JList } import java.util.concurrent.atomic.{ AtomicBoolean, AtomicReference, AtomicInteger } import java.util.concurrent.{ ConcurrentSkipListSet, CopyOnWriteArrayList, Callable, ConcurrentHashMap } import java.net.InetSocketAddress @@ -26,16 +27,22 @@ import RemoteDaemonMessageType._ import akka.util._ import Helpers._ + import akka.actor._ import Actor._ import Status._ +import DeploymentConfig.{ ReplicationScheme, ReplicationStrategy, Transient, WriteThrough, WriteBehind } + import akka.event.EventHandler import akka.dispatch.{ Dispatchers, Future } import akka.remoteinterface._ import akka.routing.RouterType -import akka.config.Config + +import akka.config.{ Config, Supervision } +import Supervision._ import Config._ -import akka.serialization.{ Format, Serializers, Serializer, Compression } + +import akka.serialization.{ Serialization, Serializer, Compression } import Compression.LZF import akka.AkkaException @@ -45,7 +52,6 @@ import akka.cluster.ChangeListener._ import com.eaio.uuid.UUID import com.google.protobuf.ByteString -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 @@ -225,7 +231,7 @@ object Cluster { /** * Creates a new AkkaZkClient. */ - def newZkClient: AkkaZkClient = new AkkaZkClient(zooKeeperServers, sessionTimeout, connectionTimeout, defaultSerializer) + def newZkClient(): AkkaZkClient = new AkkaZkClient(zooKeeperServers, sessionTimeout, connectionTimeout, defaultSerializer) def createQueue(rootPath: String, blocking: Boolean = true) = new ZooKeeperQueue(node.zkClient, rootPath, blocking) @@ -282,8 +288,18 @@ class DefaultClusterNode private[akka] ( case RemoteClientDisconnected(client, address) ⇒ client.shutdownClientModule() case _ ⇒ //ignore other } - }, "akka.cluster.remoteClientLifeCycleListener").start() + }, "akka.cluster.RemoteClientLifeCycleListener").start() + lazy val remoteDaemon = actorOf(new RemoteClusterDaemon(this), RemoteClusterDaemon.ADDRESS).start() + + lazy val remoteDaemonSupervisor = Supervisor( + SupervisorConfig( + OneForOneStrategy(List(classOf[Exception]), Int.MaxValue, Int.MaxValue), // is infinite restart what we want? + Supervise( + remoteDaemon, + Permanent) + :: Nil)) + lazy val remoteService: RemoteSupport = { val remote = new akka.remote.netty.NettyRemoteSupport remote.start(nodeAddress.hostname, nodeAddress.port) @@ -291,6 +307,7 @@ class DefaultClusterNode private[akka] ( remote.addListener(remoteClientLifeCycleListener) remote } + lazy val remoteServerAddress: InetSocketAddress = remoteService.address // static nodes @@ -451,7 +468,15 @@ class DefaultClusterNode private[akka] ( * available durable store. */ def store[T <: Actor](address: String, actorClass: Class[T], format: Serializer): ClusterNode = - store(Actor.actorOf(actorClass, address).start, 0, false, format) + store(Actor.actorOf(actorClass, address).start, 0, Transient, false, format) + + /** + * 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](address: String, actorClass: Class[T], replicationScheme: ReplicationScheme, format: Serializer): ClusterNode = + store(Actor.actorOf(actorClass, address).start, 0, replicationScheme, false, format) /** * Clusters an actor of a specific type. If the actor is already clustered then the clustered version will be updated @@ -459,7 +484,15 @@ class DefaultClusterNode private[akka] ( * available durable store. */ def store[T <: Actor](address: String, actorClass: Class[T], replicationFactor: Int, format: Serializer): ClusterNode = - store(Actor.actorOf(actorClass, address).start, replicationFactor, false, format) + store(Actor.actorOf(actorClass, address).start, replicationFactor, Transient, false, format) + + /** + * 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](address: String, actorClass: Class[T], replicationFactor: Int, replicationScheme: ReplicationScheme, format: Serializer): ClusterNode = + store(Actor.actorOf(actorClass, address).start, replicationFactor, replicationScheme, false, format) /** * Clusters an actor of a specific type. If the actor is already clustered then the clustered version will be updated @@ -467,7 +500,15 @@ class DefaultClusterNode private[akka] ( * available durable store. */ def store[T <: Actor](address: String, actorClass: Class[T], serializeMailbox: Boolean, format: Serializer): ClusterNode = - store(Actor.actorOf(actorClass, address).start, 0, serializeMailbox, format) + store(Actor.actorOf(actorClass, address).start, 0, Transient, serializeMailbox, format) + + /** + * 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](address: String, actorClass: Class[T], replicationScheme: ReplicationScheme, serializeMailbox: Boolean, format: Serializer): ClusterNode = + store(Actor.actorOf(actorClass, address).start, 0, replicationScheme, serializeMailbox, format) /** * Clusters an actor of a specific type. If the actor is already clustered then the clustered version will be updated @@ -475,7 +516,15 @@ class DefaultClusterNode private[akka] ( * available durable store. */ def store[T <: Actor](address: String, actorClass: Class[T], replicationFactor: Int, serializeMailbox: Boolean, format: Serializer): ClusterNode = - store(Actor.actorOf(actorClass, address).start, replicationFactor, serializeMailbox, format) + store(Actor.actorOf(actorClass, address).start, replicationFactor, Transient, serializeMailbox, format) + + /** + * 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](address: String, actorClass: Class[T], replicationFactor: Int, replicationScheme: ReplicationScheme, serializeMailbox: Boolean, format: Serializer): ClusterNode = + store(Actor.actorOf(actorClass, address).start, replicationFactor, replicationScheme, serializeMailbox, format) /** * Clusters an actor with UUID. If the actor is already clustered then the clustered version will be updated @@ -483,7 +532,15 @@ class DefaultClusterNode private[akka] ( * available durable store. */ def store(actorRef: ActorRef, format: Serializer): ClusterNode = - store(actorRef, 0, false, format) + store(actorRef, 0, Transient, false, format) + + /** + * 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(actorRef: ActorRef, replicationScheme: ReplicationScheme, format: Serializer): ClusterNode = + store(actorRef, 0, replicationScheme, false, format) /** * Clusters an actor with UUID. If the actor is already clustered then the clustered version will be updated @@ -491,7 +548,15 @@ class DefaultClusterNode private[akka] ( * available durable store. */ def store(actorRef: ActorRef, replicationFactor: Int, format: Serializer): ClusterNode = - store(actorRef, replicationFactor, false, format) + store(actorRef, replicationFactor, Transient, false, format) + + /** + * 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(actorRef: ActorRef, replicationFactor: Int, replicationScheme: ReplicationScheme, format: Serializer): ClusterNode = + store(actorRef, replicationFactor, replicationScheme, false, format) /** * Clusters an actor with UUID. If the actor is already clustered then the clustered version will be updated @@ -499,20 +564,47 @@ class DefaultClusterNode private[akka] ( * available durable store. */ def store(actorRef: ActorRef, serializeMailbox: Boolean, format: Serializer): ClusterNode = - store(actorRef, 0, serializeMailbox, format) - - /** - * Needed to have reflection through structural typing work. - */ - def store(actorRef: ActorRef, replicationFactor: Int, serializeMailbox: Boolean, format: AnyRef): ClusterNode = - store(actorRef, replicationFactor, serializeMailbox, format.asInstanceOf[Serializer]) + store(actorRef, 0, Transient, serializeMailbox, format) /** * 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(actorRef: ActorRef, replicationFactor: Int, serializeMailbox: Boolean, format: Serializer): ClusterNode = if (isConnected.isOn) { + def store(actorRef: ActorRef, replicationFactor: Int, serializeMailbox: Boolean, format: Serializer): ClusterNode = + store(actorRef, replicationFactor, Transient, serializeMailbox, format) + + /** + * 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(actorRef: ActorRef, replicationScheme: ReplicationScheme, serializeMailbox: Boolean, format: Serializer): ClusterNode = + store(actorRef, 0, replicationScheme, serializeMailbox, format) + + /** + * Needed to have reflection through structural typing work. + */ + def store(actorRef: ActorRef, replicationFactor: Int, replicationScheme: ReplicationScheme, serializeMailbox: Boolean, format: AnyRef): ClusterNode = + store(actorRef, replicationFactor, replicationScheme, serializeMailbox, format.asInstanceOf[Serializer]) + + /** + * Needed to have reflection through structural typing work. + */ + def store(actorRef: ActorRef, replicationFactor: Int, serializeMailbox: Boolean, format: AnyRef): ClusterNode = + store(actorRef, replicationFactor, Transient, serializeMailbox, format) + + /** + * 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( + actorRef: ActorRef, + replicationFactor: Int, + replicationScheme: ReplicationScheme, + serializeMailbox: Boolean, + format: Serializer): ClusterNode = if (isConnected.isOn) { import akka.serialization.ActorSerialization._ @@ -523,12 +615,14 @@ class DefaultClusterNode private[akka] ( EventHandler.debug(this, "Storing actor [%s] with UUID [%s] in cluster".format(actorRef.address, uuid)) - val actorBytes = if (shouldCompressData) LZF.compress(toBinary(actorRef, serializeMailbox)(format)) - else toBinary(actorRef)(format) + val actorBytes = + if (shouldCompressData) LZF.compress(toBinary(actorRef, serializeMailbox, replicationScheme)) + else toBinary(actorRef, serializeMailbox, replicationScheme) + val actorRegistryPath = actorRegistryPathFor(uuid) // create UUID -> Array[Byte] for actor registry - if (zkClient.exists(actorRegistryPath)) zkClient.writeData(actorRegistryPath, actorBytes) // FIXME check for size and warn if too big + if (zkClient.exists(actorRegistryPath)) zkClient.writeData(actorRegistryPath, actorBytes) // FIXME Store actor bytes in Data Grid not ZooKeeper else { zkClient.retryUntilConnected(new Callable[Either[String, Exception]]() { def call: Either[String, Exception] = { @@ -575,12 +669,10 @@ class DefaultClusterNode private[akka] ( .build replicaConnectionsForReplicationFactor(replicationFactor) foreach { connection ⇒ - (connection !! (command, remoteDaemonAckTimeout)) match { + (connection ? (command, remoteDaemonAckTimeout)).as[Status] match { case Some(Success) ⇒ - EventHandler.debug(this, - "Replica for [%s] successfully created on [%s]" - .format(actorRef.address, connection)) + EventHandler.debug(this, "Replica for [%s] successfully created".format(actorRef.address)) case Some(Failure(cause)) ⇒ EventHandler.error(cause, this, cause.toString) @@ -588,7 +680,7 @@ class DefaultClusterNode private[akka] ( case None ⇒ val error = new ClusterException( - "Operation to instantiate replicas throughout the cluster timed out, cause of error unknow") + "Operation to instantiate replicas throughout the cluster timed out") EventHandler.error(error, this, error.toString) throw error } @@ -604,8 +696,9 @@ class DefaultClusterNode private[akka] ( releaseActorOnAllNodes(uuid) locallyCheckedOutActors.remove(uuid) + // warning: ordering matters here - ignore[ZkNoNodeException](zkClient.deleteRecursive(actorAddressToUuidsPathFor(actorAddressForUuid(uuid)))) // remove ADDRESS to UUID mapping + ignore[ZkNoNodeException](zkClient.deleteRecursive(actorAddressToUuidsPathFor(actorAddressForUuid(uuid)))) // FIXME remove ADDRESS to UUID mapping? ignore[ZkNoNodeException](zkClient.deleteRecursive(actorAtNodePathFor(nodeAddress.nodeName, uuid))) ignore[ZkNoNodeException](zkClient.deleteRecursive(actorRegistryPathFor(uuid))) ignore[ZkNoNodeException](zkClient.deleteRecursive(actorLocationsPathFor(uuid))) @@ -650,20 +743,17 @@ class DefaultClusterNode private[akka] ( * Checks out an actor for use on this node, e.g. checked out as a 'LocalActorRef' but it makes it available * for remote access through lookup by its UUID. */ - def use[T <: Actor](actorAddress: String): Option[LocalActorRef] = use(actorAddress, formatForActor(actorAddress)) + def use[T <: Actor](actorAddress: String): Option[ActorRef] = use(actorAddress, formatForActor(actorAddress)) /** * Checks out an actor for use on this node, e.g. checked out as a 'LocalActorRef' but it makes it available * for remote access through lookup by its UUID. */ - def use[T <: Actor](actorAddress: String, format: Serializer): Option[LocalActorRef] = if (isConnected.isOn) { + def use[T <: Actor](actorAddress: String, format: Serializer): Option[ActorRef] = if (isConnected.isOn) { import akka.serialization.ActorSerialization._ actorUuidsForActorAddress(actorAddress) map { uuid ⇒ - EventHandler.debug(this, - "Checking out actor with UUID [%s] to be used on node [%s] as local actor" - .format(uuid, nodeAddress.nodeName)) ignore[ZkNodeExistsException](zkClient.createPersistent(actorAtNodePathFor(nodeAddress.nodeName, uuid), true)) ignore[ZkNodeExistsException](zkClient.createEphemeral(actorLocationsPathFor(uuid, nodeAddress))) @@ -685,15 +775,15 @@ class DefaultClusterNode private[akka] ( }) 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 + val actor = fromBinary[T](bytes, remoteServerAddress) + EventHandler.debug(this, + "Checking out actor [%s] to be used on node [%s] as local actor" + .format(actor, nodeAddress.nodeName)) actor.start() - actor.asInstanceOf[LocalActorRef] + actor case Right(exception) ⇒ throw exception } - } headOption // FIXME should not be an array at all coming here + } headOption // FIXME should not be an array at all coming here but an Option[ActorRef] } else None /** @@ -703,14 +793,15 @@ class DefaultClusterNode private[akka] ( isConnected ifOn { EventHandler.debug(this, "Using (checking out) all actors with UUID [%s] on all nodes in cluster".format(uuid)) + val command = RemoteDaemonMessageProtocol.newBuilder .setMessageType(USE) .setActorUuid(uuidToUuidProtocol(uuid)) .build + membershipNodes foreach { node ⇒ replicaConnections.get(node) foreach { - case (_, connection) ⇒ - connection ! command + case (_, connection) ⇒ connection ! command } } } @@ -774,8 +865,8 @@ class DefaultClusterNode private[akka] ( def ref(actorAddress: String, router: RouterType): ActorRef = if (isConnected.isOn) { val addresses = addressesForActor(actorAddress) EventHandler.debug(this, - "Checking out cluster actor ref with address [%s] and router [%s] connected to [\n\t%s]" - .format(actorAddress, router, addresses.mkString("\n\t"))) + "Checking out cluster actor ref with address [%s] and router [%s] on [%s] connected to [\n\t%s]" + .format(actorAddress, router, remoteServerAddress, addresses.map(_._2).mkString("\n\t"))) val actorRef = Router newRouter (router, addresses, actorAddress, Actor.TIMEOUT) addresses foreach { case (_, address) ⇒ clusterActorRefs.put(address, actorRef) } @@ -953,11 +1044,15 @@ class DefaultClusterNode private[akka] ( * Send a function 'Function0[Unit]' to be invoked on a random number of nodes (defined by 'replicationFactor' argument). */ def send(f: Function0[Unit], replicationFactor: Int) { - val message = RemoteDaemonMessageProtocol.newBuilder - .setMessageType(FUNCTION_FUN0_UNIT) - .setPayload(ByteString.copyFrom(Serializers.Java.toBinary(f))) - .build - replicaConnectionsForReplicationFactor(replicationFactor) foreach (_ ! message) + Serialization.serialize(f) match { + case Left(error) ⇒ throw error + case Right(bytes) ⇒ + val message = RemoteDaemonMessageProtocol.newBuilder + .setMessageType(FUNCTION_FUN0_UNIT) + .setPayload(ByteString.copyFrom(bytes)) + .build + replicaConnectionsForReplicationFactor(replicationFactor) foreach (_ ! message) + } } /** @@ -965,12 +1060,16 @@ class DefaultClusterNode private[akka] ( * Returns an 'Array' with all the 'Future's from the computation. */ def send(f: Function0[Any], replicationFactor: Int): List[Future[Any]] = { - val message = RemoteDaemonMessageProtocol.newBuilder - .setMessageType(FUNCTION_FUN0_ANY) - .setPayload(ByteString.copyFrom(Serializers.Java.toBinary(f))) - .build - val results = replicaConnectionsForReplicationFactor(replicationFactor) map (_ !!! message) - results.toList.asInstanceOf[List[Future[Any]]] + Serialization.serialize(f) match { + case Left(error) ⇒ throw error + case Right(bytes) ⇒ + val message = RemoteDaemonMessageProtocol.newBuilder + .setMessageType(FUNCTION_FUN0_ANY) + .setPayload(ByteString.copyFrom(bytes)) + .build + val results = replicaConnectionsForReplicationFactor(replicationFactor) map (_ ? message) + results.toList.asInstanceOf[List[Future[Any]]] + } } /** @@ -978,11 +1077,15 @@ class DefaultClusterNode private[akka] ( * with the argument speficied. */ def send(f: Function1[Any, Unit], arg: Any, replicationFactor: Int) { - val message = RemoteDaemonMessageProtocol.newBuilder - .setMessageType(FUNCTION_FUN1_ARG_UNIT) - .setPayload(ByteString.copyFrom(Serializers.Java.toBinary((f, arg)))) - .build - replicaConnectionsForReplicationFactor(replicationFactor) foreach (_ ! message) + Serialization.serialize((f, arg)) match { + case Left(error) ⇒ throw error + case Right(bytes) ⇒ + val message = RemoteDaemonMessageProtocol.newBuilder + .setMessageType(FUNCTION_FUN1_ARG_UNIT) + .setPayload(ByteString.copyFrom(bytes)) + .build + replicaConnectionsForReplicationFactor(replicationFactor) foreach (_ ! message) + } } /** @@ -991,12 +1094,16 @@ class DefaultClusterNode private[akka] ( * Returns an 'Array' with all the 'Future's from the computation. */ def send(f: Function1[Any, Any], arg: Any, replicationFactor: Int): List[Future[Any]] = { - val message = RemoteDaemonMessageProtocol.newBuilder - .setMessageType(FUNCTION_FUN1_ARG_ANY) - .setPayload(ByteString.copyFrom(Serializers.Java.toBinary((f, arg)))) - .build - val results = replicaConnectionsForReplicationFactor(replicationFactor) map (_ !!! message) - results.toList.asInstanceOf[List[Future[Any]]] + Serialization.serialize((f, arg)) match { + case Left(error) ⇒ throw error + case Right(bytes) ⇒ + val message = RemoteDaemonMessageProtocol.newBuilder + .setMessageType(FUNCTION_FUN1_ARG_ANY) + .setPayload(ByteString.copyFrom(bytes)) + .build + val results = replicaConnectionsForReplicationFactor(replicationFactor) map (_ ? message) + results.toList.asInstanceOf[List[Future[Any]]] + } } // ======================================= @@ -1086,9 +1193,9 @@ class DefaultClusterNode private[akka] ( .format(nodeAddress.clusterName, nodeAddress.nodeName, nodeAddress.port, zkServerAddresses, serializer)) EventHandler.info(this, "Starting up remote server [%s]".format(remoteServerAddress.toString)) createRootClusterNode() - val isLeader = joinLeaderElection + val isLeader = joinLeaderElection() if (isLeader) createNodeStructureIfNeeded() - registerListeners + registerListeners() joinMembershipNode() joinActorsAtAddressNode() fetchMembershipChildrenNodes() @@ -1125,7 +1232,8 @@ class DefaultClusterNode private[akka] ( if (numberOfReplicas < replicationFactor) { throw new IllegalArgumentException( - "Replication factor [" + replicationFactor + "] is greater than the number of available nodes [" + numberOfReplicas + "]") + "Replication factor [" + replicationFactor + + "] is greater than the number of available nodes [" + numberOfReplicas + "]") } else if (numberOfReplicas == replicationFactor) { replicas = replicas ++ replicaConnectionsAsArray } else { @@ -1164,7 +1272,7 @@ class DefaultClusterNode private[akka] ( } catch { 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, "") + EventHandler.error(error, this, error.toString) throw error } } @@ -1173,7 +1281,7 @@ class DefaultClusterNode private[akka] ( ignore[ZkNodeExistsException](zkClient.createPersistent(actorsAtNodePathFor(nodeAddress.nodeName))) } - private[cluster] def joinLeaderElection: Boolean = { + private[cluster] def joinLeaderElection(): Boolean = { EventHandler.info(this, "Node [%s] is joining leader election".format(nodeAddress.nodeName)) leaderLock.lock } @@ -1217,22 +1325,26 @@ class DefaultClusterNode private[akka] ( homeAddress.setAccessible(true) homeAddress.set(actor, Some(remoteServerAddress)) - remoteService.register(uuid, actor) + remoteService.register(actorAddress, 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 - } + Serialization.serialize((from, to)) match { + case Left(error) ⇒ throw error + case Right(bytes) ⇒ + val command = RemoteDaemonMessageProtocol.newBuilder + .setMessageType(FAIL_OVER_CONNECTIONS) + .setPayload(ByteString.copyFrom(bytes)) + .build + membershipNodes foreach { node ⇒ + replicaConnections.get(node) foreach { + case (_, connection) ⇒ + connection ! command + } + } } } } @@ -1302,7 +1414,7 @@ class DefaultClusterNode private[akka] ( } } - private def registerListeners = { + private def registerListeners() = { zkClient.subscribeStateChanges(stateListener) zkClient.subscribeChildChanges(MEMBERSHIP_NODE, membershipListener) } @@ -1456,12 +1568,10 @@ trait ErrorHandler { object RemoteClusterDaemon { val ADDRESS = "akka-cluster-daemon".intern - // FIXME configure functionServerDispatcher to what? - val functionServerDispatcher = Dispatchers.newDispatcher("akka:cloud:cluster:function:server").build + // FIXME configure computeGridDispatcher to what? + val computeGridDispatcher = Dispatchers.newDispatcher("akka:cloud:cluster:compute-grid").build } -// FIXME supervise RemoteClusterDaemon - /** * @author Jonas Bonér */ @@ -1472,6 +1582,10 @@ class RemoteClusterDaemon(cluster: ClusterNode) extends Actor { self.dispatcher = Dispatchers.newPinnedDispatcher(self) + override def preRestart(reason: Throwable) { + EventHandler.debug(this, "RemoteClusterDaemon failed due to [%s] restarting...".format(reason)) + } + def receive: Receive = { case message: RemoteDaemonMessageProtocol ⇒ EventHandler.debug(this, "Received command to RemoteClusterDaemon [%s]".format(message)) @@ -1528,7 +1642,7 @@ class RemoteClusterDaemon(cluster: ClusterNode) extends Actor { case FUNCTION_FUN0_UNIT ⇒ actorOf(new Actor() { - self.dispatcher = functionServerDispatcher + self.dispatcher = computeGridDispatcher def receive = { case f: Function0[Unit] ⇒ try { @@ -1541,7 +1655,7 @@ class RemoteClusterDaemon(cluster: ClusterNode) extends Actor { case FUNCTION_FUN0_ANY ⇒ actorOf(new Actor() { - self.dispatcher = functionServerDispatcher + self.dispatcher = computeGridDispatcher def receive = { case f: Function0[Any] ⇒ try { @@ -1554,7 +1668,7 @@ class RemoteClusterDaemon(cluster: ClusterNode) extends Actor { case FUNCTION_FUN1_ARG_UNIT ⇒ actorOf(new Actor() { - self.dispatcher = functionServerDispatcher + self.dispatcher = computeGridDispatcher def receive = { case (fun: Function[Any, Unit], param: Any) ⇒ try { @@ -1567,7 +1681,7 @@ class RemoteClusterDaemon(cluster: ClusterNode) extends Actor { case FUNCTION_FUN1_ARG_ANY ⇒ actorOf(new Actor() { - self.dispatcher = functionServerDispatcher + self.dispatcher = computeGridDispatcher def receive = { case (fun: Function[Any, Unit], param: Any) ⇒ try { @@ -1583,6 +1697,6 @@ class RemoteClusterDaemon(cluster: ClusterNode) extends Actor { } private def payloadFor[T](message: RemoteDaemonMessageProtocol, clazz: Class[T]): T = { - Serializers.Java.fromBinary(message.getPayload.toByteArray, Some(clazz)).asInstanceOf[T] + Serialization.serialize(message.getPayload.toByteArray, Some(clazz)).asInstanceOf[T] } } diff --git a/akka-cluster/src/main/scala/akka/cluster/ClusterActorRef.scala b/akka-cluster/src/main/scala/akka/cluster/ClusterActorRef.scala index f107904892..494fa42fe1 100644 --- a/akka-cluster/src/main/scala/akka/cluster/ClusterActorRef.scala +++ b/akka-cluster/src/main/scala/akka/cluster/ClusterActorRef.scala @@ -6,12 +6,17 @@ package akka.cluster import Cluster._ import akka.actor._ -import akka.actor.Actor._ +import Actor._ +import akka.dispatch._ +import akka.util._ +import ReflectiveAccess._ +import ClusterModule._ import akka.event.EventHandler -import akka.dispatch.Promise +import akka.dispatch.Future import java.net.InetSocketAddress import java.util.concurrent.atomic.AtomicReference +import java.util.{ Map ⇒ JMap } import com.eaio.uuid.UUID @@ -20,32 +25,39 @@ import com.eaio.uuid.UUID */ class ClusterActorRef private[akka] ( inetSocketAddresses: Array[Tuple2[UUID, InetSocketAddress]], - actorAddress: String, - timeout: Long, - val replicationStrategy: ReplicationStrategy) - extends RemoteActorRef(null, actorAddress, timeout, None) { // FIXME UGLY HACK - should not extend RemoteActorRef - this: ClusterActorRef with Router.Router ⇒ + val address: String, + _timeout: Long) + extends ActorRef with ScalaActorRef { this: Router.Router ⇒ - EventHandler.debug(this, - "Creating a ClusterActorRef for actor with address [%s] with connections [\n\t%s]" - .format(actorAddress, inetSocketAddresses.mkString("\n\t"))) + timeout = _timeout private[akka] val inetSocketAddressToActorRefMap = new AtomicReference[Map[InetSocketAddress, ActorRef]]( (Map[InetSocketAddress, ActorRef]() /: inetSocketAddresses) { - case (map, (uuid, inetSocketAddress)) ⇒ map + (inetSocketAddress -> createRemoteActorRef(actorAddress, inetSocketAddress)) + case (map, (uuid, inetSocketAddress)) ⇒ map + (inetSocketAddress -> createRemoteActorRef(address, inetSocketAddress)) }) + ClusterModule.ensureEnabled() + start() + def connections: Map[InetSocketAddress, ActorRef] = inetSocketAddressToActorRefMap.get - override def postMessageToMailbox(message: Any, senderOption: Option[ActorRef]): Unit = - route(message)(senderOption) + override def postMessageToMailbox(message: Any, channel: UntypedChannel): Unit = { + val sender = channel match { + case ref: ActorRef ⇒ Some(ref) + case _ ⇒ None + } + route(message)(sender) + } - override def postMessageToMailboxAndCreateFutureResultWithTimeout[T]( + override def postMessageToMailboxAndCreateFutureResultWithTimeout( message: Any, timeout: Long, - senderOption: Option[ActorRef], - senderFuture: Option[Promise[T]]): Promise[T] = { - route[T](message, timeout)(senderOption).asInstanceOf[Promise[T]] + channel: UntypedChannel): Future[Any] = { + val sender = channel match { + case ref: ActorRef ⇒ Some(ref) + case _ ⇒ None + } + route[Any](message, timeout)(sender) } private[akka] def failOver(fromInetSocketAddress: InetSocketAddress, toInetSocketAddress: InetSocketAddress) { @@ -60,4 +72,53 @@ class ClusterActorRef private[akka] ( private def createRemoteActorRef(actorAddress: String, inetSocketAddress: InetSocketAddress) = { RemoteActorRef(inetSocketAddress, actorAddress, Actor.TIMEOUT, None) } + + def start(): ActorRef = synchronized { + _status = ActorRefInternals.RUNNING + this + } + + def stop() { + synchronized { + if (_status == ActorRefInternals.RUNNING) { + _status = ActorRefInternals.SHUTDOWN + postMessageToMailbox(RemoteActorSystemMessage.Stop, None) + } + } + } + + // ==== NOT SUPPORTED ==== + // FIXME move these methods and the same ones in RemoteActorRef to a base class - now duplicated + def dispatcher_=(md: MessageDispatcher) { + unsupported + } + def dispatcher: MessageDispatcher = unsupported + def link(actorRef: ActorRef) { + unsupported + } + def unlink(actorRef: ActorRef) { + unsupported + } + def startLink(actorRef: ActorRef): ActorRef = unsupported + def supervisor: Option[ActorRef] = unsupported + def linkedActors: JMap[Uuid, ActorRef] = unsupported + protected[akka] def mailbox: AnyRef = unsupported + protected[akka] def mailbox_=(value: AnyRef): AnyRef = unsupported + protected[akka] def handleTrapExit(dead: ActorRef, reason: Throwable) { + unsupported + } + protected[akka] def restart(reason: Throwable, maxNrOfRetries: Option[Int], withinTimeRange: Option[Int]) { + unsupported + } + protected[akka] def restartLinkedActors(reason: Throwable, maxNrOfRetries: Option[Int], withinTimeRange: Option[Int]) { + unsupported + } + protected[akka] def invoke(messageHandle: MessageInvocation) { + unsupported + } + protected[akka] def supervisor_=(sup: Option[ActorRef]) { + unsupported + } + protected[akka] def actorInstance: AtomicReference[Actor] = unsupported + private def unsupported = throw new UnsupportedOperationException("Not supported for RemoteActorRef") } diff --git a/akka-cluster/src/main/scala/akka/cluster/ClusterDeployer.scala b/akka-cluster/src/main/scala/akka/cluster/ClusterDeployer.scala index 19b89628a1..070a52d96b 100644 --- a/akka-cluster/src/main/scala/akka/cluster/ClusterDeployer.scala +++ b/akka-cluster/src/main/scala/akka/cluster/ClusterDeployer.scala @@ -27,7 +27,7 @@ import java.util.concurrent.atomic.AtomicReference /** * A ClusterDeployer is responsible for deploying a Deploy. * - * big question is: what does Deploy mean? + * FIXME Document: what does Deploy mean? * * @author Jonas Bonér */ @@ -35,11 +35,16 @@ object ClusterDeployer { val clusterName = Cluster.name val nodeName = Config.nodename val clusterPath = "/%s" format clusterName - val clusterDeploymentLockPath = clusterPath + "/deployment-lock" + val deploymentPath = clusterPath + "/deployment" - val baseNodes = List(clusterPath, clusterDeploymentLockPath, deploymentPath) val deploymentAddressPath = deploymentPath + "/%s" + val deploymentCoordinationPath = clusterPath + "/deployment-coordination" + val deploymentInProgressLockPath = deploymentCoordinationPath + "/in-progress" + val isDeploymentCompletedInClusterLockPath = deploymentCoordinationPath + "/completed" // should not be part of baseNodes + + val baseNodes = List(clusterPath, deploymentPath, deploymentCoordinationPath, deploymentInProgressLockPath) + private val isConnected = new Switch(false) private val deploymentCompleted = new CountDownLatch(1) @@ -49,7 +54,7 @@ object ClusterDeployer { Cluster.connectionTimeout, Cluster.defaultSerializer) - private val clusterDeploymentLockListener = new LockListener { + private val deploymentInProgressLockListener = new LockListener { def lockAcquired() { EventHandler.debug(this, "Clustered deployment started") } @@ -60,13 +65,11 @@ object ClusterDeployer { } } - private val deploymentLock = new WriteLock( - zkClient.connection.getZookeeper, clusterDeploymentLockPath, null, clusterDeploymentLockListener) { - private val ownerIdField = classOf[WriteLock].getDeclaredField("ownerId") - ownerIdField.setAccessible(true) - - def leader: String = ownerIdField.get(this).asInstanceOf[String] - } + private val deploymentInProgressLock = new WriteLock( + zkClient.connection.getZookeeper, + deploymentInProgressLockPath, + null, + deploymentInProgressLockListener) private val systemDeployments: List[Deploy] = Nil @@ -79,6 +82,7 @@ object ClusterDeployer { deployment ← zkClient.readData(deploymentAddressPath.format(child)).asInstanceOf[Deploy] } zkClient.delete(deploymentAddressPath.format(deployment.address)) + invalidateDeploymentInCluster() } catch { case e: Exception ⇒ handleError(new DeploymentException("Could not undeploy all deployment data in ZooKeeper due to: " + e)) @@ -124,8 +128,6 @@ object ClusterDeployer { } private[akka] def init(deployments: List[Deploy]) { - println("===============================================================") - println("------------ INIT 1") isConnected switchOn { EventHandler.info(this, "Initializing cluster deployer") @@ -141,31 +143,21 @@ object ClusterDeployer { } } - println("------------ INIT 2") val allDeployments = deployments ::: systemDeployments - ///=========================================================== - // FIXME need a flag 'deploymentDone' in ZK and to wrap the deployment in 'if (!deploymentDone) { .. }', since now the deployment is only protected by lock during the actual deployment, if node comes in later then deployment is repeated on that node again - ///=========================================================== + if (!isDeploymentCompletedInCluster) { + if (deploymentInProgressLock.lock()) { + // try to be the one doing the clustered deployment + EventHandler.info(this, "Deploying to cluster [\n" + allDeployments.mkString("\n\t") + "\n]") + allDeployments foreach (deploy(_)) // deploy + markDeploymentCompletedInCluster() + deploymentInProgressLock.unlock() // signal deployment complete - if (deploymentLock.lock()) { - println("------------ INIT 3") - // try to be the one doing the clustered deployment - EventHandler.info(this, "Deploying to cluster [\n" + allDeployments.mkString("\n\t") + "\n]") - - println("------------ INIT 4") - allDeployments foreach (deploy(_)) // deploy - println("------------ INIT 5") - - // FIXME need to set deployment done flag - - deploymentLock.unlock() // signal deployment complete - } else { - println("------------ INIT WAITING") - deploymentCompleted.await() // wait until deployment is completed by other "master" node + } else { + deploymentCompleted.await() // wait until deployment is completed by other "master" node + } } - println("------------ INIT 6") // fetch clustered deployments and deploy them locally fetchDeploymentsFromCluster foreach (LocalDeployer.deploy(_)) } @@ -183,14 +175,29 @@ object ClusterDeployer { zkClient.writeData(path, deployment) } catch { case e: NullPointerException ⇒ - handleError(new DeploymentException("Could not store deployment data [" + deployment + "] in ZooKeeper since client session is closed")) + handleError(new DeploymentException( + "Could not store deployment data [" + deployment + + "] in ZooKeeper since client session is closed")) case e: Exception ⇒ - handleError(new DeploymentException("Could not store deployment data [" + deployment + "] in ZooKeeper due to: " + e)) + handleError(new DeploymentException( + "Could not store deployment data [" + + deployment + "] in ZooKeeper due to: " + e)) } } } } + private def markDeploymentCompletedInCluster() { + ignore[ZkNodeExistsException](zkClient.create(isDeploymentCompletedInClusterLockPath, null, CreateMode.PERSISTENT)) + } + + private def isDeploymentCompletedInCluster = zkClient.exists(isDeploymentCompletedInClusterLockPath) + + // FIXME in future - add watch to this path to be able to trigger redeployment, and use this method to trigger redeployment + private def invalidateDeploymentInCluster() { + ignore[ZkNoNodeException](zkClient.delete(isDeploymentCompletedInClusterLockPath)) + } + private def ensureRunning[T](body: ⇒ T): T = { if (isConnected.isOn) body else throw new IllegalStateException("ClusterDeployer is not running") diff --git a/akka-cluster/src/main/scala/akka/cluster/RawStorage.scala b/akka-cluster/src/main/scala/akka/cluster/RawStorage.scala deleted file mode 100644 index d0e58958d6..0000000000 --- a/akka-cluster/src/main/scala/akka/cluster/RawStorage.scala +++ /dev/null @@ -1,136 +0,0 @@ -package akka.cluster - -import zookeeper.AkkaZkClient -import akka.AkkaException -import org.apache.zookeeper.{ KeeperException, CreateMode } -import org.apache.zookeeper.data.Stat -import scala.Some -import java.util.concurrent.ConcurrentHashMap -import org.apache.zookeeper.KeeperException.NoNodeException - -/** - * Simple abstraction to store an Array of bytes based on some String key. - * - * Nothing is being said about ACID, transactions etc. It depends on the implementation - * of this Storage interface of what is and isn't done on the lowest level. - * - * TODO: Perhaps add a version to the store to prevent lost updates using optimistic locking. - * (This is supported by ZooKeeper). - * TODO: Class is up for better names. - * TODO: Instead of a String as key, perhaps also a byte-array. - */ -trait RawStorage { - - /** - * Inserts a byte-array based on some key. - * - * @throws NodeExistsException when a Node with the given Key already exists. - */ - def insert(key: String, bytes: Array[Byte]): Unit - - /** - * Stores a array of bytes based on some key. - * - * @throws MissingNodeException when the Node with the given key doesn't exist. - */ - def update(key: String, bytes: Array[Byte]): Unit - - /** - * Loads the given entry. If it exists, a 'Some[Array[Byte]]' will be returned, else a None. - */ - def load(key: String): Option[Array[Byte]] -} - -/** - * An AkkaException thrown by the RawStorage module. - */ -class RawStorageException(msg: String = null, cause: java.lang.Throwable = null) extends AkkaException(msg, cause) - -/** - * * - * A RawStorageException thrown when an operation is done on a non existing node. - */ -class MissingNodeException(msg: String = null, cause: java.lang.Throwable = null) extends RawStorageException(msg, cause) - -/** - * A RawStorageException thrown when an operation is done on an existing node, but no node was expected. - */ -class NodeExistsException(msg: String = null, cause: java.lang.Throwable = null) extends RawStorageException(msg, cause) - -/** - * A RawStorage implementation based on ZooKeeper. - * - * The store method is atomic: - * - so everything is written or nothing is written - * - is isolated, so threadsafe, - * but it will not participate in any transactions. - * //todo: unclear, is only a single connection used in the JVM?? - * - */ -class ZooKeeperRawStorage(zkClient: AkkaZkClient) extends RawStorage { - - override def load(key: String) = try { - Some(zkClient.connection.readData(key, new Stat, false)) - } catch { - case e: KeeperException.NoNodeException ⇒ None - case e: KeeperException ⇒ throw new RawStorageException("failed to load key" + key, e) - } - - override def insert(key: String, bytes: Array[Byte]) { - try { - zkClient.connection.create(key, bytes, CreateMode.PERSISTENT); - } catch { - case e: KeeperException.NodeExistsException ⇒ throw new NodeExistsException("failed to insert key" + key, e) - case e: KeeperException ⇒ throw new RawStorageException("failed to insert key" + key, e) - } - } - - override def update(key: String, bytes: Array[Byte]) { - try { - zkClient.connection.writeData(key, bytes) - } catch { - case e: KeeperException.NoNodeException ⇒ throw new MissingNodeException("failed to update key", e) - case e: KeeperException ⇒ throw new RawStorageException("failed to update key", e) - } - } -} - -/** - * An in memory {@link RawStore} implementation. Useful for testing purposes. - */ -class InMemoryRawStorage extends RawStorage { - - private val map = new ConcurrentHashMap[String, Array[Byte]]() - - def load(key: String) = Option(map.get(key)) - - def insert(key: String, bytes: Array[Byte]) { - val previous = map.putIfAbsent(key, bytes) - if (previous != null) throw new NodeExistsException("failed to insert key " + key) - } - - def update(key: String, bytes: Array[Byte]) { - val previous = map.put(key, bytes) - if (previous == null) throw new NoNodeException("failed to update key " + key) - } -} - -//TODO: To minimize the number of dependencies, should the RawStorage not be placed in a seperate module? -//class VoldemortRawStorage(storeClient: StoreClient) extends RawStorage { -// -// def load(Key: String) = { -// try { -// -// } catch { -// case -// } -// } -// -// override def insert(key: String, bytes: Array[Byte]) { -// throw new UnsupportedOperationException() -// } -// -// def update(key: String, bytes: Array[Byte]) { -// throw new UnsupportedOperationException() -// } -//} \ No newline at end of file diff --git a/akka-cluster/src/main/scala/akka/cluster/ReplicatedClusterRef.scala b/akka-cluster/src/main/scala/akka/cluster/ReplicatedClusterRef.scala deleted file mode 100644 index 4b075c7f91..0000000000 --- a/akka-cluster/src/main/scala/akka/cluster/ReplicatedClusterRef.scala +++ /dev/null @@ -1,105 +0,0 @@ -package akka.cluster - -/** - * Copyright (C) 2009-2011 Scalable Solutions AB - */ -import Cluster._ - -import akka.actor._ -import akka.remote.MessageSerializer -import akka.event.EventHandler -import akka.config.Supervision._ -import akka.dispatch._ - -import java.net.InetSocketAddress -import java.util.concurrent.atomic.AtomicReference -import java.util.{ Map ⇒ JMap } - -/** - * @author Jonas Bonér - */ -trait Replicable { this: Actor ⇒ -} - -/** - * @author Jonas Bonér - */ -sealed trait ReplicationStrategy - -object ReplicationStrategy { - case object Transient extends ReplicationStrategy - case object WriteThrough extends ReplicationStrategy - case object WriteBehind extends ReplicationStrategy -} - -/** - * @author Jonas Bonér - */ -class ReplicatedActorRef private[akka] (actorRef: ActorRef, val address: String) extends ActorRef with ScalaActorRef { - - private lazy val txLog = { - EventHandler.debug(this, "Creating a ReplicatedActorRef for Actor [%s]".format(address)) - TransactionLog.newLogFor(uuid.toString) - } - - def invoke(messageHandle: MessageInvocation) { - actorRef.invoke(messageHandle) - txLog.recordEntry(MessageSerializer.serialize(messageHandle.message).toByteArray) - } - - def start(): ActorRef = { - EventHandler.debug(this, "Starting ReplicatedActorRef for Actor [%s] with transaction log [%s]" - .format(address, txLog.logId)) - actorRef.start() - } - - def stop() { - txLog.delete() - actorRef.stop() - } - - override def setFaultHandler(handler: FaultHandlingStrategy) { - actorRef.setFaultHandler(handler) - } - override def getFaultHandler: FaultHandlingStrategy = actorRef.getFaultHandler() - override def setLifeCycle(lifeCycle: LifeCycle) { - actorRef.setLifeCycle(lifeCycle) - } - override def getLifeCycle: LifeCycle = actorRef.getLifeCycle - def dispatcher_=(md: MessageDispatcher) { - actorRef.dispatcher_=(md) - } - def dispatcher: MessageDispatcher = actorRef.dispatcher - def link(actorRef: ActorRef) { - actorRef.link(actorRef) - } - def unlink(actorRef: ActorRef) { - actorRef.unlink(actorRef) - } - def startLink(actorRef: ActorRef): ActorRef = actorRef.startLink(actorRef) - def supervisor: Option[ActorRef] = actorRef.supervisor - def linkedActors: JMap[Uuid, ActorRef] = actorRef.linkedActors - protected[akka] def postMessageToMailbox(message: Any, senderOption: Option[ActorRef]) { - actorRef.postMessageToMailbox(message, senderOption) - } - protected[akka] def postMessageToMailboxAndCreateFutureResultWithTimeout[T]( - message: Any, - timeout: Long, - senderOption: Option[ActorRef], - senderFuture: Option[Promise[T]]): Promise[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) - } - protected[akka] def mailbox: AnyRef = actorRef.mailbox - protected[akka] def mailbox_=(value: AnyRef): AnyRef = actorRef.mailbox_=(value) - protected[akka] def handleTrapExit(dead: ActorRef, reason: Throwable) { - actorRef.handleTrapExit(dead, reason) - } - protected[akka] def restart(reason: Throwable, maxNrOfRetries: Option[Int], withinTimeRange: Option[Int]) { - actorRef.restart(reason, maxNrOfRetries, withinTimeRange) - } - protected[akka] def restartLinkedActors(reason: Throwable, maxNrOfRetries: Option[Int], withinTimeRange: Option[Int]) { - actorRef.restartLinkedActors(reason, maxNrOfRetries, withinTimeRange) - } -} diff --git a/akka-cluster/src/main/scala/akka/cluster/Routing.scala b/akka-cluster/src/main/scala/akka/cluster/Routing.scala index 1bde759ca6..838efc729f 100644 --- a/akka-cluster/src/main/scala/akka/cluster/Routing.scala +++ b/akka-cluster/src/main/scala/akka/cluster/Routing.scala @@ -27,12 +27,11 @@ object Router { routerType: RouterType, inetSocketAddresses: Array[Tuple2[UUID, InetSocketAddress]], actorAddress: String, - timeout: Long, - replicationStrategy: ReplicationStrategy = ReplicationStrategy.WriteThrough): ClusterActorRef = { + timeout: Long): ClusterActorRef = { routerType match { - case Direct ⇒ new ClusterActorRef(inetSocketAddresses, actorAddress, timeout, replicationStrategy) with Direct - case Random ⇒ new ClusterActorRef(inetSocketAddresses, actorAddress, timeout, replicationStrategy) with Random - case RoundRobin ⇒ new ClusterActorRef(inetSocketAddresses, actorAddress, timeout, replicationStrategy) with RoundRobin + case Direct ⇒ new ClusterActorRef(inetSocketAddresses, actorAddress, timeout) with Direct + case Random ⇒ new ClusterActorRef(inetSocketAddresses, actorAddress, timeout) with Random + case RoundRobin ⇒ new ClusterActorRef(inetSocketAddresses, actorAddress, timeout) 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") @@ -57,7 +56,7 @@ object Router { } def route[T](message: Any, timeout: Long)(implicit sender: Option[ActorRef]): Future[T] = next match { - case Some(actor) ⇒ actor.!!!(message, timeout)(sender) + case Some(actor) ⇒ actor.?(message, timeout)(sender).asInstanceOf[Future[T]] case _ ⇒ throwNoConnectionsError() } diff --git a/akka-cluster/src/main/scala/akka/cluster/Storage.scala b/akka-cluster/src/main/scala/akka/cluster/Storage.scala new file mode 100755 index 0000000000..32519e56d7 --- /dev/null +++ b/akka-cluster/src/main/scala/akka/cluster/Storage.scala @@ -0,0 +1,320 @@ +package akka.cluster + +import zookeeper.AkkaZkClient +import akka.AkkaException +import org.apache.zookeeper.{ KeeperException, CreateMode } +import org.apache.zookeeper.data.Stat +import java.util.concurrent.ConcurrentHashMap +import annotation.tailrec +import java.lang.{ UnsupportedOperationException, RuntimeException } + +/** + * Simple abstraction to store an Array of bytes based on some String key. + * + * Nothing is being said about ACID, transactions etc. It depends on the implementation + * of this Storage interface of what is and isn't done on the lowest level. + * + * The amount of data that is allowed to be insert/updated is implementation specific. The InMemoryStorage + * has no limits, but the ZooKeeperStorage has a maximum size of 1 mb. + * + * TODO: Class is up for better names. + * TODO: Instead of a String as key, perhaps also a byte-array. + */ +trait Storage { + + /** + * Loads the VersionedData for the given key. + * + * @param key: the key of the VersionedData to load. + * @return the VersionedData for the given entry. + * @throws MissingDataException if the entry with the given key doesn't exist. + * @throws StorageException if anything goes wrong while accessing the storage + */ + def load(key: String): VersionedData + + /** + * Loads the VersionedData for the given key and version. + * + * @param key: the key of the VersionedData to load + * @param version the version of the VersionedData to load + * @throws MissingDataException if the data with the given key doesn't exist. + * @throws VersioningException if the version of the data is not the same as the given data. + * @throws StorageException if anything goes wrong while accessing the storage + */ + def load(key: String, version: Long): VersionedData + + /** + * Checks if a VersionedData with the given key exists. + * + * @param key the key to check the existence for. + * @return true if exists, false if not. + * @throws StorageException if anything goes wrong while accessing the storage + */ + def exists(key: String): Boolean + + /** + * Inserts a byte-array based on some key. + * + * @param key the key of the Data to insert. + * @param bytes the data to insert. + * @return the VersionedData + * @throws DataExistsException when VersionedData with the given Key already exists. + * @throws StorageException if anything goes wrong while accessing the storage + */ + def insert(key: String, bytes: Array[Byte]): VersionedData + + /** + * Inserts the data if there is no data for that key, or overwrites it if it is there. + * + * This is the method you want to call if you just want to save something and don't + * care about any lost update issues. + * + * @param key the key of the data + * @param bytes the data to insert + * @return the VersionedData that was stored. + * @throws StorageException if anything goes wrong while accessing the storage + */ + def insertOrOverwrite(key: String, bytes: Array[Byte]): VersionedData + + /** + * Overwrites the current data for the given key. + * + * @param key the key of the data to overwrite + * @param bytes the data to insert. + * @throws ` when the entry with the given key doesn't exist. + * @throws StorageException if anything goes wrong while accessing the storage + */ + def overwrite(key: String, bytes: Array[Byte]): VersionedData + + /** + * @throws StorageException if anything goes wrong while accessing the storage + */ + def update(key: String, versionedData: VersionedData): Unit +} + +/** + * The VersionedData is a container of data (some bytes) and a version (a Long). + */ +class VersionedData(val data: Array[Byte], val version: Long) { + + /** + * Creates an updated VersionedData. What happens is that a new VersionedData object is created with the newData + * and a version that is one higher than the current version. + */ + def createUpdate(newData: Array[Byte]): VersionedData = new VersionedData(newData, version + 1) +} + +/** + * An AkkaException thrown by the Storage module. + */ +class StorageException(msg: String = null, cause: java.lang.Throwable = null) extends AkkaException(msg, cause) + +/** + * * + * A StorageException thrown when an operation is done on a non existing node. + */ +class MissingDataException(msg: String = null, cause: java.lang.Throwable = null) extends StorageException(msg, cause) + +/** + * A StorageException thrown when an operation is done on an existing node, but no node was expected. + */ +class DataExistsException(msg: String = null, cause: java.lang.Throwable = null) extends StorageException(msg, cause) + +/** + * A StorageException thrown when an operation causes an optimistic locking failure. + */ +class VersioningException(msg: String = null, cause: java.lang.Throwable = null) extends StorageException(msg, cause) + +/** + * A Storage implementation based on ZooKeeper. + * + * The store method is atomic: + * - so everything is written or nothing is written + * - is isolated, so threadsafe, + * but it will not participate in any transactions. + * + */ +class ZooKeeperStorage(zkClient: AkkaZkClient) extends Storage { + + def load(key: String) = try { + val stat = new Stat + val arrayOfBytes = zkClient.connection.readData(key, stat, false) + new VersionedData(arrayOfBytes, stat.getVersion) + } catch { + case e: KeeperException.NoNodeException ⇒ throw new MissingDataException( + String.format("Failed to load key [%s]: no data was found", key), e) + case e: KeeperException ⇒ throw new StorageException( + String.format("Failed to load key [%s]", key), e) + } + + def load(key: String, expectedVersion: Long) = try { + val stat = new Stat + val arrayOfBytes = zkClient.connection.readData(key, stat, false) + + if (stat.getVersion != expectedVersion) throw new VersioningException( + "Failed to update key [" + key + "]: version mismatch, expected [" + expectedVersion + "]" + + " but found [" + stat.getVersion + "]") + + new VersionedData(arrayOfBytes, stat.getVersion) + } catch { + case e: KeeperException.NoNodeException ⇒ throw new MissingDataException( + String.format("Failed to load key [%s]: no data was found", key), e) + case e: KeeperException ⇒ throw new StorageException( + String.format("Failed to load key [%s]", key), e) + } + + def insertOrOverwrite(key: String, bytes: Array[Byte]) = { + try { + throw new UnsupportedOperationException() + } catch { + case e: KeeperException.NodeExistsException ⇒ throw new DataExistsException( + String.format("Failed to insert key [%s]: an entry already exists with the same key", key), e) + case e: KeeperException ⇒ throw new StorageException( + String.format("Failed to insert key [%s]", key), e) + } + } + + def insert(key: String, bytes: Array[Byte]): VersionedData = { + try { + zkClient.connection.create(key, bytes, CreateMode.PERSISTENT) + //todo: how to get hold of the reference. + val version: Long = 0 + new VersionedData(bytes, version) + } catch { + case e: KeeperException.NodeExistsException ⇒ throw new DataExistsException( + String.format("Failed to insert key [%s]: an entry already exists with the same key", key), e) + case e: KeeperException ⇒ throw new StorageException( + String.format("Failed to insert key [%s]", key), e) + } + } + + def exists(key: String) = try { + zkClient.connection.exists(key, false) + } catch { + case e: KeeperException ⇒ throw new StorageException( + String.format("Failed to check existance for key [%s]", key), e) + } + + def update(key: String, versionedData: VersionedData) { + try { + zkClient.connection.writeData(key, versionedData.data, versionedData.version.asInstanceOf[Int]) + } catch { + case e: KeeperException.BadVersionException ⇒ throw new VersioningException( + String.format("Failed to update key [%s]: version mismatch", key), e) + case e: KeeperException ⇒ throw new StorageException( + String.format("Failed to update key [%s]", key), e) + } + } + + def overwrite(key: String, bytes: Array[Byte]): VersionedData = { + try { + zkClient.connection.writeData(key, bytes) + throw new RuntimeException() + } catch { + case e: KeeperException.NoNodeException ⇒ throw new MissingDataException( + String.format("Failed to overwrite key [%s]: a previous entry already exists", key), e) + case e: KeeperException ⇒ throw new StorageException( + String.format("Failed to overwrite key [%s]", key), e) + } + } +} + +object InMemoryStorage { + val InitialVersion = 0; +} + +/** + * An in memory {@link RawStore} implementation. Useful for testing purposes. + */ +final class InMemoryStorage extends Storage { + + private val map = new ConcurrentHashMap[String, VersionedData]() + + def load(key: String) = { + val result = map.get(key) + + if (result == null) throw new MissingDataException( + String.format("Failed to load key [%s]: no data was found", key)) + + result + } + + def load(key: String, expectedVersion: Long) = { + val result = load(key) + + if (result.version != expectedVersion) throw new VersioningException( + "Failed to load key [" + key + "]: version mismatch, expected [" + result.version + "] " + + "but found [" + expectedVersion + "]") + + result + } + + def exists(key: String) = map.containsKey(key) + + def insert(key: String, bytes: Array[Byte]): VersionedData = { + val version: Long = InMemoryStorage.InitialVersion + val result = new VersionedData(bytes, version) + + val previous = map.putIfAbsent(key, result) + if (previous != null) throw new DataExistsException( + String.format("Failed to insert key [%s]: the key already has been inserted previously", key)) + + result + } + + @tailrec + def update(key: String, updatedData: VersionedData) { + val currentData = map.get(key) + + if (currentData == null) throw new MissingDataException( + String.format("Failed to update key [%s], no previous entry exist", key)) + + val expectedVersion = currentData.version + 1 + if (expectedVersion != updatedData.version) throw new VersioningException( + "Failed to update key [" + key + "]: version mismatch, expected [" + expectedVersion + "]" + + " but found [" + updatedData.version + "]") + + if (!map.replace(key, currentData, updatedData)) update(key, updatedData) + } + + @tailrec + def overwrite(key: String, bytes: Array[Byte]): VersionedData = { + val currentData = map.get(key) + + if (currentData == null) throw new MissingDataException( + String.format("Failed to overwrite key [%s], no previous entry exist", key)) + + val newData = currentData.createUpdate(bytes) + if (map.replace(key, currentData, newData)) newData else overwrite(key, bytes) + } + + def insertOrOverwrite(key: String, bytes: Array[Byte]): VersionedData = { + val version = InMemoryStorage.InitialVersion + val result = new VersionedData(bytes, version) + + val previous = map.putIfAbsent(key, result) + + if (previous == null) result + else overwrite(key, bytes) + } +} + +//TODO: To minimize the number of dependencies, should the Storage not be placed in a seperate module? +//class VoldemortRawStorage(storeClient: StoreClient) extends Storage { +// +// def load(Key: String) = { +// try { +// +// } catch { +// case +// } +// } +// +// override def insert(key: String, bytes: Array[Byte]) { +// throw new UnsupportedOperationException() +// } +// +// def update(key: String, bytes: Array[Byte]) { +// throw new UnsupportedOperationException() +// } +//} \ No newline at end of file diff --git a/akka-cluster/src/main/scala/akka/cluster/TransactionLog.scala b/akka-cluster/src/main/scala/akka/cluster/TransactionLog.scala index f5c96250b4..89a9c811d9 100644 --- a/akka-cluster/src/main/scala/akka/cluster/TransactionLog.scala +++ b/akka-cluster/src/main/scala/akka/cluster/TransactionLog.scala @@ -9,16 +9,23 @@ import org.apache.zookeeper.CreateMode import org.I0Itec.zkclient.exception._ +import akka.AkkaException import akka.config._ import Config._ import akka.util._ +import akka.actor._ +import DeploymentConfig.{ ReplicationScheme, ReplicationStrategy, Transient, WriteThrough, WriteBehind } import akka.event.EventHandler -import akka.dispatch.{ DefaultPromise, Promise } -import akka.AkkaException - +import akka.dispatch.{ DefaultPromise, Promise, MessageInvocation } +import akka.remote.MessageSerializer +import akka.serialization.ActorSerialization._ import akka.cluster.zookeeper._ +import akka.serialization.{ Serializer, Compression } +import Compression.LZF +import akka.serialization.ActorSerialization._ import java.util.Enumeration +import java.util.concurrent.atomic.AtomicLong // FIXME allow user to choose dynamically between 'async' and 'sync' tx logging (asyncAddEntry(byte[] data, AddCallback cb, Object ctx)) // FIXME clean up old entries in log after doing a snapshot @@ -41,25 +48,47 @@ 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, + replicationScheme: ReplicationScheme, + format: Serializer) { import TransactionLog._ val logId = ledger.getId val txLogPath = transactionLogNode + "/" + id val snapshotPath = txLogPath + "/snapshot" + val nrOfEntries = new AtomicLong(0) private val isOpen = new Switch(true) + /** + * TODO document method + */ + def recordEntry(messageHandle: MessageInvocation, actorRef: ActorRef) { + if (nrOfEntries.incrementAndGet % snapshotFrequency == 0) { + val snapshot = + // FIXME ReplicationStrategy Transient is always used + if (Cluster.shouldCompressData) LZF.compress(toBinary(actorRef, false, replicationScheme)) + else toBinary(actorRef, false, replicationScheme) + recordSnapshot(snapshot) + } + recordEntry(MessageSerializer.serialize(messageHandle.message.asInstanceOf[AnyRef]).toByteArray) + } + /** * TODO document method */ def recordEntry(entry: Array[Byte]) { if (isOpen.isOn) { + val bytes = if (Cluster.shouldCompressData) LZF.compress(entry) + else entry try { if (isAsync) { ledger.asyncAddEntry( - entry, + bytes, new AsyncCallback.AddCallback { def addComplete( returnCode: Int, @@ -73,7 +102,7 @@ class TransactionLog private (ledger: LedgerHandle, val id: String, val isAsync: }, null) } else { - handleReturnCode(ledger.addEntry(entry)) + handleReturnCode(ledger.addEntry(bytes)) val entryId = ledger.getLastAddPushed EventHandler.debug(this, "Writing entry [%s] to log [%s]".format(entryId, logId)) } @@ -88,10 +117,12 @@ class TransactionLog private (ledger: LedgerHandle, val id: String, val isAsync: */ def recordSnapshot(snapshot: Array[Byte]) { if (isOpen.isOn) { + val bytes = if (Cluster.shouldCompressData) LZF.compress(snapshot) + else snapshot try { if (isAsync) { ledger.asyncAddEntry( - snapshot, + bytes, new AsyncCallback.AddCallback { def addComplete( returnCode: Int, @@ -104,7 +135,7 @@ class TransactionLog private (ledger: LedgerHandle, val id: String, val isAsync: }, null) } else { - handleReturnCode(ledger.addEntry(snapshot)) + handleReturnCode(ledger.addEntry(bytes)) storeSnapshotMetaDataInZooKeeper(ledger.getLastAddPushed) } } catch { @@ -121,7 +152,7 @@ class TransactionLog private (ledger: LedgerHandle, val id: String, val isAsync: /** * TODO document method */ - def entriesFromLatestSnapshot: Tuple2[Array[Byte], Vector[Array[Byte]]] = { + def toByteArraysLatestSnapshot: (Array[Byte], Vector[Array[Byte]]) = { val snapshotId = latestSnapshotId EventHandler.debug(this, "Reading entries from snapshot id [%s] for log [%s]".format(snapshotId, logId)) @@ -133,9 +164,9 @@ class TransactionLog private (ledger: LedgerHandle, val id: String, val isAsync: */ def entriesInRange(from: Long, to: Long): Vector[Array[Byte]] = if (isOpen.isOn) { try { - if (from < 0) throw new IllegalArgumentException("'from' can't be negative [" + from + "]") - if (to < 0) throw new IllegalArgumentException("'to' can't be negative [" + from + "]") - if (to < from) throw new IllegalArgumentException("'to' can't be smaller than 'from' [" + from + "," + to + "]") + if (from < 0) throw new IllegalArgumentException("'from' index can't be negative [" + from + "]") + if (to < 0) throw new IllegalArgumentException("'to' index can't be negative [" + from + "]") + if (to < from) throw new IllegalArgumentException("'to' index can't be smaller than 'from' index [" + from + "," + to + "]") EventHandler.debug(this, "Reading entries [%s -> %s] for log [%s]".format(from, to, logId)) @@ -150,10 +181,7 @@ class TransactionLog private (ledger: LedgerHandle, val id: String, val isAsync: enumeration: Enumeration[LedgerEntry], ctx: AnyRef) { val future = ctx.asInstanceOf[Promise[Vector[Array[Byte]]]] - var entries = Vector[Array[Byte]]() - while (enumeration.hasMoreElements) { - entries = entries :+ enumeration.nextElement.getEntry - } + val entries = toByteArrays(enumeration) if (returnCode == BKException.Code.OK) future.completeWithResult(entries) else future.completeWithException(BKException.create(returnCode)) } @@ -161,12 +189,7 @@ class TransactionLog private (ledger: LedgerHandle, val id: String, val isAsync: future) await(future) } else { - val enumeration = ledger.readEntries(from, to) - var entries = Vector[Array[Byte]]() - while (enumeration.hasMoreElements) { - entries = entries :+ enumeration.nextElement.getEntry - } - entries + toByteArrays(ledger.readEntries(from, to)) } } catch { case e ⇒ handleError(e) @@ -190,8 +213,7 @@ class TransactionLog private (ledger: LedgerHandle, val id: String, val isAsync: } catch { case e: ZkNoNodeException ⇒ handleError(new ReplicationException( - "Transaction log for UUID [" + id + - "] does not have a snapshot recorded in ZooKeeper")) + "Transaction log for UUID [" + id + "] does not have a snapshot recorded in ZooKeeper")) case e ⇒ handleError(e) } } @@ -208,7 +230,7 @@ class TransactionLog private (ledger: LedgerHandle, val id: String, val isAsync: logId, new AsyncCallback.DeleteCallback { def deleteComplete(returnCode: Int, ctx: AnyRef) { - handleReturnCode(returnCode) + (returnCode) } }, null) @@ -248,6 +270,18 @@ class TransactionLog private (ledger: LedgerHandle, val id: String, val isAsync: } } + private def toByteArrays(enumeration: Enumeration[LedgerEntry]): Vector[Array[Byte]] = { + var entries = Vector[Array[Byte]]() + while (enumeration.hasMoreElements) { + val bytes = enumeration.nextElement.getEntry + val entry = + if (Cluster.shouldCompressData) LZF.uncompress(bytes) + else bytes + entries = entries :+ entry + } + entries + } + private def storeSnapshotMetaDataInZooKeeper(snapshotId: Long) { if (isOpen.isOn) { try { @@ -265,8 +299,7 @@ class TransactionLog private (ledger: LedgerHandle, val id: String, val isAsync: "Could not store transaction log snapshot meta-data in ZooKeeper for UUID [" + id + "]")) } - EventHandler.debug(this, - "Writing snapshot [%s] to log [%s]".format(snapshotId, logId)) + EventHandler.debug(this, "Writing snapshot [%s] to log [%s]".format(snapshotId, logId)) } else transactionClosedError } @@ -292,12 +325,13 @@ object TransactionLog { case "CRC32" ⇒ BookKeeper.DigestType.CRC32 case "MAC" ⇒ BookKeeper.DigestType.MAC case unknown ⇒ throw new ConfigurationException( - "akka.cluster.replication.digest-type is invalid [" + unknown + "]") + "akka.cluster.replication.digest-type is invalid [" + unknown + "], must be either 'CRC32' or 'MAC'") } val password = config.getString("akka.cluster.replication.password", "secret").getBytes("UTF-8") val ensembleSize = config.getInt("akka.cluster.replication.ensemble-size", 3) val quorumSize = config.getInt("akka.cluster.replication.quorum-size", 2) - val timeout = 5000 // FIXME make configurable + val snapshotFrequency = config.getInt("akka.cluster.replication.snapshot-frequency", 1000) + val timeout = Duration(config.getInt("akka.cluster.replication.timeout", 30), TIME_UNIT).toMillis private[akka] val transactionLogNode = "/transaction-log-ids" @@ -333,8 +367,13 @@ object TransactionLog { (bk, zk) } - private[akka] def apply(ledger: LedgerHandle, id: String, isAsync: Boolean = false) = - new TransactionLog(ledger, id, isAsync) + private[akka] def apply( + ledger: LedgerHandle, + id: String, + isAsync: Boolean, + replicationScheme: ReplicationScheme, + format: Serializer) = + new TransactionLog(ledger, id, isAsync, replicationScheme, format) /** * Shuts down the transaction log. @@ -355,7 +394,12 @@ object TransactionLog { /** * TODO document method */ - def newLogFor(id: String, isAsync: Boolean = false): TransactionLog = { + def newLogFor( + id: String, + isAsync: Boolean, + replicationScheme: ReplicationScheme, + format: Serializer): TransactionLog = { + val txLogPath = transactionLogNode + "/" + id val ledger = try { @@ -399,13 +443,18 @@ object TransactionLog { } EventHandler.info(this, "Created new transaction log [%s] for UUID [%s]".format(logId, id)) - TransactionLog(ledger, id, isAsync) + TransactionLog(ledger, id, isAsync, replicationScheme, format) } /** * TODO document method */ - def logFor(id: String, isAsync: Boolean = false): TransactionLog = { + def logFor( + id: String, + isAsync: Boolean, + replicationScheme: ReplicationScheme, + format: Serializer): TransactionLog = { + val txLogPath = transactionLogNode + "/" + id val logId = try { @@ -444,7 +493,7 @@ object TransactionLog { case e ⇒ handleError(e) } - TransactionLog(ledger, id, isAsync) + TransactionLog(ledger, id, isAsync, replicationScheme, format) } private[akka] def await[T](future: Promise[T]): T = { @@ -489,15 +538,10 @@ object LocalBookKeeperEnsemble { def shutdown() { isRunning switchOff { EventHandler.info(this, "Shutting down LocalBookKeeperEnsemble...") - println("***************************** 1") localBookKeeper.bs.foreach(_.shutdown()) // stop bookies - println("***************************** 2") localBookKeeper.zkc.close() // stop zk client - println("***************************** 3") localBookKeeper.zks.shutdown() // stop zk server - println("***************************** 4") localBookKeeper.serverFactory.shutdown() // stop zk NIOServer - println("***************************** 5") EventHandler.info(this, "LocalBookKeeperEnsemble shut down successfully") } } diff --git a/akka-cluster/src/test/scala/akka/cluster/ClusterDeployerSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ClusterDeployerSpec.scala index 3ab9acdb8a..435f20d094 100644 --- a/akka-cluster/src/test/scala/akka/cluster/ClusterDeployerSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/ClusterDeployerSpec.scala @@ -47,7 +47,7 @@ class ClusterDeployerSpec extends WordSpec with MustMatchers with BeforeAndAfter val deployments2 = ClusterDeployer.fetchDeploymentsFromCluster deployments2.size must equal(1) - deployments2.first must equal(deployments1.first) + deployments2.head must equal(deployments1.head) } } diff --git a/akka-cluster/src/test/scala/akka/cluster/ClusterSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ClusterSpec.scala index 0e450308d4..aa6016aa15 100644 --- a/akka-cluster/src/test/scala/akka/cluster/ClusterSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/ClusterSpec.scala @@ -1,3 +1,4 @@ +/* package akka.cluster import org.scalatest.WordSpec @@ -33,7 +34,6 @@ object BinaryFormatMyJavaSerializableActor { val serializer = Serializers.Java } } -/* class ClusterSpec extends WordSpec with MustMatchers with BeforeAndAfterAll with BeforeAndAfterEach { import Cluster._ diff --git a/akka-cluster/src/test/scala/akka/cluster/ClusteredPingPongSample.scala b/akka-cluster/src/test/scala/akka/cluster/ClusteredPingPongSample.scala index 4e1b358d89..60d2a69a88 100644 --- a/akka-cluster/src/test/scala/akka/cluster/ClusteredPingPongSample.scala +++ b/akka-cluster/src/test/scala/akka/cluster/ClusteredPingPongSample.scala @@ -8,7 +8,6 @@ import akka.cluster._ import akka.actor._ import akka.actor.Actor._ -import akka.serialization.{ Serializers, SerializerBasedActorFormat } import java.util.concurrent.CountDownLatch @@ -42,7 +41,7 @@ object PingPong { count += 1 self reply Ball } else { - self.sender.foreach(_ !! Stop) + self.sender.foreach(s ⇒ (s ? Stop).await) gameOverLatch.countDown self.stop } @@ -60,20 +59,6 @@ object PingPong { self.stop } } - - // ------------------------ - // Serialization - // ------------------------ - - object BinaryFormats { - implicit object PingActorFormat extends SerializerBasedActorFormat[PingActor] with Serializable { - val serializer = Serializers.Java - } - - implicit object PongActorFormat extends SerializerBasedActorFormat[PongActor] with Serializable { - val serializer = Serializers.Java - } - } } /* diff --git a/akka-cluster/src/test/scala/akka/cluster/InMemoryStorageSpec.scala b/akka-cluster/src/test/scala/akka/cluster/InMemoryStorageSpec.scala new file mode 100755 index 0000000000..7f3c6a26cd --- /dev/null +++ b/akka-cluster/src/test/scala/akka/cluster/InMemoryStorageSpec.scala @@ -0,0 +1,251 @@ +package akka.cluster + +import org.scalatest.matchers.MustMatchers +import org.scalatest.WordSpec +import akka.cluster.StorageTestUtils._ + +class InMemoryStorageSpec extends WordSpec with MustMatchers { + + "unversioned load" must { + "throw MissingDataException if non existing key" in { + val store = new InMemoryStorage() + + try { + store.load("foo") + fail() + } catch { + case e: MissingDataException ⇒ + } + } + + "return VersionedData if key existing" in { + val storage = new InMemoryStorage() + val key = "somekey" + val value = "somevalue".getBytes + storage.insert(key, value) + + val result = storage.load(key) + //todo: strange that the implicit store is not found + assertContent(key, value, result.version)(storage) + } + } + + "exist" must { + "return true if value exists" in { + val store = new InMemoryStorage() + val key = "somekey" + store.insert(key, "somevalue".getBytes) + store.exists(key) must be(true) + } + + "return false if value not exists" in { + val store = new InMemoryStorage() + store.exists("somekey") must be(false) + } + } + + "versioned load" must { + "throw MissingDataException if non existing key" in { + val store = new InMemoryStorage() + + try { + store.load("foo", 1) + fail() + } catch { + case e: MissingDataException ⇒ + } + } + + "return VersionedData if key existing and exact version match" in { + val storage = new InMemoryStorage() + val key = "somekey" + val value = "somevalue".getBytes + val stored = storage.insert(key, value) + + val result = storage.load(key, stored.version) + assert(result.version == stored.version) + assert(result.data == stored.data) + } + + "throw VersioningException is version too new" in { + val storage = new InMemoryStorage() + val key = "somekey" + val value = "somevalue".getBytes + val stored = storage.insert(key, value) + + try { + storage.load(key, stored.version + 1) + fail() + } catch { + case e: VersioningException ⇒ + } + } + + "throw VersioningException is version too old" in { + val storage = new InMemoryStorage() + val key = "somekey" + val value = "somevalue".getBytes + val stored = storage.insert(key, value) + + try { + storage.load(key, stored.version - 1) + fail() + } catch { + case e: VersioningException ⇒ + } + } + } + + "insert" must { + + "place a new value when non previously existed" in { + val storage = new InMemoryStorage() + val key = "somekey" + val oldValue = "oldvalue".getBytes + storage.insert(key, oldValue) + + val result = storage.load(key) + assertContent(key, oldValue)(storage) + assert(InMemoryStorage.InitialVersion == result.version) + } + + "throw MissingDataException when there already exists an entry with the same key" in { + val storage = new InMemoryStorage() + val key = "somekey" + val oldValue = "oldvalue".getBytes + + val oldVersionedData = storage.insert(key, oldValue) + + val newValue = "newValue".getBytes + + try { + storage.insert(key, newValue) + fail() + } catch { + case e: DataExistsException ⇒ + } + + //make sure that the old value was not changed + assert(oldVersionedData == storage.load(key)) + } + } + + "update" must { + + "throw MissingDataException when no node exists" in { + val storage = new InMemoryStorage() + + val key = "somekey" + + try { + storage.update(key, new VersionedData("somevalue".getBytes, 1)) + fail() + } catch { + case e: MissingDataException ⇒ + } + } + + "replace if previous value exists and no other updates have been done" in { + val storage = new InMemoryStorage() + + //do the initial insert + val key = "foo" + val oldValue = "insert".getBytes + val insert = storage.insert(key, oldValue) + + //do the update the will be the cause of the conflict. + val updateValue = "update".getBytes + val update = insert.createUpdate(updateValue) + storage.update(key, update) + + assertContent(key, update.data, update.version)(storage) + } + + "throw VersioningException when already overwritten" in { + val storage = new InMemoryStorage() + + //do the initial insert + val key = "foo" + val oldValue = "insert".getBytes + val insert = storage.insert(key, oldValue) + + //do the update the will be the cause of the conflict. + val otherUpdateValue = "otherupdate".getBytes + val otherUpdate = insert.createUpdate(otherUpdateValue) + storage.update(key, otherUpdate) + + val update = insert.createUpdate("update".getBytes) + + try { + storage.update(key, update) + fail() + } catch { + case e: VersioningException ⇒ + } + + assertContent(key, otherUpdate.data, otherUpdate.version)(storage) + } + } + + "overwrite" must { + + "throw MissingDataException when no node exists" in { + val storage = new InMemoryStorage() + val key = "somekey" + + try { + storage.overwrite(key, "somevalue".getBytes) + fail() + } catch { + case e: MissingDataException ⇒ + } + + storage.exists(key) must be(false) + } + + "succeed if previous value exist" in { + val storage = new InMemoryStorage() + val key = "somekey" + val oldValue = "oldvalue".getBytes + val newValue: Array[Byte] = "somevalue".getBytes + + val initialInsert: VersionedData = storage.insert(key, oldValue) + + val result: VersionedData = storage.overwrite(key, newValue) + + assert(result.version == initialInsert.version + 1) + assert(result.data == newValue) + storage.load(key) must be eq (result) + } + } + + "insertOrOverwrite" must { + "insert if nothing was inserted before" in { + val storage = new InMemoryStorage() + val key = "somekey" + val value = "somevalue".getBytes + + val result = storage.insertOrOverwrite(key, value) + + assert(result.version == InMemoryStorage.InitialVersion) + assert(result.data == value) + storage.load(key) must be eq (result) + } + + "overwrite of something existed before" in { + val storage = new InMemoryStorage() + val key = "somekey" + val oldValue = "oldvalue".getBytes + val newValue = "somevalue".getBytes + + val initialInsert = storage.insert(key, oldValue) + + val result = storage.insertOrOverwrite(key, newValue) + + assert(result.version == initialInsert.version + 1) + assert(result.data == newValue) + storage.load(key) must be eq (result) + } + } + +} \ 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 4856efd188..81fb364d76 100644 --- a/akka-cluster/src/test/scala/akka/cluster/PingPongMultiJvmExample.scala +++ b/akka-cluster/src/test/scala/akka/cluster/PingPongMultiJvmExample.scala @@ -7,7 +7,6 @@ package example.cluster import akka.cluster._ import akka.actor._ -import akka.serialization.{ Serializers, SerializerBasedActorFormat } import akka.util.duration._ object PingPong { @@ -62,20 +61,6 @@ object PingPong { self reply Pong } } - - // ----------------------------------------------- - // Serialization - // ----------------------------------------------- - - object BinaryFormats { - implicit object PingActorFormat extends SerializerBasedActorFormat[PingActor] with Serializable { - val serializer = Serializers.Java - } - - implicit object PongActorFormat extends SerializerBasedActorFormat[PongActor] with Serializable { - val serializer = Serializers.Java - } - } } /* diff --git a/akka-cluster/src/test/scala/akka/cluster/ReplicationSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ReplicationSpec.scala index 42423a3afc..e5f5261d0a 100644 --- a/akka-cluster/src/test/scala/akka/cluster/ReplicationSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/ReplicationSpec.scala @@ -32,31 +32,31 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll "A Transaction Log" should { "be able to record entries - synchronous" in { val uuid = (new UUID).toString - val txlog = TransactionLog.newLogFor(uuid) + val txlog = TransactionLog.newLogFor(uuid, false, null, JavaSerializer) val entry = "hello".getBytes("UTF-8") txlog.recordEntry(entry) } "be able to record and delete entries - synchronous" in { val uuid = (new UUID).toString - val txlog1 = TransactionLog.newLogFor(uuid) + val txlog1 = TransactionLog.newLogFor(uuid, false, null, JavaSerializer) val entry = "hello".getBytes("UTF-8") txlog1.recordEntry(entry) txlog1.recordEntry(entry) txlog1.delete txlog1.close - intercept[BKNoSuchLedgerExistsException](TransactionLog.logFor(uuid)) + intercept[BKNoSuchLedgerExistsException](TransactionLog.logFor(uuid, false, null, JavaSerializer)) } "be able to record entries and read entries with 'entriesInRange' - synchronous" in { val uuid = (new UUID).toString - val txlog1 = TransactionLog.newLogFor(uuid) + val txlog1 = TransactionLog.newLogFor(uuid, false, null, JavaSerializer) val entry = "hello".getBytes("UTF-8") txlog1.recordEntry(entry) txlog1.recordEntry(entry) txlog1.close - val txlog2 = TransactionLog.logFor(uuid) + val txlog2 = TransactionLog.logFor(uuid, false, null, JavaSerializer) val entries = txlog2.entriesInRange(0, 1).map(bytes ⇒ new String(bytes, "UTF-8")) entries.size must equal(2) entries(0) must equal("hello") @@ -66,7 +66,7 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll "be able to record entries and read entries with 'entries' - synchronous" in { val uuid = (new UUID).toString - val txlog1 = TransactionLog.newLogFor(uuid) + val txlog1 = TransactionLog.newLogFor(uuid, false, null, JavaSerializer) val entry = "hello".getBytes("UTF-8") txlog1.recordEntry(entry) txlog1.recordEntry(entry) @@ -74,7 +74,7 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll txlog1.recordEntry(entry) txlog1.close - val txlog2 = TransactionLog.logFor(uuid) + val txlog2 = TransactionLog.logFor(uuid, false, null, JavaSerializer) val entries = txlog2.entries.map(bytes ⇒ new String(bytes, "UTF-8")) entries.size must equal(4) entries(0) must equal("hello") @@ -86,7 +86,7 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll "be able to record a snapshot - synchronous" in { val uuid = (new UUID).toString - val txlog1 = TransactionLog.newLogFor(uuid) + val txlog1 = TransactionLog.newLogFor(uuid, false, null, JavaSerializer) val snapshot = "snapshot".getBytes("UTF-8") txlog1.recordSnapshot(snapshot) txlog1.close @@ -94,7 +94,7 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll "be able to record and read a snapshot and following entries - synchronous" in { val uuid = (new UUID).toString - val txlog1 = TransactionLog.newLogFor(uuid) + val txlog1 = TransactionLog.newLogFor(uuid, false, null, JavaSerializer) val snapshot = "snapshot".getBytes("UTF-8") txlog1.recordSnapshot(snapshot) @@ -105,8 +105,8 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll txlog1.recordEntry(entry) txlog1.close - val txlog2 = TransactionLog.logFor(uuid) - val (snapshotAsBytes, entriesAsBytes) = txlog2.entriesFromLatestSnapshot + val txlog2 = TransactionLog.logFor(uuid, false, null, JavaSerializer) + val (snapshotAsBytes, entriesAsBytes) = txlog2.toByteArraysLatestSnapshot new String(snapshotAsBytes, "UTF-8") must equal("snapshot") val entries = entriesAsBytes.map(bytes ⇒ new String(bytes, "UTF-8")) @@ -120,7 +120,7 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll "be able to record entries then a snapshot then more entries - and then read from the snapshot and the following entries - synchronous" in { val uuid = (new UUID).toString - val txlog1 = TransactionLog.newLogFor(uuid) + val txlog1 = TransactionLog.newLogFor(uuid, false, null, JavaSerializer) val entry = "hello".getBytes("UTF-8") txlog1.recordEntry(entry) @@ -134,8 +134,8 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll txlog1.recordEntry(entry) txlog1.close - val txlog2 = TransactionLog.logFor(uuid) - val (snapshotAsBytes, entriesAsBytes) = txlog2.entriesFromLatestSnapshot + val txlog2 = TransactionLog.logFor(uuid, false, null, JavaSerializer) + val (snapshotAsBytes, entriesAsBytes) = txlog2.toByteArraysLatestSnapshot new String(snapshotAsBytes, "UTF-8") must equal("snapshot") val entries = entriesAsBytes.map(bytes ⇒ new String(bytes, "UTF-8")) @@ -149,7 +149,7 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll "A Transaction Log" should { "be able to record entries - asynchronous" in { val uuid = (new UUID).toString - val txlog = TransactionLog.newLogFor(uuid, true) + val txlog = TransactionLog.newLogFor(uuid, true, null, JavaSerializer) val entry = "hello".getBytes("UTF-8") txlog.recordEntry(entry) Thread.sleep(100) @@ -158,24 +158,24 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll "be able to record and delete entries - asynchronous" in { val uuid = (new UUID).toString - val txlog1 = TransactionLog.newLogFor(uuid, true) + val txlog1 = TransactionLog.newLogFor(uuid, true, null, JavaSerializer) val entry = "hello".getBytes("UTF-8") txlog1.recordEntry(entry) txlog1.recordEntry(entry) txlog1.delete Thread.sleep(100) - intercept[BKNoSuchLedgerExistsException](TransactionLog.logFor(uuid, true)) + intercept[BKNoSuchLedgerExistsException](TransactionLog.logFor(uuid, true, null, JavaSerializer)) } "be able to record entries and read entries with 'entriesInRange' - asynchronous" in { val uuid = (new UUID).toString - val txlog1 = TransactionLog.newLogFor(uuid, true) + val txlog1 = TransactionLog.newLogFor(uuid, true, null, JavaSerializer) val entry = "hello".getBytes("UTF-8") txlog1.recordEntry(entry) txlog1.recordEntry(entry) Thread.sleep(100) txlog1.close - val txlog2 = TransactionLog.logFor(uuid, true) + val txlog2 = TransactionLog.logFor(uuid, true, null, JavaSerializer) val entries = txlog2.entriesInRange(0, 1).map(bytes ⇒ new String(bytes, "UTF-8")) entries.size must equal(2) entries(0) must equal("hello") @@ -186,7 +186,7 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll "be able to record entries and read entries with 'entries' - asynchronous" in { val uuid = (new UUID).toString - val txlog1 = TransactionLog.newLogFor(uuid, true) + val txlog1 = TransactionLog.newLogFor(uuid, true, null, JavaSerializer) val entry = "hello".getBytes("UTF-8") txlog1.recordEntry(entry) txlog1.recordEntry(entry) @@ -195,7 +195,7 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll Thread.sleep(100) txlog1.close - val txlog2 = TransactionLog.logFor(uuid, true) + val txlog2 = TransactionLog.logFor(uuid, true, null, JavaSerializer) val entries = txlog2.entries.map(bytes ⇒ new String(bytes, "UTF-8")) entries.size must equal(4) entries(0) must equal("hello") @@ -208,7 +208,7 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll "be able to record a snapshot - asynchronous" in { val uuid = (new UUID).toString - val txlog1 = TransactionLog.newLogFor(uuid, true) + val txlog1 = TransactionLog.newLogFor(uuid, true, null, JavaSerializer) val snapshot = "snapshot".getBytes("UTF-8") txlog1.recordSnapshot(snapshot) Thread.sleep(100) @@ -217,7 +217,7 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll "be able to record and read a snapshot and following entries - asynchronous" in { val uuid = (new UUID).toString - val txlog1 = TransactionLog.newLogFor(uuid, true) + val txlog1 = TransactionLog.newLogFor(uuid, true, null, JavaSerializer) val snapshot = "snapshot".getBytes("UTF-8") txlog1.recordSnapshot(snapshot) @@ -229,8 +229,8 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll Thread.sleep(100) txlog1.close - val txlog2 = TransactionLog.logFor(uuid, true) - val (snapshotAsBytes, entriesAsBytes) = txlog2.entriesFromLatestSnapshot + val txlog2 = TransactionLog.logFor(uuid, true, null, JavaSerializer) + val (snapshotAsBytes, entriesAsBytes) = txlog2.toByteArraysLatestSnapshot new String(snapshotAsBytes, "UTF-8") must equal("snapshot") val entries = entriesAsBytes.map(bytes ⇒ new String(bytes, "UTF-8")) @@ -245,7 +245,7 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll "be able to record entries then a snapshot then more entries - and then read from the snapshot and the following entries - asynchronous" in { val uuid = (new UUID).toString - val txlog1 = TransactionLog.newLogFor(uuid, true) + val txlog1 = TransactionLog.newLogFor(uuid, true, null, JavaSerializer) val entry = "hello".getBytes("UTF-8") txlog1.recordEntry(entry) @@ -258,8 +258,8 @@ class ReplicationSpec extends WordSpec with MustMatchers with BeforeAndAfterAll Thread.sleep(100) txlog1.close - val txlog2 = TransactionLog.logFor(uuid, true) - val (snapshotAsBytes, entriesAsBytes) = txlog2.entriesFromLatestSnapshot + val txlog2 = TransactionLog.logFor(uuid, true, null, JavaSerializer) + val (snapshotAsBytes, entriesAsBytes) = txlog2.toByteArraysLatestSnapshot new String(snapshotAsBytes, "UTF-8") must equal("snapshot") val entries = entriesAsBytes.map(bytes ⇒ new String(bytes, "UTF-8")) entries.size must equal(2) diff --git a/akka-cluster/src/test/scala/akka/cluster/StorageTestUtils.scala b/akka-cluster/src/test/scala/akka/cluster/StorageTestUtils.scala new file mode 100644 index 0000000000..99ceaf0070 --- /dev/null +++ b/akka-cluster/src/test/scala/akka/cluster/StorageTestUtils.scala @@ -0,0 +1,15 @@ +package akka.cluster + +object StorageTestUtils { + + def assertContent(key: String, expectedData: Array[Byte], expectedVersion: Long)(implicit storage: InMemoryStorage) { + val found = storage.load(key) + assert(found.version == expectedVersion) + assert(expectedData == found.data) //todo: structural equals + } + + def assertContent(key: String, expectedData: Array[Byte])(implicit storage: InMemoryStorage) { + val found = storage.load(key) + assert(expectedData == found.data) //todo: structural equals + } +} \ No newline at end of file diff --git a/akka-cluster/src/test/scala/akka/cluster/ZooKeeperStorageSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ZooKeeperStorageSpec.scala new file mode 100644 index 0000000000..84f91a0453 --- /dev/null +++ b/akka-cluster/src/test/scala/akka/cluster/ZooKeeperStorageSpec.scala @@ -0,0 +1,58 @@ +package akka.cluster + +import org.scalatest.matchers.MustMatchers +import akka.actor.Actor +import org.scalatest.{ BeforeAndAfterEach, BeforeAndAfterAll, WordSpec } +import org.I0Itec.zkclient.ZkServer +import zookeeper.AkkaZkClient + +class ZooKeeperStorageSpec extends WordSpec with MustMatchers with BeforeAndAfterAll with BeforeAndAfterEach { + val dataPath = "_akka_cluster/data" + val logPath = "_akka_cluster/log" + var zkServer: ZkServer = _ + var zkClient: AkkaZkClient = _ + /* + override def beforeAll() { + try { + zkServer = Cluster.startLocalCluster(dataPath, logPath) + Thread.sleep(5000) + Actor.cluster.start() + zkClient = Cluster.newZkClient() + } catch { + case e ⇒ e.printStackTrace() + } + } + + override def afterAll() { + zkClient.close() + Actor.cluster.shutdown() + ClusterDeployer.shutdown() + Cluster.shutdownLocalCluster() + Actor.registry.local.shutdownAll() + } +*/ + "unversioned load" must { + "throw MissingDataException if non existing key" in { + // val store = new ZooKeeperStorage(zkClient) + + //try { + // store.load("foo") + // fail() + //} catch { + // case e: MissingDataException ⇒ + //} + } + + /* + "return VersionedData if key existing" in { + val storage = new InMemoryStorage() + val key = "somekey" + val value = "somevalue".getBytes + storage.insert(key, value) + + val result = storage.load(key) + //todo: strange that the implicit store is not found + assertContent(key, value, result.version)(storage) + } */ + } +} \ No newline at end of file diff --git a/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_1_replica/RoundRobin1ReplicaMultiJvmNode1.conf b/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_1_replica/RoundRobin1ReplicaMultiJvmNode1.conf index 3c9999f42c..7b2ecc1583 100644 --- a/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_1_replica/RoundRobin1ReplicaMultiJvmNode1.conf +++ b/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_1_replica/RoundRobin1ReplicaMultiJvmNode1.conf @@ -1,5 +1,4 @@ akka.event-handler-level = "DEBUG" akka.actor.deployment.service-hello.router = "round-robin" akka.actor.deployment.service-hello.clustered.home = "node:node1" -akka.actor.deployment.service-hello.clustered.replicas = 1 -akka.actor.deployment.service-hello.clustered.stateless = on +akka.actor.deployment.service-hello.clustered.replicas = 1 \ No newline at end of file diff --git a/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_1_replica/RoundRobin1ReplicaMultiJvmNode2.conf b/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_1_replica/RoundRobin1ReplicaMultiJvmNode2.conf index 59aa6fddac..7b2ecc1583 100644 --- a/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_1_replica/RoundRobin1ReplicaMultiJvmNode2.conf +++ b/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_1_replica/RoundRobin1ReplicaMultiJvmNode2.conf @@ -1,5 +1,4 @@ akka.event-handler-level = "DEBUG" akka.actor.deployment.service-hello.router = "round-robin" akka.actor.deployment.service-hello.clustered.home = "node:node1" -akka.actor.deployment.service-hello.clustered.replicas = 1 -akka.actor.deployment.service-hello.clustered.stateless = on \ No newline at end of file +akka.actor.deployment.service-hello.clustered.replicas = 1 \ No newline at end of file diff --git a/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_1_replica/RoundRobin1ReplicaMultiJvmSpec.scala b/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_1_replica/RoundRobin1ReplicaMultiJvmSpec.scala index 1f6d60efc3..668acb3376 100644 --- a/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_1_replica/RoundRobin1ReplicaMultiJvmSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_1_replica/RoundRobin1ReplicaMultiJvmSpec.scala @@ -8,9 +8,12 @@ import org.scalatest.WordSpec import org.scalatest.matchers.MustMatchers import org.scalatest.BeforeAndAfterAll +import org.apache.bookkeeper.client.{ BookKeeper, BKException } +import BKException._ + import akka.cluster._ import akka.actor._ -import Actor._ +import akka.actor.Actor._ import akka.config.Config object RoundRobin1ReplicaMultiJvmSpec { @@ -27,6 +30,9 @@ object RoundRobin1ReplicaMultiJvmSpec { class RoundRobin1ReplicaMultiJvmNode1 extends WordSpec with MustMatchers with BeforeAndAfterAll { import RoundRobin1ReplicaMultiJvmSpec._ + private var bookKeeper: BookKeeper = _ + // private var localBookKeeper: LocalBookKeeper = _ + "A cluster" must { "create clustered actor, get a 'local' actor on 'home' node and a 'ref' to actor on remote node" in { @@ -49,10 +55,13 @@ class RoundRobin1ReplicaMultiJvmNode1 extends WordSpec with MustMatchers with Be override def beforeAll() = { Cluster.startLocalCluster() + // LocalBookKeeperEnsemble.start() } override def afterAll() = { Cluster.shutdownLocalCluster() + // TransactionLog.shutdown() + // LocalBookKeeperEnsemble.shutdown() } } @@ -81,7 +90,7 @@ class RoundRobin1ReplicaMultiJvmNode2 extends WordSpec with MustMatchers { Cluster.barrier("send-message-from-node2-to-node1", NrOfNodes) { hello must not equal (null) - val reply = (hello !! "Hello").as[String].getOrElse(fail("Should have recieved reply from node1")) + val reply = (hello ? "Hello").as[String].getOrElse(fail("Should have recieved reply from node1")) reply must equal("World from node [node1]") } diff --git a/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_2_replicas/RoundRobin2ReplicasMultiJvmSpec.scala b/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_2_replicas/RoundRobin2ReplicasMultiJvmSpec.scala index 9f3083868b..a65abd2b1c 100644 --- a/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_2_replicas/RoundRobin2ReplicasMultiJvmSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/routing/roundrobin_2_replicas/RoundRobin2ReplicasMultiJvmSpec.scala @@ -8,9 +8,12 @@ import org.scalatest.WordSpec import org.scalatest.matchers.MustMatchers import org.scalatest.BeforeAndAfterAll +import org.apache.bookkeeper.client.{ BookKeeper, BKException } +import BKException._ + import akka.cluster._ import akka.actor._ -import Actor._ +import akka.actor.Actor._ import akka.config.Config object RoundRobin2ReplicasMultiJvmSpec { @@ -28,6 +31,9 @@ object RoundRobin2ReplicasMultiJvmSpec { class RoundRobin2ReplicasMultiJvmNode1 extends WordSpec with MustMatchers with BeforeAndAfterAll { import RoundRobin2ReplicasMultiJvmSpec._ + private var bookKeeper: BookKeeper = _ + private var localBookKeeper: LocalBookKeeper = _ + "A cluster" must { "create clustered actor, get a 'local' actor on 'home' node and a 'ref' to actor on remote node" in { @@ -52,10 +58,13 @@ class RoundRobin2ReplicasMultiJvmNode1 extends WordSpec with MustMatchers with B override def beforeAll() = { Cluster.startLocalCluster() + LocalBookKeeperEnsemble.start() } override def afterAll() = { Cluster.shutdownLocalCluster() + TransactionLog.shutdown() + LocalBookKeeperEnsemble.shutdown() } } @@ -93,14 +102,14 @@ class RoundRobin2ReplicasMultiJvmNode2 extends WordSpec with MustMatchers { else replies.put(reply, replies(reply) + 1) } - count((hello !! "Hello").as[String].getOrElse(fail("Should have recieved reply from node1"))) - count((hello !! "Hello").as[String].getOrElse(fail("Should have recieved reply from node3"))) - count((hello !! "Hello").as[String].getOrElse(fail("Should have recieved reply from node1"))) - count((hello !! "Hello").as[String].getOrElse(fail("Should have recieved reply from node3"))) - count((hello !! "Hello").as[String].getOrElse(fail("Should have recieved reply from node1"))) - count((hello !! "Hello").as[String].getOrElse(fail("Should have recieved reply from node3"))) - count((hello !! "Hello").as[String].getOrElse(fail("Should have recieved reply from node1"))) - count((hello !! "Hello").as[String].getOrElse(fail("Should have recieved reply from node3"))) + count((hello ? "Hello").as[String].getOrElse(fail("Should have recieved reply from node1"))) + count((hello ? "Hello").as[String].getOrElse(fail("Should have recieved reply from node3"))) + count((hello ? "Hello").as[String].getOrElse(fail("Should have recieved reply from node1"))) + count((hello ? "Hello").as[String].getOrElse(fail("Should have recieved reply from node3"))) + count((hello ? "Hello").as[String].getOrElse(fail("Should have recieved reply from node1"))) + count((hello ? "Hello").as[String].getOrElse(fail("Should have recieved reply from node3"))) + count((hello ? "Hello").as[String].getOrElse(fail("Should have recieved reply from node1"))) + count((hello ? "Hello").as[String].getOrElse(fail("Should have recieved reply from node3"))) replies("World from node [node1]") must equal(4) replies("World from node [node3]") must equal(4) diff --git a/akka-docs/additional/add-on-modules.rst b/akka-docs/additional/add-on-modules.rst deleted file mode 100644 index bab2f1b174..0000000000 --- a/akka-docs/additional/add-on-modules.rst +++ /dev/null @@ -1,16 +0,0 @@ -.. _add-on-modules: - -Add-on Modules -============== - -Akka Modules consist of add-on modules outside the core of Akka: - -- ``akka-kernel-1.1.jar`` -- Akka microkernel for running a bare-bones mini application server (embeds Jetty etc.) -- ``akka-amqp-1.1.jar`` -- AMQP integration -- ``akka-camel-1.1.jar`` -- Apache Camel Actors integration (it's the best way to have your Akka application communicate with the rest of the world) -- ``akka-camel-typed-1.1.jar`` -- Apache Camel Typed Actors integration -- ``akka-scalaz-1.1.jar`` -- Support for the Scalaz library -- ``akka-spring-1.1.jar`` -- Spring framework integration -- ``akka-osgi-dependencies-bundle-1.1.jar`` -- OSGi support - -Documentation for Akka Modules is located `here `_. diff --git a/akka-docs/additional/index.rst b/akka-docs/additional/index.rst index 7398db601b..ca92363ee3 100644 --- a/akka-docs/additional/index.rst +++ b/akka-docs/additional/index.rst @@ -4,7 +4,6 @@ Additional Information .. toctree:: :maxdepth: 2 - add-on-modules articles benchmarks recipies diff --git a/akka-docs/cluster/durable-mailbox.rst b/akka-docs/cluster/durable-mailbox.rst index 5ebc34df5a..b24e1fea30 100644 --- a/akka-docs/cluster/durable-mailbox.rst +++ b/akka-docs/cluster/durable-mailbox.rst @@ -18,8 +18,8 @@ in its mailbox. .. sidebar:: **IMPORTANT** None of these mailboxes work with blocking message send, e.g. the message - send operations that are relying on futures; ``!!``, ``!!!``, - ``sendRequestReply`` and ``sendRequestReplyFuture``. If the node has crashed + send operations that are relying on futures; ``!!``, ``?``, + ``sendRequestReply`` and ``ask``. If the node has crashed and then restarted, the thread that was blocked waiting for the reply is gone and there is no way we can deliver the message. @@ -52,7 +52,7 @@ The durable dispatchers and their configuration options reside in the You configure durable mailboxes through the "Akka"-only durable dispatchers, the actor is oblivious to which type of mailbox it is using. Here is an example:: - val dispatcher = DurableEventBasedDispatcher( + val dispatcher = DurableDispatcher( "my:service", FileDurableMailboxStorage) // Then set the actors dispatcher to this dispatcher @@ -63,7 +63,7 @@ or for a thread-based durable dispatcher:: self, FileDurableMailboxStorage) -There are 2 different durable dispatchers, ``DurableEventBasedDispatcher`` and +There are 2 different durable dispatchers, ``DurableDispatcher`` and ``DurablePinnedDispatcher``, which are durable versions of ``Dispatcher`` and ``PinnedDispatcher``. @@ -114,7 +114,7 @@ mailboxes. Read more in the Redis documentation on how to do that. Here is an example of how you can configure your dispatcher to use this mailbox:: - val dispatcher = DurableEventBasedDispatcher( + val dispatcher = DurableDispatcher( "my:service", RedisDurableMailboxStorage) @@ -158,7 +158,7 @@ there will not be that much more work to set up this durable mailbox. Here is an example of how you can configure your dispatcher to use this mailbox:: - val dispatcher = DurableEventBasedDispatcher( + val dispatcher = DurableDispatcher( "my:service", ZooKeeperDurableMailboxStorage) @@ -196,7 +196,7 @@ Beanstalk is a simple, fast work queue. This means that you have to start up a Beanstalk server that can host these durable mailboxes. Read more in the Beanstalk documentation on how to do that. :: - val dispatcher = DurableEventBasedDispatcher( + val dispatcher = DurableDispatcher( "my:service", BeanstalkDurableMailboxStorage) diff --git a/akka-docs/dev/multi-jvm-testing.rst b/akka-docs/dev/multi-jvm-testing.rst index 84a3e5de32..fe5d48540a 100644 --- a/akka-docs/dev/multi-jvm-testing.rst +++ b/akka-docs/dev/multi-jvm-testing.rst @@ -62,7 +62,7 @@ like the following:: When you call ``multi-jvm-run Test`` at the sbt prompt, three JVMs will be spawned, one for each node. It will look like this: -.. code-block:: shell +.. code-block:: none > multi-jvm-run Test ... @@ -252,7 +252,7 @@ something in coordination:: An example output from this would be: -.. code-block:: shell +.. code-block:: none > multi-jvm-run Test ... diff --git a/akka-docs/disabled/getting-started-first.rst b/akka-docs/disabled/getting-started-first.rst index 3fa245febc..b0817fa22f 100644 --- a/akka-docs/disabled/getting-started-first.rst +++ b/akka-docs/disabled/getting-started-first.rst @@ -1,175 +1,6 @@ Getting Started Tutorial: First Chapter ======================================= -Introduction ------------- - -Welcome to the first tutorial on how to get started with Akka and Scala. We assume that you already know what Akka and Scala are and will now focus on the steps necessary to start your first project. - -There are two variations of this first tutorial: - -- creating a standalone project and run it from the command line -- creating a SBT (Simple Build Tool) project and running it from within SBT - -Since they are so similar we will present them both. - -The sample application that we will create is using actors to calculate the value of Pi. Calculating Pi is a CPU intensive operation and we will utilize Akka Actors to write a concurrent solution that scales out to multi-core processors. This sample will be extended in future tutorials to use Akka Remote Actors to scale out on multiple machines in a cluster. - -We will be using an algorithm that is called "embarrassingly parallel" which just means that each job is completely isolated and not coupled with any other job. Since this algorithm is so parallelizable it suits the actor model very well. - -Here is the formula for the algorithm we will use: - -.. image:: ../images/pi-formula.png - -In this particular algorithm the master splits the series into chunks which are sent out to each worker actor to be processed. When each worker has processed its chunk it sends a result back to the master which aggregates the total result. - -Tutorial source code --------------------- - -If you want don't want to type in the code and/or set up an SBT project then you can check out the full tutorial from the Akka GitHub repository. It is in the ``akka-tutorials/akka-tutorial-first`` module. You can also browse it online `here`__, with the actual source code `here`__. - -__ https://github.com/jboner/akka/tree/master/akka-tutorials/akka-tutorial-first -__ https://github.com/jboner/akka/blob/master/akka-tutorials/akka-tutorial-first/src/main/scala/Pi.scala - -Prerequisites -------------- - -This tutorial assumes that you have Java 1.6 or later installed on you machine and ``java`` on your ``PATH``. You also need to know how to run commands in a shell (ZSH, Bash, DOS etc.) and a decent text editor or IDE to type in the Scala code. - -Downloading and installing Akka -------------------------------- - -To build and run the tutorial sample from the command line, you have to download Akka. If you prefer to use SBT to build and run the sample then you can skip this section and jump to the next one. - -Let's get the ``akka-1.1`` distribution of Akka core (not Akka Modules) from `http://akka.io/downloads `_. Once you have downloaded the distribution unzip it in the folder you would like to have Akka installed in, in my case I choose to install it in ``/Users/jboner/tools/``, simply by unzipping it to this directory. - -You need to do one more thing in order to install Akka properly: set the ``AKKA_HOME`` environment variable to the root of the distribution. In my case I'm opening up a shell, navigating down to the distribution, and setting the ``AKKA_HOME`` variable:: - - $ cd /Users/jboner/tools/akka-1.1 - $ export AKKA_HOME=`pwd` - $ echo $AKKA_HOME - /Users/jboner/tools/akka-1.1 - -The distribution looks like this:: - - $ ls -l - total 16944 - drwxr-xr-x 7 jboner staff 238 Apr 6 11:15 . - drwxr-xr-x 28 jboner staff 952 Apr 6 11:16 .. - drwxr-xr-x 17 jboner staff 578 Apr 6 11:16 deploy - drwxr-xr-x 26 jboner staff 884 Apr 6 11:16 dist - drwxr-xr-x 3 jboner staff 102 Apr 6 11:15 lib_managed - -rwxr-xr-x 1 jboner staff 8674105 Apr 6 11:15 scala-library.jar - drwxr-xr-x 4 jboner staff 136 Apr 6 11:16 scripts - -- In the ``dist`` directory we have the Akka JARs, including sources and docs. -- In the ``lib_managed/compile`` directory we have Akka's dependency JARs. -- In the ``deploy`` directory we have the sample JARs. -- In the ``scripts`` directory we have scripts for running Akka. -- Finally ``scala-library.jar`` is the JAR for the latest Scala distribution that Akka depends on. - -The only JAR we will need for this tutorial (apart from the ``scala-library.jar`` JAR) is the ``akka-actor-1.1.jar`` JAR in the ``dist`` directory. This is a self-contained JAR with zero dependencies and contains everything we need to write a system using Actors. - -Akka is very modular and has many JARs for containing different features. The core distribution has seven modules: - -- ``akka-actor-1.1.jar`` -- Standard Actors -- ``akka-typed-actor-1.1.jar`` -- Typed Actors -- ``akka-remote-1.1.jar`` -- Remote Actors -- ``akka-stm-1.1.jar`` -- STM (Software Transactional Memory), transactors and transactional datastructures -- ``akka-http-1.1.jar`` -- Akka Mist for continuation-based asynchronous HTTP and also Jersey integration -- ``akka-slf4j-1.1.jar`` -- SLF4J Event Handler Listener -- ``akka-testkit-1.1.jar`` -- Toolkit for testing Actors - -We also have Akka Modules containing add-on modules outside the core of Akka. You can download the Akka Modules distribution from ``_. It contains Akka core as well. We will not be needing any modules there today, but for your information the module JARs are these: - -- ``akka-kernel-1.1.jar`` -- Akka microkernel for running a bare-bones mini application server (embeds Jetty etc.) -- ``akka-amqp-1.1.jar`` -- AMQP integration -- ``akka-camel-1.1.jar`` -- Apache Camel Actors integration (it's the best way to have your Akka application communicate with the rest of the world) -- ``akka-camel-typed-1.1.jar`` -- Apache Camel Typed Actors integration -- ``akka-scalaz-1.1.jar`` -- Support for the Scalaz library -- ``akka-spring-1.1.jar`` -- Spring framework integration -- ``akka-osgi-dependencies-bundle-1.1.jar`` -- OSGi support - -Downloading and installing Scala --------------------------------- - -To build and run the tutorial sample from the command line, you have to install the Scala distribution. If you prefer to use SBT to build and run the sample then you can skip this section and jump to the next one. - -Scala can be downloaded from `http://www.scala-lang.org/downloads `_. Browse there and download the Scala 2.9.0 release. If you pick the ``tgz`` or ``zip`` distribution then just unzip it where you want it installed. If you pick the IzPack Installer then double click on it and follow the instructions. - -You also need to make sure that the ``scala-2.9.0/bin`` (if that is the directory where you installed Scala) is on your ``PATH``:: - - $ export PATH=$PATH:scala-2.9.0/bin - -You can test your installation by invoking scala:: - - $ scala -version - Scala code runner version 2.9.0.final -- Copyright 2002-2011, LAMP/EPFL - -Looks like we are all good. Finally let's create a source file ``Pi.scala`` for the tutorial and put it in the root of the Akka distribution in the ``tutorial`` directory (you have to create it first). - -Some tools require you to set the ``SCALA_HOME`` environment variable to the root of the Scala distribution, however Akka does not require that. - -Downloading and installing SBT ------------------------------- - -SBT, short for 'Simple Build Tool' is an excellent build system written in Scala. It uses Scala to write the build scripts which gives you a lot of power. It has a plugin architecture with many plugins available, something that we will take advantage of soon. SBT is the preferred way of building software in Scala and is probably the easiest way of getting through this tutorial. If you want to use SBT for this tutorial then follow the following instructions, if not you can skip this section and the next. - -First browse to the `SBT download page `_ and download the ``0.7.6.RC0`` distribution. - -To install SBT and create a project for this tutorial it is easiest to follow the instructions on `this page `_. - -If you have created an SBT project then step into the newly created SBT project, create a source file ``Pi.scala`` for the tutorial sample and put it in the ``src/main/scala`` directory. - -So far we only have a standard Scala project but now we need to make our project an Akka project. You could add the dependencies manually to the build script, but the easiest way is to use Akka's SBT Plugin, covered in the next section. - -Creating an Akka SBT project ----------------------------- - -If you have not already done so, now is the time to create an SBT project for our tutorial. You do that by stepping into the directory you want to create your project in and invoking the ``sbt`` command answering the questions for setting up your project (just pressing ENTER will choose the default in square brackets):: - - $ sbt - Project does not exist, create new project? (y/N/s) y - Name: Tutorial 1 - Organization: Hakkers Inc - Version [1.0]: - Scala version [2.9.0]: - sbt version [0.7.6.RC0]: - -Now we have the basis for an SBT project. Akka has an SBT Plugin making it very easy to use Akka is an SBT-based project so let's use that. - -To use the plugin, first add a plugin definition to your SBT project by creating a ``Plugins.scala`` file in the ``project/plugins`` directory containing:: - - import sbt._ - - class Plugins(info: ProjectInfo) extends PluginDefinition(info) { - val akkaRepo = "Akka Repo" at "http://akka.io/repository" - val akkaPlugin = "se.scalablesolutions.akka" % "akka-sbt-plugin" % "1.1" - } - -Now we need to create a project definition using our Akka SBT plugin. We do that by creating a ``project/build/Project.scala`` file containing:: - - import sbt._ - - class TutorialOneProject(info: ProjectInfo) extends DefaultProject(info) with AkkaProject { - val akkaRepo = "Akka Repo" at "http://akka.io/repository" - } - -The magic is in mixing in the ``AkkaProject`` trait. - -Not needed in this tutorial, but if you would like to use additional Akka modules beyond ``akka-actor``, you can add these as "module configurations" in the project file. Here is an example adding ``akka-remote`` and ``akka-stm``:: - - class AkkaSampleProject(info: ProjectInfo) extends DefaultProject(info) with AkkaProject { - val akkaSTM = akkaModule("stm") - val akkaRemote = akkaModule("remote") - } - -So, now we are all set. Just one final thing to do; make SBT download the dependencies it needs. That is done by invoking:: - - > update - -SBT itself needs a whole bunch of dependencies but our project will only need one; ``akka-actor-1.1.jar``. SBT downloads that as well. - Start writing the code ---------------------- @@ -236,7 +67,7 @@ Here is the master actor: A couple of things are worth explaining further. -First, we are passing in a ``java.util.concurrent.CountDownLatch`` to the ``Master`` actor. This latch is only used for plumbing (in this specific tutorial), to have a simple way of letting the outside world knowing when the master can deliver the result and shut down. In more idiomatic Akka code, as we will see in part two of this tutorial series, we would not use a latch but other abstractions and functions like ``Channel``, ``Future`` and ``!!!`` to achive the same thing in a non-blocking way. But for simplicity let's stick to a ``CountDownLatch`` for now. +First, we are passing in a ``java.util.concurrent.CountDownLatch`` to the ``Master`` actor. This latch is only used for plumbing (in this specific tutorial), to have a simple way of letting the outside world knowing when the master can deliver the result and shut down. In more idiomatic Akka code, as we will see in part two of this tutorial series, we would not use a latch but other abstractions and functions like ``Channel``, ``Future`` and ``?`` to achive the same thing in a non-blocking way. But for simplicity let's stick to a ``CountDownLatch`` for now. Second, we are adding a couple of life-cycle callback methods; ``preStart`` and ``postStop``. In the ``preStart`` callback we are recording the time when the actor is started and in the ``postStop`` callback we are printing out the result (the approximation of Pi) and the time it took to calculate it. In this call we also invoke ``latch.countDown`` to tell the outside world that we are done. @@ -268,69 +99,3 @@ That's it. Now we are done. But before we package it up and run it, let's take a look at the full code now, with package declaration, imports and all: .. includecode:: examples/Pi.scala - -Run it as a command line application ------------------------------------- - -If you have not typed in (or copied) the code for the tutorial as ``$AKKA_HOME/tutorial/Pi.scala`` then now is the time. When that's done open up a shell and step in to the Akka distribution (``cd $AKKA_HOME``). - -First we need to compile the source file. That is done with Scala's compiler ``scalac``. Our application depends on the ``akka-actor-1.1.jar`` JAR file, so let's add that to the compiler classpath when we compile the source:: - - $ scalac -cp dist/akka-actor-1.1.jar tutorial/Pi.scala - -When we have compiled the source file we are ready to run the application. This is done with ``java`` but yet again we need to add the ``akka-actor-1.1.jar`` JAR file to the classpath, and this time we also need to add the Scala runtime library ``scala-library.jar`` and the classes we compiled ourselves:: - - $ java -cp dist/akka-actor-1.1.jar:scala-library.jar:tutorial akka.tutorial.scala.first.Pi - AKKA_HOME is defined as [/Users/jboner/src/akka-stuff/akka-core], loading config from \ - [/Users/jboner/src/akka-stuff/akka-core/config/akka.conf]. - - Pi estimate: 3.1435501812459323 - Calculation time: 858 millis - -Yippee! It is working. - -If you have not defined an the ``AKKA_HOME`` environment variable then Akka can't find the ``akka.conf`` configuration file and will print out a ``Can’t load akka.conf`` warning. This is ok since it will then just use the defaults. - -Run it inside SBT ------------------ - -If you used SBT, then you can run the application directly inside SBT. First you need to compile the project:: - - $ sbt - > update - ... - > compile - ... - -When this in done we can run our application directly inside SBT:: - - > run - ... - Pi estimate: 3.1435501812459323 - Calculation time: 942 millis - -Yippee! It is working. - -If you have not defined an the ``AKKA_HOME`` environment variable then Akka can't find the ``akka.conf`` configuration file and will print out a ``Can’t load akka.conf`` warning. This is ok since it will then just use the defaults. - -The implementation in more detail ---------------------------------- - -To create our actors we used a method called ``actorOf`` in the ``Actor`` object. We used it in two different ways, one of them taking a actor type and the other one an instance of an actor. The former one (``actorOf[Worker]``) is used when the actor class has a no-argument constructor while the second one (``actorOf(new Master(..))``) is used when the actor class has a constructor that takes arguments. This is the only way to create an instance of an Actor and the ``actorOf`` method ensures this. The latter version is using call-by-name and lazily creates the actor within the scope of the ``actorOf`` method. The ``actorOf`` method instantiates the actor and returns, not an instance to the actor, but an instance to an ``ActorRef``. This reference is the handle through which you communicate with the actor. It is immutable, serializable and location-aware meaning that it "remembers" its original actor even if it is sent to other nodes across the network and can be seen as the equivalent to the Erlang actor's PID. - -The actor's life-cycle is: - -- Created -- ``Actor.actorOf[MyActor]`` -- can **not** receive messages -- Started -- ``actorRef.start()`` -- can receive messages -- Stopped -- ``actorRef.stop()`` -- can **not** receive messages - -Once the actor has been stopped it is dead and can not be started again. - -Conclusion ----------- - -We have learned how to create our first Akka project using Akka's actors to speed up a computation-intensive problem by scaling out on multi-core processors (also known as scaling up). We have also learned to compile and run an Akka project using either the tools on the command line or the SBT build system. - -Now we are ready to take on more advanced problems. In the next tutorial we will build on this one, refactor it into more idiomatic Akka and Scala code, and introduce a few new concepts and abstractions. Whenever you feel ready, join me in the `Getting Started Tutorial: Second Chapter `_. - -Happy hakking. diff --git a/akka-docs/intro/deployment-scenarios.rst b/akka-docs/intro/deployment-scenarios.rst index a8343d5b33..1dc4879d6e 100644 --- a/akka-docs/intro/deployment-scenarios.rst +++ b/akka-docs/intro/deployment-scenarios.rst @@ -41,7 +41,7 @@ Using Akka as a stand alone microkernel --------------------------------------- Akka can also be run as a stand-alone microkernel. It implements a full -enterprise stack. See the :ref:`add-on-modules` for more information. +enterprise stack. See the :ref:`microkernel` for more information. Using the Akka sbt plugin to package your application ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -56,7 +56,7 @@ To use the plugin, first add a plugin definition to your SBT project by creating class Plugins(info: ProjectInfo) extends PluginDefinition(info) { val akkaRepo = "Akka Repo" at "http://akka.io/repository" - val akkaPlugin = "se.scalablesolutions.akka" % "akka-sbt-plugin" % "1.1" + val akkaPlugin = "se.scalablesolutions.akka" % "akka-sbt-plugin" % "2.0-SNAPSHOT" } Then mix the ``AkkaKernelProject`` trait into your project definition. For diff --git a/akka-docs/intro/getting-started-first-java.rst b/akka-docs/intro/getting-started-first-java.rst index 6b4b724216..57bfd01db9 100644 --- a/akka-docs/intro/getting-started-first-java.rst +++ b/akka-docs/intro/getting-started-first-java.rst @@ -66,7 +66,7 @@ To build and run the tutorial sample from the command line, you have to download Akka. If you prefer to use SBT to build and run the sample then you can skip this section and jump to the next one. -Let's get the ``akka-actors-1.1.zip`` distribution of Akka from +Let's get the ``akka-actors-2.0-SNAPSHOT.zip`` distribution of Akka from http://akka.io/downloads/ which includes everything we need for this tutorial. Once you have downloaded the distribution unzip it in the folder you would like to have Akka installed in. In my case I choose to install it in @@ -77,10 +77,10 @@ You need to do one more thing in order to install Akka properly: set the I'm opening up a shell, navigating down to the distribution, and setting the ``AKKA_HOME`` variable:: - $ cd /Users/jboner/tools/akka-actors-1.1 + $ cd /Users/jboner/tools/akka-actors-2.0-SNAPSHOT $ export AKKA_HOME=`pwd` $ echo $AKKA_HOME - /Users/jboner/tools/akka-actors-1.1 + /Users/jboner/tools/akka-actors-2.0-SNAPSHOT The distribution looks like this:: @@ -98,32 +98,26 @@ The distribution looks like this:: The only JAR we will need for this tutorial (apart from the -``scala-library.jar`` JAR) is the ``akka-actor-1.1.jar`` JAR in the ``lib/akka`` +``scala-library.jar`` JAR) is the ``akka-actor-2.0-SNAPSHOT.jar`` JAR in the ``lib/akka`` directory. This is a self-contained JAR with zero dependencies and contains everything we need to write a system using Actors. Akka is very modular and has many JARs for containing different features. The core distribution has seven modules: -- ``akka-actor-1.1.jar`` -- Standard Actors -- ``akka-typed-actor-1.1.jar`` -- Typed Actors -- ``akka-remote-1.1.jar`` -- Remote Actors -- ``akka-stm-1.1.jar`` -- STM (Software Transactional Memory), transactors and transactional datastructures -- ``akka-http-1.1.jar`` -- Akka Mist for continuation-based asynchronous HTTP and also Jersey integration -- ``akka-slf4j-1.1.jar`` -- SLF4J Event Handler Listener for logging with SLF4J -- ``akka-testkit-1.1.jar`` -- Toolkit for testing Actors +- ``akka-actor-2.0-SNAPSHOT.jar`` -- Standard Actors +- ``akka-typed-actor-2.0-SNAPSHOT.jar`` -- Typed Actors +- ``akka-remote-2.0-SNAPSHOT.jar`` -- Remote Actors +- ``akka-stm-2.0-SNAPSHOT.jar`` -- STM (Software Transactional Memory), transactors and transactional datastructures +- ``akka-http-2.0-SNAPSHOT.jar`` -- Akka Mist for continuation-based asynchronous HTTP and also Jersey integration +- ``akka-slf4j-2.0-SNAPSHOT.jar`` -- SLF4J Event Handler Listener for logging with SLF4J +- ``akka-testkit-2.0-SNAPSHOT.jar`` -- Toolkit for testing Actors -We also have Akka Modules containing add-on modules outside the core of -Akka. You can download the Akka Modules distribution from ``_. It contains Akka -core as well. We will not be needing any modules there today, but for your -information the module JARs are these: +The Akka Microkernel distribution also includes these jars: -- ``akka-kernel-1.1.jar`` -- Akka microkernel for running a bare-bones mini application server (embeds Jetty etc.) -- ``akka-amqp-1.1.jar`` -- AMQP integration -- ``akka-camel-1.1.jar`` -- Apache Camel Actors integration (it's the best way to have your Akka application communicate with the rest of the world) -- ``akka-camel-typed-1.1.jar`` -- Apache Camel Typed Actors integration -- ``akka-scalaz-1.1.jar`` -- Support for the Scalaz library -- ``akka-spring-1.1.jar`` -- Spring framework integration -- ``akka-osgi-dependencies-bundle-1.1.jar`` -- OSGi support +- ``akka-kernel-2.0-SNAPSHOT.jar`` -- Akka microkernel for running a bare-bones mini application server (embeds Jetty etc.) +- ``akka-camel-2.0-SNAPSHOT.jar`` -- Apache Camel Actors integration (it's the best way to have your Akka application communicate with the rest of the world) +- ``akka-camel-typed-2.0-SNAPSHOT.jar`` -- Apache Camel Typed Actors integration +- ``akka-spring-2.0-SNAPSHOT.jar`` -- Spring framework integration Downloading and installing Maven @@ -186,7 +180,7 @@ We also need to edit the ``pom.xml`` build file. Let's add the dependency we nee se.scalablesolutions.akka akka-actor - 1.1 + 2.0-SNAPSHOT @@ -441,7 +435,7 @@ Here is the master actor:: A couple of things are worth explaining further. -First, we are passing in a ``java.util.concurrent.CountDownLatch`` to the ``Master`` actor. This latch is only used for plumbing (in this specific tutorial), to have a simple way of letting the outside world knowing when the master can deliver the result and shut down. In more idiomatic Akka code, as we will see in part two of this tutorial series, we would not use a latch but other abstractions and functions like ``Channel``, ``Future`` and ``!!!`` to achieve the same thing in a non-blocking way. But for simplicity let's stick to a ``CountDownLatch`` for now. +First, we are passing in a ``java.util.concurrent.CountDownLatch`` to the ``Master`` actor. This latch is only used for plumbing (in this specific tutorial), to have a simple way of letting the outside world knowing when the master can deliver the result and shut down. In more idiomatic Akka code, as we will see in part two of this tutorial series, we would not use a latch but other abstractions and functions like ``Channel``, ``Future`` and ``?`` to achieve the same thing in a non-blocking way. But for simplicity let's stick to a ``CountDownLatch`` for now. Second, we are adding a couple of life-cycle callback methods; ``preStart`` and ``postStop``. In the ``preStart`` callback we are recording the time when the actor is started and in the ``postStop`` callback we are printing out the result (the approximation of Pi) and the time it took to calculate it. In this call we also invoke ``latch.countDown()`` to tell the outside world that we are done. @@ -721,22 +715,22 @@ time. When that's done open up a shell and step in to the Akka distribution (``cd $AKKA_HOME``). First we need to compile the source file. That is done with Java's compiler -``javac``. Our application depends on the ``akka-actor-1.1.jar`` and the +``javac``. Our application depends on the ``akka-actor-2.0-SNAPSHOT.jar`` and the ``scala-library.jar`` JAR files, so let's add them to the compiler classpath when we compile the source:: - $ javac -cp lib/scala-library.jar:lib/akka/akka-actor-1.1.jar tutorial/akka/tutorial/first/java/Pi.java + $ javac -cp lib/scala-library.jar:lib/akka/akka-actor-2.0-SNAPSHOT.jar tutorial/akka/tutorial/first/java/Pi.java When we have compiled the source file we are ready to run the application. This -is done with ``java`` but yet again we need to add the ``akka-actor-1.1.jar`` +is done with ``java`` but yet again we need to add the ``akka-actor-2.0-SNAPSHOT.jar`` and the ``scala-library.jar`` JAR files to the classpath as well as the classes we compiled ourselves:: $ java \ - -cp lib/scala-library.jar:lib/akka/akka-actor-1.1.jar:tutorial \ + -cp lib/scala-library.jar:lib/akka/akka-actor-2.0-SNAPSHOT.jar:tutorial \ akka.tutorial.java.first.Pi - AKKA_HOME is defined as [/Users/jboner/tools/akka-actors-1.1] - loading config from [/Users/jboner/tools/akka-actors-1.1/config/akka.conf]. + AKKA_HOME is defined as [/Users/jboner/tools/akka-actors-2.0-SNAPSHOT] + loading config from [/Users/jboner/tools/akka-actors-2.0-SNAPSHOT/config/akka.conf]. Pi estimate: 3.1435501812459323 Calculation time: 822 millis diff --git a/akka-docs/intro/getting-started-first-scala-eclipse.rst b/akka-docs/intro/getting-started-first-scala-eclipse.rst index bfe533f148..d9c7356471 100644 --- a/akka-docs/intro/getting-started-first-scala-eclipse.rst +++ b/akka-docs/intro/getting-started-first-scala-eclipse.rst @@ -51,7 +51,7 @@ To build and run the tutorial sample from the command line, you have to download Akka. If you prefer to use SBT to build and run the sample then you can skip this section and jump to the next one. -Let's get the ``akka-actors-1.1.zip`` distribution of Akka from +Let's get the ``akka-actors-2.0-SNAPSHOT.zip`` distribution of Akka from http://akka.io/downloads/ which includes everything we need for this tutorial. Once you have downloaded the distribution unzip it in the folder you would like to have Akka installed in. In my case I choose to install it in @@ -62,10 +62,10 @@ You need to do one more thing in order to install Akka properly: set the I'm opening up a shell, navigating down to the distribution, and setting the ``AKKA_HOME`` variable:: - $ cd /Users/jboner/tools/akka-actors-1.1 + $ cd /Users/jboner/tools/akka-actors-2.0-SNAPSHOT $ export AKKA_HOME=`pwd` $ echo $AKKA_HOME - /Users/jboner/tools/akka-actors-1.1 + /Users/jboner/tools/akka-actors-2.0-SNAPSHOT The distribution looks like this:: @@ -83,32 +83,26 @@ The distribution looks like this:: The only JAR we will need for this tutorial (apart from the -``scala-library.jar`` JAR) is the ``akka-actor-1.1.jar`` JAR in the ``lib/akka`` +``scala-library.jar`` JAR) is the ``akka-actor-2.0-SNAPSHOT.jar`` JAR in the ``lib/akka`` directory. This is a self-contained JAR with zero dependencies and contains everything we need to write a system using Actors. Akka is very modular and has many JARs for containing different features. The core distribution has seven modules: -- ``akka-actor-1.1.jar`` -- Standard Actors -- ``akka-typed-actor-1.1.jar`` -- Typed Actors -- ``akka-remote-1.1.jar`` -- Remote Actors -- ``akka-stm-1.1.jar`` -- STM (Software Transactional Memory), transactors and transactional datastructures -- ``akka-http-1.1.jar`` -- Akka Mist for continuation-based asynchronous HTTP and also Jersey integration -- ``akka-slf4j-1.1.jar`` -- SLF4J Event Handler Listener for logging with SLF4J -- ``akka-testkit-1.1.jar`` -- Toolkit for testing Actors +- ``akka-actor-2.0-SNAPSHOT.jar`` -- Standard Actors +- ``akka-typed-actor-2.0-SNAPSHOT.jar`` -- Typed Actors +- ``akka-remote-2.0-SNAPSHOT.jar`` -- Remote Actors +- ``akka-stm-2.0-SNAPSHOT.jar`` -- STM (Software Transactional Memory), transactors and transactional datastructures +- ``akka-http-2.0-SNAPSHOT.jar`` -- Akka Mist for continuation-based asynchronous HTTP and also Jersey integration +- ``akka-slf4j-2.0-SNAPSHOT.jar`` -- SLF4J Event Handler Listener for logging with SLF4J +- ``akka-testkit-2.0-SNAPSHOT.jar`` -- Toolkit for testing Actors -We also have Akka Modules containing add-on modules outside the core of -Akka. You can download the Akka Modules distribution from ``_. It contains Akka -core as well. We will not be needing any modules there today, but for your -information the module JARs are these: +The Akka Microkernel distribution also includes these jars: -- ``akka-kernel-1.1.jar`` -- Akka microkernel for running a bare-bones mini application server (embeds Jetty etc.) -- ``akka-amqp-1.1.jar`` -- AMQP integration -- ``akka-camel-1.1.jar`` -- Apache Camel Actors integration (it's the best way to have your Akka application communicate with the rest of the world) -- ``akka-camel-typed-1.1.jar`` -- Apache Camel Typed Actors integration -- ``akka-scalaz-1.1.jar`` -- Support for the Scalaz library -- ``akka-spring-1.1.jar`` -- Spring framework integration -- ``akka-osgi-dependencies-bundle-1.1.jar`` -- OSGi support +- ``akka-kernel-2.0-SNAPSHOT.jar`` -- Akka microkernel for running a bare-bones mini application server (embeds Jetty etc.) +- ``akka-camel-2.0-SNAPSHOT.jar`` -- Apache Camel Actors integration (it's the best way to have your Akka application communicate with the rest of the world) +- ``akka-camel-typed-2.0-SNAPSHOT.jar`` -- Apache Camel Typed Actors integration +- ``akka-spring-2.0-SNAPSHOT.jar`` -- Spring framework integration Downloading and installing the Scala IDE for Eclipse @@ -173,7 +167,7 @@ If you are an `SBT `_ user, you can lazy val eclipse = "de.element34" % "sbt-eclipsify" % "0.7.0" val akkaRepo = "Akka Repo" at "http://akka.io/repository" - val akkaPlugin = "se.scalablesolutions.akka" % "akka-sbt-plugin" % "1.1" + val akkaPlugin = "se.scalablesolutions.akka" % "akka-sbt-plugin" % "2.0-SNAPSHOT" } and then update your SBT project definition by mixing in ``Eclipsify`` in your project definition:: @@ -341,7 +335,7 @@ Here is the master actor:: A couple of things are worth explaining further. -First, we are passing in a ``java.util.concurrent.CountDownLatch`` to the ``Master`` actor. This latch is only used for plumbing (in this specific tutorial), to have a simple way of letting the outside world knowing when the master can deliver the result and shut down. In more idiomatic Akka code, as we will see in part two of this tutorial series, we would not use a latch but other abstractions and functions like ``Channel``, ``Future`` and ``!!!`` to achieve the same thing in a non-blocking way. But for simplicity let's stick to a ``CountDownLatch`` for now. +First, we are passing in a ``java.util.concurrent.CountDownLatch`` to the ``Master`` actor. This latch is only used for plumbing (in this specific tutorial), to have a simple way of letting the outside world knowing when the master can deliver the result and shut down. In more idiomatic Akka code, as we will see in part two of this tutorial series, we would not use a latch but other abstractions and functions like ``Channel``, ``Future`` and ``?`` to achieve the same thing in a non-blocking way. But for simplicity let's stick to a ``CountDownLatch`` for now. Second, we are adding a couple of life-cycle callback methods; ``preStart`` and ``postStop``. In the ``preStart`` callback we are recording the time when the actor is started and in the ``postStop`` callback we are printing out the result (the approximation of Pi) and the time it took to calculate it. In this call we also invoke ``latch.countDown`` to tell the outside world that we are done. @@ -412,8 +406,8 @@ Run it from Eclipse Eclipse builds your project on every save when ``Project/Build Automatically`` is set. If not, bring you project up to date by clicking ``Project/Build Project``. If there are no compilation errors, you can right-click in the editor where ``Pi`` is defined, and choose ``Run as.. /Scala application``. If everything works fine, you should see:: - AKKA_HOME is defined as [/Users/jboner/tools/akka-actors-1.1] - loading config from [/Users/jboner/tools/akka-actors-1.1/config/akka.conf]. + AKKA_HOME is defined as [/Users/jboner/tools/akka-actors-2.0-SNAPSHOT] + loading config from [/Users/jboner/tools/akka-actors-2.0-SNAPSHOT/config/akka.conf]. Pi estimate: 3.1435501812459323 Calculation time: 858 millis diff --git a/akka-docs/intro/getting-started-first-scala.rst b/akka-docs/intro/getting-started-first-scala.rst index f72d5812e9..05ce8a15ce 100644 --- a/akka-docs/intro/getting-started-first-scala.rst +++ b/akka-docs/intro/getting-started-first-scala.rst @@ -37,7 +37,7 @@ To check out the code using Git invoke the following:: $ git clone git://github.com/jboner/akka.git -Then you can navigate down to the tutorial:: +Then you can navigate down to the tutorial:: $ cd akka/akka-tutorials/akka-tutorial-first @@ -63,10 +63,9 @@ Downloading and installing Akka ------------------------------- To build and run the tutorial sample from the command line, you have to download -Akka. If you prefer to use SBT to build and run the sample then you can skip -this section and jump to the next one. +Akka. If you prefer to use SBT to build and run the sample then you can skipthis section and jump to the next one. -Let's get the ``akka-actors-1.1.zip`` distribution of Akka from +Let's get the ``akka-actors-2.0-SNAPSHOT.zip`` distribution of Akka from http://akka.io/downloads/ which includes everything we need for this tutorial. Once you have downloaded the distribution unzip it in the folder you would like to have Akka installed in. In my case I choose to install it in @@ -77,10 +76,10 @@ You need to do one more thing in order to install Akka properly: set the I'm opening up a shell, navigating down to the distribution, and setting the ``AKKA_HOME`` variable:: - $ cd /Users/jboner/tools/akka-actors-1.1 + $ cd /Users/jboner/tools/akka-actors-2.0-SNAPSHOT $ export AKKA_HOME=`pwd` $ echo $AKKA_HOME - /Users/jboner/tools/akka-actors-1.1 + /Users/jboner/tools/akka-actors-2.0-SNAPSHOT The distribution looks like this:: @@ -98,32 +97,26 @@ The distribution looks like this:: The only JAR we will need for this tutorial (apart from the -``scala-library.jar`` JAR) is the ``akka-actor-1.1.jar`` JAR in the ``lib/akka`` +``scala-library.jar`` JAR) is the ``akka-actor-2.0-SNAPSHOT.jar`` JAR in the ``lib/akka`` directory. This is a self-contained JAR with zero dependencies and contains everything we need to write a system using Actors. Akka is very modular and has many JARs for containing different features. The core distribution has seven modules: -- ``akka-actor-1.1.jar`` -- Standard Actors -- ``akka-typed-actor-1.1.jar`` -- Typed Actors -- ``akka-remote-1.1.jar`` -- Remote Actors -- ``akka-stm-1.1.jar`` -- STM (Software Transactional Memory), transactors and transactional datastructures -- ``akka-http-1.1.jar`` -- Akka Mist for continuation-based asynchronous HTTP and also Jersey integration -- ``akka-slf4j-1.1.jar`` -- SLF4J Event Handler Listener for logging with SLF4J -- ``akka-testkit-1.1.jar`` -- Toolkit for testing Actors +- ``akka-actor-2.0-SNAPSHOT.jar`` -- Standard Actors +- ``akka-typed-actor-2.0-SNAPSHOT.jar`` -- Typed Actors +- ``akka-remote-2.0-SNAPSHOT.jar`` -- Remote Actors +- ``akka-stm-2.0-SNAPSHOT.jar`` -- STM (Software Transactional Memory), transactors and transactional datastructures +- ``akka-http-2.0-SNAPSHOT.jar`` -- Akka Mist for continuation-based asynchronous HTTP and also Jersey integration +- ``akka-slf4j-2.0-SNAPSHOT.jar`` -- SLF4J Event Handler Listener for logging with SLF4J +- ``akka-testkit-2.0-SNAPSHOT.jar`` -- Toolkit for testing Actors -We also have Akka Modules containing add-on modules outside the core of -Akka. You can download the Akka Modules distribution from ``_. It contains Akka -core as well. We will not be needing any modules there today, but for your -information the module JARs are these: +The Akka Microkernel distribution also includes these jars: -- ``akka-kernel-1.1.jar`` -- Akka microkernel for running a bare-bones mini application server (embeds Jetty etc.) -- ``akka-amqp-1.1.jar`` -- AMQP integration -- ``akka-camel-1.1.jar`` -- Apache Camel Actors integration (it's the best way to have your Akka application communicate with the rest of the world) -- ``akka-camel-typed-1.1.jar`` -- Apache Camel Typed Actors integration -- ``akka-scalaz-1.1.jar`` -- Support for the Scalaz library -- ``akka-spring-1.1.jar`` -- Spring framework integration -- ``akka-osgi-dependencies-bundle-1.1.jar`` -- OSGi support +- ``akka-kernel-2.0-SNAPSHOT.jar`` -- Akka microkernel for running a bare-bones mini application server (embeds Jetty etc.) +- ``akka-camel-2.0-SNAPSHOT.jar`` -- Apache Camel Actors integration (it's the best way to have your Akka application communicate with the rest of the world) +- ``akka-camel-typed-2.0-SNAPSHOT.jar`` -- Apache Camel Typed Actors integration +- ``akka-spring-2.0-SNAPSHOT.jar`` -- Spring framework integration Downloading and installing Scala @@ -180,7 +173,7 @@ To use the plugin, first add a plugin definition to your SBT project by creating class Plugins(info: ProjectInfo) extends PluginDefinition(info) { val akkaRepo = "Akka Repo" at "http://akka.io/repository" - val akkaPlugin = "se.scalablesolutions.akka" % "akka-sbt-plugin" % "1.1" + val akkaPlugin = "se.scalablesolutions.akka" % "akka-sbt-plugin" % "2.0-SNAPSHOT" } Now we need to create a project definition using our Akka SBT plugin. We do that by creating a ``project/build/Project.scala`` file containing:: @@ -205,7 +198,7 @@ So, now we are all set. Just one final thing to do; make SBT download the depend The first reload command is needed because we have changed the project definition since the sbt session started. -SBT itself needs a whole bunch of dependencies but our project will only need one; ``akka-actor-1.1.jar``. SBT downloads that as well. +SBT itself needs a whole bunch of dependencies but our project will only need one; ``akka-actor-2.0-SNAPSHOT.jar``. SBT downloads that as well. Start writing the code ---------------------- @@ -336,7 +329,7 @@ Here is the master actor:: A couple of things are worth explaining further. -First, we are passing in a ``java.util.concurrent.CountDownLatch`` to the ``Master`` actor. This latch is only used for plumbing (in this specific tutorial), to have a simple way of letting the outside world knowing when the master can deliver the result and shut down. In more idiomatic Akka code, as we will see in part two of this tutorial series, we would not use a latch but other abstractions and functions like ``Channel``, ``Future`` and ``!!!`` to achieve the same thing in a non-blocking way. But for simplicity let's stick to a ``CountDownLatch`` for now. +First, we are passing in a ``java.util.concurrent.CountDownLatch`` to the ``Master`` actor. This latch is only used for plumbing (in this specific tutorial), to have a simple way of letting the outside world knowing when the master can deliver the result and shut down. In more idiomatic Akka code, as we will see in part two of this tutorial series, we would not use a latch but other abstractions and functions like ``Channel``, ``Future`` and ``?`` to achieve the same thing in a non-blocking way. But for simplicity let's stick to a ``CountDownLatch`` for now. Second, we are adding a couple of life-cycle callback methods; ``preStart`` and ``postStop``. In the ``preStart`` callback we are recording the time when the actor is started and in the ``postStop`` callback we are printing out the result (the approximation of Pi) and the time it took to calculate it. In this call we also invoke ``latch.countDown`` to tell the outside world that we are done. @@ -519,17 +512,17 @@ Run it as a command line application If you have not typed in (or copied) the code for the tutorial as ``$AKKA_HOME/tutorial/Pi.scala`` then now is the time. When that's done open up a shell and step in to the Akka distribution (``cd $AKKA_HOME``). -First we need to compile the source file. That is done with Scala's compiler ``scalac``. Our application depends on the ``akka-actor-1.1.jar`` JAR file, so let's add that to the compiler classpath when we compile the source:: +First we need to compile the source file. That is done with Scala's compiler ``scalac``. Our application depends on the ``akka-actor-2.0-SNAPSHOT.jar`` JAR file, so let's add that to the compiler classpath when we compile the source:: - $ scalac -cp lib/akka/akka-actor-1.1.jar tutorial/Pi.scala + $ scalac -cp lib/akka/akka-actor-2.0-SNAPSHOT.jar tutorial/Pi.scala -When we have compiled the source file we are ready to run the application. This is done with ``java`` but yet again we need to add the ``akka-actor-1.1.jar`` JAR file to the classpath, and this time we also need to add the Scala runtime library ``scala-library.jar`` and the classes we compiled ourselves:: +When we have compiled the source file we are ready to run the application. This is done with ``java`` but yet again we need to add the ``akka-actor-2.0-SNAPSHOT.jar`` JAR file to the classpath, and this time we also need to add the Scala runtime library ``scala-library.jar`` and the classes we compiled ourselves:: $ java \ - -cp lib/scala-library.jar:lib/akka/akka-actor-1.1.jar:. \ + -cp lib/scala-library.jar:lib/akka/akka-actor-2.0-SNAPSHOT.jar:. \ akka.tutorial.first.scala.Pi - AKKA_HOME is defined as [/Users/jboner/tools/akka-actors-1.1] - loading config from [/Users/jboner/tools/akka-actors-1.1/config/akka.conf]. + AKKA_HOME is defined as [/Users/jboner/tools/akka-actors-2.0-SNAPSHOT] + loading config from [/Users/jboner/tools/akka-actors-2.0-SNAPSHOT/config/akka.conf]. Pi estimate: 3.1435501812459323 Calculation time: 858 millis diff --git a/akka-docs/intro/getting-started.rst b/akka-docs/intro/getting-started.rst index 049dc103e2..377f2c8de8 100644 --- a/akka-docs/intro/getting-started.rst +++ b/akka-docs/intro/getting-started.rst @@ -40,31 +40,19 @@ dependencies from the Akka Maven repository. Modules ------- -Akka is split up into two different parts: - -* Akka - The core modules. Reflects all the sections under :ref:`scala-api` and :ref:`java-api`. -* Akka Modules - The microkernel and add-on modules, described in :ref:`add-on-modules`. - -Akka is very modular and has many JARs for containing different features. The core distribution has seven modules: - -- ``akka-actor-1.1.jar`` -- Standard Actors -- ``akka-typed-actor-1.1.jar`` -- Typed Actors -- ``akka-remote-1.1.jar`` -- Remote Actors -- ``akka-stm-1.1.jar`` -- STM (Software Transactional Memory), transactors and transactional datastructures -- ``akka-http-1.1.jar`` -- Akka Mist for continuation-based asynchronous HTTP and also Jersey integration -- ``akka-slf4j-1.1.jar`` -- SLF4J Event Handler Listener -- ``akka-testkit-1.1.jar`` -- Toolkit for testing Actors - -We also have Akka Modules containing add-on modules outside the core of Akka. - -- ``akka-kernel-1.1.jar`` -- Akka microkernel for running a bare-bones mini application server (embeds Jetty etc.) -- ``akka-amqp-1.1.jar`` -- AMQP integration -- ``akka-camel-1.1.jar`` -- Apache Camel Actors integration (it's the best way to have your Akka application communicate with the rest of the world) -- ``akka-camel-typed-1.1.jar`` -- Apache Camel Typed Actors integration -- ``akka-scalaz-1.1.jar`` -- Support for the Scalaz library -- ``akka-spring-1.1.jar`` -- Spring framework integration -- ``akka-osgi-dependencies-bundle-1.1.jar`` -- OSGi support +Akka is very modular and has many JARs for containing different features. +- ``akka-actor-2.0-SNAPSHOT.jar`` -- Standard Actors +- ``akka-typed-actor-2.0-SNAPSHOT.jar`` -- Typed Actors +- ``akka-remote-2.0-SNAPSHOT.jar`` -- Remote Actors +- ``akka-stm-2.0-SNAPSHOT.jar`` -- STM (Software Transactional Memory), transactors and transactional datastructures +- ``akka-http-2.0-SNAPSHOT.jar`` -- Akka Mist for continuation-based asynchronous HTTP and also Jersey integration +- ``akka-slf4j-2.0-SNAPSHOT.jar`` -- SLF4J Event Handler Listener +- ``akka-testkit-2.0-SNAPSHOT.jar`` -- Toolkit for testing Actors +- ``akka-camel-2.0-SNAPSHOT.jar`` -- Apache Camel Actors integration (it's the best way to have your Akka application communicate with the rest of the world) +- ``akka-camel-typed-2.0-SNAPSHOT.jar`` -- Apache Camel Typed Actors integration +- ``akka-spring-2.0-SNAPSHOT.jar`` -- Spring framework integration +- ``akka-kernel-2.0-SNAPSHOT.jar`` -- Akka microkernel for running a bare-bones mini application server (embeds Jetty etc.) How to see the JARs dependencies of each Akka module is described in the :ref:`dependencies` section. Worth noting is that ``akka-actor`` has zero external dependencies (apart from the ``scala-library.jar`` JAR). @@ -82,7 +70,7 @@ The Akka Modules distribution includes the microkernel. To run the microkernel: * Set the AKKA_HOME environment variable to the root of the Akka distribution. * To start the kernel use the scripts in the ``bin`` directory and deploy all samples applications from ``./deploy`` dir. -More information is available in the documentation of the Microkernel in :ref:`add-on-modules`. +More information is available in the documentation of the :ref:`microkernel`. Using a build tool ------------------ @@ -107,14 +95,14 @@ Summary of the essential parts for using Akka with Maven: http://akka.io/repository/ -2) Add the Akka dependencies. For example, here is the dependency for Akka Actor 1.1: +2) Add the Akka dependencies. For example, here is the dependency for Akka Actor 2.0-SNAPSHOT: .. code-block:: xml se.scalablesolutions.akka akka-actor - 1.1 + 2.0-SNAPSHOT @@ -129,7 +117,7 @@ Summary of the essential parts for using Akka with SBT: 1) Akka has an SBT plugin which makes it very easy to get started with Akka and SBT. -The Scala version in your SBT project needs to match the version that Akka is built against. For Akka 1.1 this is +The Scala version in your SBT project needs to match the version that Akka is built against. For Akka 2.0-SNAPSHOT this is Scala version 2.9.0. To use the plugin, first add a plugin definition to your SBT project by creating project/plugins/Plugins.scala with: @@ -140,10 +128,10 @@ To use the plugin, first add a plugin definition to your SBT project by creating class Plugins(info: ProjectInfo) extends PluginDefinition(info) { val akkaRepo = "Akka Repo" at "http://akka.io/repository" - val akkaPlugin = "se.scalablesolutions.akka" % "akka-sbt-plugin" % "1.1" + val akkaPlugin = "se.scalablesolutions.akka" % "akka-sbt-plugin" % "2.0-SNAPSHOT" } -*Note: the plugin version matches the Akka version provided. The current release is 1.1.* +*Note: the plugin version matches the Akka version provided. The current release is 2.0-SNAPSHOT.* 2) Then mix the AkkaProject trait into your project definition. For example: diff --git a/akka-docs/java/dispatchers.rst b/akka-docs/java/dispatchers.rst index b67cb1c02e..7f8998c18e 100644 --- a/akka-docs/java/dispatchers.rst +++ b/akka-docs/java/dispatchers.rst @@ -13,7 +13,7 @@ The Dispatcher is an important piece that allows you to configure the right sema Akka supports dispatchers for both event-driven lightweight threads, allowing creation of millions threads on a single workstation, and thread-based Actors, where each dispatcher is bound to a dedicated OS thread. -The event-based Actors currently consume ~600 bytes per Actor which means that you can create more than 6.5 million Actors on 4 G RAM. +The event-based Actors currently consume ~600 bytes per Actor which means that you can create more than 6.5 million Actors on 4 GB RAM. Default dispatcher ------------------ @@ -84,6 +84,7 @@ The 'Dispatcher' binds a set of Actors to a thread pool backed up by a 'Blocking The event-driven dispatchers **must be shared** between multiple Typed Actors and/or Actors. One best practice is to let each top-level Actor, e.g. the Actors you define in the declarative supervisor config, to get their own dispatcher but reuse the dispatcher for each new Actor that the top-level Actor creates. But you can also share dispatcher between multiple top-level Actors. This is very use-case specific and needs to be tried out on a case by case basis. The important thing is that Akka tries to provide you with the freedom you need to design and implement your system in the most efficient way in regards to performance, throughput and latency. It comes with many different predefined BlockingQueue configurations: + * Bounded LinkedBlockingQueue * Unbounded LinkedBlockingQueue * Bounded ArrayBlockingQueue diff --git a/akka-docs/java/futures.rst b/akka-docs/java/futures.rst index 660dc6bd05..91fc62cd4d 100644 --- a/akka-docs/java/futures.rst +++ b/akka-docs/java/futures.rst @@ -17,11 +17,11 @@ Use with Actors There are generally two ways of getting a reply from an ``UntypedActor``: the first is by a sent message (``actorRef.sendOneWay(msg);``), which only works if the original sender was an ``UntypedActor``) and the second is through a ``Future``. -Using the ``ActorRef``\'s ``sendRequestReplyFuture`` method to send a message will return a Future. To wait for and retrieve the actual result the simplest method is: +Using the ``ActorRef``\'s ``ask`` method to send a message will return a Future. To wait for and retrieve the actual result the simplest method is: .. code-block:: java - Future[Object] future = actorRef.sendRequestReplyFuture[Object](msg); + Future[Object] future = actorRef.ask[Object](msg); Object result = future.get(); //Block until result is available, usually bad practice This will cause the current thread to block and wait for the ``UntypedActor`` to 'complete' the ``Future`` with it's reply. Due to the dynamic nature of Akka's ``UntypedActor``\s this result can be anything. The safest way to deal with this is to specify the result to an ``Object`` as is shown in the above example. You can also use the expected result type instead of ``Any``, but if an unexpected type were to be returned you will get a ``ClassCastException``. For more elegant ways to deal with this and to use the result without blocking, refer to `Functional Futures`_. diff --git a/akka-docs/java/typed-actors.rst b/akka-docs/java/typed-actors.rst index daed909727..2eb02f6ebc 100644 --- a/akka-docs/java/typed-actors.rst +++ b/akka-docs/java/typed-actors.rst @@ -115,6 +115,7 @@ Methods that return something (e.g. non-void methods) are turned into ‘send-an User user = service.getUser(username); Generally it is preferred to use fire-forget messages as much as possible since they will never block, e.g. consume a resource by waiting. But sometimes they are neat to use since they: + # Simulates standard Java method dispatch, which is more intuitive for most Java developers # Are a neat to model request-reply # Are useful when you need to do things in a defined order diff --git a/akka-docs/java/untyped-actors.rst b/akka-docs/java/untyped-actors.rst index ddeedbe829..db698b1a4f 100644 --- a/akka-docs/java/untyped-actors.rst +++ b/akka-docs/java/untyped-actors.rst @@ -109,7 +109,7 @@ Send messages Messages are sent to an Actor through one of the 'send' methods. * 'sendOneWay' means “fire-and-forget”, e.g. send a message asynchronously and return immediately. * 'sendRequestReply' means “send-and-reply-eventually”, e.g. send a message asynchronously and wait for a reply through a Future. Here you can specify a timeout. Using timeouts is very important. If no timeout is specified then the actor’s default timeout (set by the 'getContext().setTimeout(..)' method in the 'ActorRef') is used. This method throws an 'ActorTimeoutException' if the call timed out. -* 'sendRequestReplyFuture' sends a message asynchronously and returns a 'Future'. +* 'ask' sends a message asynchronously and returns a 'Future'. In all these methods you have the option of passing along your 'ActorRef' context variable. Make it a practice of doing so because it will allow the receiver actors to be able to respond to your message, since the sender reference is sent along with the message. @@ -158,11 +158,11 @@ Here are some examples: Send-And-Receive-Future ^^^^^^^^^^^^^^^^^^^^^^^ -Using 'sendRequestReplyFuture' will send a message to the receiving Actor asynchronously and will immediately return a 'Future'. +Using 'ask' will send a message to the receiving Actor asynchronously and will immediately return a 'Future'. .. code-block:: java - Future future = actorRef.sendRequestReplyFuture("Hello", getContext(), 1000); + Future future = actorRef.ask("Hello", getContext(), 1000); The 'Future' interface looks like this: @@ -170,7 +170,6 @@ The 'Future' interface looks like this: interface Future { void await(); - void awaitBlocking(); boolean isCompleted(); boolean isExpired(); long timeoutInNanos(); @@ -183,7 +182,7 @@ So the normal way of working with futures is something like this: .. code-block:: java - Future future = actorRef.sendRequestReplyFuture("Hello", getContext(), 1000); + Future future = actorRef.ask("Hello", getContext(), 1000); future.await(); if (future.isCompleted()) { Option resultOption = future.result(); @@ -306,7 +305,7 @@ On this 'Option' you can invoke 'boolean isDefined()' or 'boolean isEmpty()' to Reply using the sender future ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -If a message was sent with the 'sendRequestReply' or 'sendRequestReplyFuture' methods, which both implements request-reply semantics using Future's, then you either have the option of replying using the 'reply' method as above. This method will then resolve the Future. But you can also get a reference to the Future directly and resolve it yourself or if you would like to store it away to resolve it later, or pass it on to some other Actor to resolve it. +If a message was sent with the 'sendRequestReply' or 'ask' methods, which both implements request-reply semantics using Future's, then you either have the option of replying using the 'reply' method as above. This method will then resolve the Future. But you can also get a reference to the Future directly and resolve it yourself or if you would like to store it away to resolve it later, or pass it on to some other Actor to resolve it. The reference to the Future resides in the 'ActorRef' instance and can be retrieved using 'Option getSenderFuture()'. diff --git a/akka-docs/modules/spring.rst b/akka-docs/modules/spring.rst index 29bf4632cf..d8ec97b72c 100644 --- a/akka-docs/modules/spring.rst +++ b/akka-docs/modules/spring.rst @@ -323,7 +323,7 @@ The Akka configuration can be made available as property placeholders by using a - + Camel configuration diff --git a/akka-docs/project/migration-guide-0.10.x-1.0.x.rst b/akka-docs/project/migration-guide-0.10.x-1.0.x.rst index 5cdbbfd608..fbc951229b 100644 --- a/akka-docs/project/migration-guide-0.10.x-1.0.x.rst +++ b/akka-docs/project/migration-guide-0.10.x-1.0.x.rst @@ -1,4 +1,4 @@ -Migration guide from 0.10.x to 1.0.x +Migration Guide 0.10.x to 1.0.x ==================================== Akka & Akka Modules separated into two different repositories and distributions @@ -15,7 +15,7 @@ Download the release you need (Akka core or Akka Modules) from `.xsd +The Akka-Spring namespace has changed from akkasource.org and scalablesolutions.se to http://akka.io/schema and http://akka.io/akka-.xsd Module akka-actor ----------------- @@ -444,4 +444,4 @@ The Akka XML schema URI has changed to http://akka.io/schema/akka - \ No newline at end of file + diff --git a/akka-docs/project/release-notes.rst b/akka-docs/project/release-notes.rst index c6effb9b19..20553a15a8 100644 --- a/akka-docs/project/release-notes.rst +++ b/akka-docs/project/release-notes.rst @@ -3,7 +3,7 @@ Release Notes Changes listed in no particular order. -Current Development 1.1-SNAPSHOT +1.1 ---------------------------------------- - **UPD** - improve FSM DSL: make onTransition syntax nicer (Roland Kuhn) @@ -524,7 +524,7 @@ Release 0.6 - January 5th 2010 - **ADD** - New and much improved docs (Jonas Bonér) - **ADD** - Enhanced trapping of failures: 'trapExit = List(classOf[..], classOf[..])' (Jonas Bonér) - **ADD** - Upgraded to Netty 3.2, Protobuf 2.2, ScalaTest 1.0, Jersey 1.1.3, Atmosphere 0.4.1, Cassandra 0.4.1, Configgy 1.4 (Jonas Bonér) -- **FIX** - Lowered actor memory footprint; now an actor consumes ~600 bytes, which mean that you can create 6.5 million on 4 G RAM (Jonas Bonér) +- **FIX** - Lowered actor memory footprint; now an actor consumes ~600 bytes, which mean that you can create 6.5 million on 4 GB RAM (Jonas Bonér) - **FIX** - Remote actors are now defined by their UUID (not class name) (Jonas Bonér) - **FIX** - Fixed dispatcher bugs (Jonas Bonér) - **FIX** - Cleaned up Maven scripts and distribution in general (Jonas Bonér) diff --git a/akka-docs/scala/actors.rst b/akka-docs/scala/actors.rst index 38076d7b58..2d0f105e0e 100644 --- a/akka-docs/scala/actors.rst +++ b/akka-docs/scala/actors.rst @@ -126,7 +126,7 @@ Messages are sent to an Actor through one of the “bang” methods. * ! means “fire-and-forget”, e.g. send a message asynchronously and return immediately. * !! means “send-and-reply-eventually”, e.g. send a message asynchronously and wait for a reply through aFuture. Here you can specify a timeout. Using timeouts is very important. If no timeout is specified then the actor’s default timeout (set by the this.timeout variable in the actor) is used. This method returns an ``Option[Any]`` which will be either ``Some(result)`` if returning successfully or None if the call timed out. -* !!! sends a message asynchronously and returns a ``Future``. +* ? sends a message asynchronously and returns a ``Future``. You can check if an Actor can handle a specific message by invoking the ``isDefinedAt`` method: @@ -180,11 +180,11 @@ Here are some examples: Send-And-Receive-Future ^^^^^^^^^^^^^^^^^^^^^^^ -Using ``!!!`` will send a message to the receiving Actor asynchronously and will return a 'Future': +Using ``?`` will send a message to the receiving Actor asynchronously and will return a 'Future': .. code-block:: scala - val future = actor !!! "Hello" + val future = actor ? "Hello" See :ref:`futures-scala` for more information. @@ -329,7 +329,7 @@ The same pattern holds for using the ``senderFuture`` in the section below. Reply using the sender future ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -If a message was sent with the ``!!`` or ``!!!`` methods, which both implements request-reply semantics using Future's, then you either have the option of replying using the ``reply`` method as above. This method will then resolve the Future. But you can also get a reference to the Future directly and resolve it yourself or if you would like to store it away to resolve it later, or pass it on to some other Actor to resolve it. +If a message was sent with the ``!!`` or ``?`` methods, which both implements request-reply semantics using Future's, then you either have the option of replying using the ``reply`` method as above. This method will then resolve the Future. But you can also get a reference to the Future directly and resolve it yourself or if you would like to store it away to resolve it later, or pass it on to some other Actor to resolve it. The reference to the Future resides in the ``senderFuture: Option[Promise[_]]`` member field in the ``ActorRef`` class. @@ -427,7 +427,7 @@ PoisonPill You can also send an actor the ``akka.actor.PoisonPill`` message, which will stop the actor when the message is processed. -If the sender is a ``Future`` (e.g. the message is sent with ``!!`` or ``!!!``), the ``Future`` will be completed with an ``akka.actor.ActorKilledException("PoisonPill")``. +If the sender is a ``Future`` (e.g. the message is sent with ``!!`` or ``?``), the ``Future`` will be completed with an ``akka.actor.ActorKilledException("PoisonPill")``. HotSwap ------- @@ -457,7 +457,7 @@ To hotswap the Actor using ``become``: .. code-block:: scala def angry: Receive = { - case "foo" => self reply "I am already angry!!!" + case "foo" => self reply "I am already angry?" case "bar" => become(happy) } diff --git a/akka-docs/scala/dispatchers.rst b/akka-docs/scala/dispatchers.rst index cc75b5c099..afc7d204ec 100644 --- a/akka-docs/scala/dispatchers.rst +++ b/akka-docs/scala/dispatchers.rst @@ -13,7 +13,7 @@ The Dispatcher is an important piece that allows you to configure the right sema Akka supports dispatchers for both event-driven lightweight threads, allowing creation of millions of threads on a single workstation, and thread-based Actors, where each dispatcher is bound to a dedicated OS thread. -The event-based Actors currently consume ~600 bytes per Actor which means that you can create more than 6.5 million Actors on 4 G RAM. +The event-based Actors currently consume ~600 bytes per Actor which means that you can create more than 6.5 million Actors on 4 GB RAM. Default dispatcher ------------------ diff --git a/akka-docs/scala/futures.rst b/akka-docs/scala/futures.rst index f64c864564..a9955d9a50 100644 --- a/akka-docs/scala/futures.rst +++ b/akka-docs/scala/futures.rst @@ -17,11 +17,11 @@ Use with Actors There are generally two ways of getting a reply from an ``Actor``: the first is by a sent message (``actor ! msg``), which only works if the original sender was an ``Actor``) and the second is through a ``Future``. -Using an ``Actor``\'s ``!!!`` method to send a message will return a Future. To wait for and retrieve the actual result the simplest method is: +Using an ``Actor``\'s ``?`` method to send a message will return a Future. To wait for and retrieve the actual result the simplest method is: .. code-block:: scala - val future = actor !!! msg + val future = actor ? msg val result: Any = future.get() This will cause the current thread to block and wait for the ``Actor`` to 'complete' the ``Future`` with it's reply. Due to the dynamic nature of Akka's ``Actor``\s this result will be untyped and will default to ``Nothing``. The safest way to deal with this is to cast the result to an ``Any`` as is shown in the above example. You can also use the expected result type instead of ``Any``, but if an unexpected type were to be returned you will get a ``ClassCastException``. For more elegant ways to deal with this and to use the result without blocking, refer to `Functional Futures`_. @@ -141,13 +141,13 @@ The example for comprehension above is an example of composing ``Future``\s. A c .. code-block:: scala - val f1 = actor1 !!! msg1 - val f2 = actor2 !!! msg2 + val f1 = actor1 ? msg1 + val f2 = actor2 ? msg2 val a: Int = f1.get() val b: Int = f2.get() - val f3 = actor3 !!! (a + b) + val f3 = actor3 ? (a + b) val result: String = f3.get() @@ -155,13 +155,13 @@ Here we wait for the results from the first 2 ``Actor``\s before sending that re .. code-block:: scala - val f1 = actor1 !!! msg1 - val f2 = actor2 !!! msg2 + val f1 = actor1 ? msg1 + val f2 = actor2 ? msg2 val f3 = for { a: Int <- f1 b: Int <- f2 - c: String <- actor3 !!! (a + b) + c: String <- actor3 ? (a + b) } yield c val result = f3.get() @@ -173,7 +173,7 @@ This is fine when dealing with a known amount of Actors, but can grow unwieldy i .. code-block:: scala // oddActor returns odd numbers sequentially from 1 - val listOfFutures: List[Future[Int]] = List.fill(100)(oddActor !!! GetNext) + val listOfFutures: List[Future[Int]] = List.fill(100)(oddActor ? GetNext) // now we have a Future[List[Int]] val futureList = Future.sequence(listOfFutures) @@ -223,22 +223,27 @@ Same as with ``fold``, the execution will be done by the Thread that completes t This is just a sample of what can be done, but to use more advanced techniques it is easier to take advantage of Scalaz, which Akka has support for in its akka-scalaz module. + Scalaz ^^^^^^ -Akka also has a Scalaz module (:ref:`add-on-modules`) for a more complete support of programming in a functional style. +There is also an `Akka-Scalaz`_ project created by Derek Williams for a more +complete support of programming in a functional style. + +.. _Akka-Scalaz: https://github.com/derekjw/akka-scalaz + Exceptions ---------- Since the result of a ``Future`` is created concurrently to the rest of the program, exceptions must be handled differently. It doesn't matter if an ``Actor`` or the dispatcher is completing the ``Future``, if an ``Exception`` is caught the ``Future`` will contain it instead of a valid result. If a ``Future`` does contain an ``Exception``, calling ``get`` will cause it to be thrown again so it can be handled properly. -It is also possible to handle an ``Exception`` by returning a different result. This is done with the ``failure`` method. For example: +It is also possible to handle an ``Exception`` by returning a different result. This is done with the ``recover`` method. For example: .. code-block:: scala - val future = actor !!! msg1 failure { + val future = actor ? msg1 recover { case e: ArithmeticException => 0 } -In this example, if an ``ArithmeticException`` was thrown while the ``Actor`` processed the message, our ``Future`` would have a result of 0. The ``failure`` method works very similarly to the standard try/catch blocks, so multiple ``Exception``\s can be handled in this manner, and if an ``Exception`` is not handled this way it will be behave as if we hadn't used the ``failure`` method. +In this example, if an ``ArithmeticException`` was thrown while the ``Actor`` processed the message, our ``Future`` would have a result of 0. The ``recover`` method works very similarly to the standard try/catch blocks, so multiple ``Exception``\s can be handled in this manner, and if an ``Exception`` is not handled this way it will be behave as if we hadn't used the ``recover`` method. diff --git a/akka-docs/scala/http.rst b/akka-docs/scala/http.rst index 9f15664b70..ba25234f93 100644 --- a/akka-docs/scala/http.rst +++ b/akka-docs/scala/http.rst @@ -10,43 +10,10 @@ HTTP Module stability: **SOLID** -When using Akkas embedded servlet container -------------------------------------------- - -Akka supports the JSR for REST called JAX-RS (JSR-311). It allows you to create interaction with your actors through HTTP + REST - -You can deploy your REST services directly into the Akka kernel. All you have to do is to drop the JAR with your application containing the REST services into the ‘$AKKA_HOME/deploy’ directory and specify in your akka.conf what resource packages to scan for (more on that below) and optionally define a “boot class” (if you need to create any actors or do any config). WAR deployment is coming soon. - -Boot configuration class ------------------------- - -The boot class is needed for Akka to bootstrap the application and should contain the initial supervisor configuration of any actors in the module. - -The boot class should be a regular POJO with a default constructor in which the initial configuration is done. The boot class then needs to be defined in the ‘$AKKA_HOME/config/akka.conf’ config file like this: - -.. code-block:: ruby - - akka { - boot = ["sample.java.Boot", "sample.scala.Boot"] # FQN to the class doing initial actor - # supervisor bootstrap, should be defined in default constructor - ... - } - -After you've placed your service-jar into the $AKKA_HOME/deploy directory, you'll need to tell Akka where to look for your services, and you do that by specifying what packages you want Akka to scan for services, and that's done in akka.conf in the http-section: - -.. code-block:: ruby - - akka { - http { - ... - resource-packages = ["com.bar","com.foo.bar"] # List with all resource packages for your Jersey services - ... - } - -When deploying in another servlet container: +When deploying in a servlet container: -------------------------------------------- -If you deploy Akka in another JEE container, don't forget to create an Akka initialization and cleanup hook: +If you deploy Akka in a JEE container, don't forget to create an Akka initialization and cleanup hook: .. code-block:: scala @@ -86,32 +53,6 @@ Then you just declare it in your web.xml: ... -Also, you need to map the servlet that will handle your Jersey/JAX-RS calls, you use Jerseys ServletContainer servlet. - -.. code-block:: xml - - - ... - - Akka - com.sun.jersey.spi.container.servlet.ServletContainer - - - com.sun.jersey.config.property.resourceConfigClass - com.sun.jersey.api.core.PackagesResourceConfig - - - com.sun.jersey.config.property.packages - your.resource.package.here;and.another.here;and.so.on - - - - * - Akka - - ... - - Adapting your own Akka Initializer for the Servlet Container ------------------------------------------------------------ @@ -142,16 +83,6 @@ If you want to use akka-camel or any other modules that have their own "Bootable loader.boot(true, new BootableActorLoaderService with BootableRemoteActorService with CamelService) //<--- Important } -Java API: Typed Actors ----------------------- - -`Sample module for REST services with Actors in Java `_ - -Scala API: Actors ------------------ - -`Sample module for REST services with Actors in Scala `_ - Using Akka with the Pinky REST/MVC framework -------------------------------------------- @@ -193,6 +124,10 @@ In order to use Mist you have to register the MistServlet in *web.xml* or do the akkaMistServlet akka.http.AkkaMistServlet + + root-endpoint + address_of_root_endpoint_actor + diff --git a/akka-docs/scala/security.rst b/akka-docs/scala/security.rst deleted file mode 100644 index 9d186b5ea2..0000000000 --- a/akka-docs/scala/security.rst +++ /dev/null @@ -1,266 +0,0 @@ -HTTP Security -============= - -.. sidebar:: Contents - - .. contents:: :local: - -Module stability: **IN PROGRESS** - -Akka supports security for access to RESTful Actors through `HTTP Authentication `_. The security is implemented as a jersey ResourceFilter which delegates the actual authentication to an authentication actor. - -Akka provides authentication via the following authentication schemes: - -* `Basic Authentication `_ -* `Digest Authentication `_ -* `Kerberos SPNEGO Authentication `_ - -The authentication is performed by implementations of akka.security.AuthenticationActor. - -Akka provides a trait for each authentication scheme: - -* BasicAuthenticationActor -* DigestAuthenticationActor -* SpnegoAuthenticationActor - - -Setup ------ - -To secure your RESTful actors you need to perform the following steps: - -1. configure the resource filter factory 'akka.security.AkkaSecurityFilterFactory' in the 'akka.conf' like this: - -.. code-block:: ruby - - akka { - ... - rest { - filters="akka.security.AkkaSecurityFilterFactory" - } - ... - } - -2. Configure an implementation of an authentication actor in 'akka.conf': - -.. code-block:: ruby - - akka { - ... - rest { - filters= ... - authenticator = "akka.security.samples.BasicAuthenticationService" - } - ... - } - -3. Start your authentication actor in your 'Boot' class. The security package consists of the following parts: - -4. Secure your RESTful actors using class or resource level annotations: - -* @DenyAll -* @RolesAllowed(listOfRoles) -* @PermitAll - -Security Samples ----------------- - -The akka-samples-security module contains a small sample application with sample implementations for each authentication scheme. -You can start the sample app using the jetty plugin: mvn jetty:run. - -The RESTful actor can then be accessed using your browser of choice under: - -* permit access only to users having the “chef” role: ``_ -* public access: ``_ - -You can access the secured resource using any user for basic authentication (which is the default authenticator in the sample app). - -Digest authentication can be directly enabled in the sample app. Kerberos/SPNEGO authentication is a bit more involved an is described below. - - -Kerberos/SPNEGO Authentication ------------------------------- - -Kerberos is a network authentication protocol, (see ``_). It provides strong authentication for client/server applications. -In a kerberos enabled environment a user will need to sign on only once. Subsequent authentication to applications is handled transparently by kerberos. - -Most prominently the kerberos protocol is used to authenticate users in a windows network. When deploying web applications to a corporate intranet an important feature will be to support the single sign on (SSO), which comes to make the application kerberos aware. - -How does it work (at least for REST actors)? - -- When accessing a secured resource the server will check the request for the *Authorization* header as with basic or digest authentication. -- If it is not set, the server will respond with a challenge to "Negotiate". The negotiation is in fact the NEGO part of the `SPNEGO `_ specification -- The browser will then try to acquire a so called *service ticket* from a ticket granting service, i.e. the kerberos server -- The browser will send the *service ticket* to the web application encoded in the header value of the *Authorization* header -- The web application must validate the ticket based on a shared secret between the web application and the kerberos server. As a result the web application will know the name of the user - -To activate the kerberos/SPNEGO authentication for your REST actor you need to enable the kerberos/SPNEGOauthentication actor in the akka.conf like this: - -.. code-block:: ruby - - akka { - ... - rest { - filters= ... - authenticator = "akka.security.samples.SpnegoAuthenticationService" - } - ... - } - -Furthermore you must provide the SpnegoAuthenticator with the following information. - -- Service principal name: the name of your web application in the kerberos servers user database. This name is always has the form ``HTTP/{server}@{realm}`` -- Path to the keytab file: this is a kind of certificate for your web application to acquire tickets from the kerberos server - -.. code-block:: ruby - - akka { - ... - rest { - filters= ... - authenticator = "akka.security.samples.SpnegoAuthenticationService" - kerberos { - servicePrincipal = "HTTP/{server}@{realm}" - keyTabLocation = "URL to keytab" - # kerberosDebug = "true" - } - } - ... - } - - -How to setup kerberos on localhost for Ubuntu ---------------------------------------------- - -This is a short step by step description of howto set up a kerberos server on an ubuntu system. - -1. Install the Heimdal Kerberos Server and Client - -:: - - sudo apt-get install heimdal-clients heimdal-clients-x heimdal-kdc krb5-config - ... - -2. Set up your kerberos realm. In this example the realm is of course … EXAMPLE.COM - -:: - - eckart@dilbert:~$ sudo kadmin -l - kadmin> init EXAMPLE.COM - Realm max ticket life [unlimited]: - Realm max renewable ticket life [unlimited]: - kadmin> quit - -3. Tell your kerberos clients what your realm is and where to find the kerberos server (aka the Key Distribution Centre or KDC) - -Edit the kerberos config file: /etc/krb5.conf and configure … -…the default realm: - -:: - - [libdefaults] - default_realm = EXAMPLE.COM - -… where to find the KDC for your realm - -:: - - [realms] - EXAMPLE.COM = { - kdc = localhost - } - -…which hostnames or domains map to which realm (a kerberos realm is **not** a DNS domain): - -:: - - [domain_realm] - localhost = EXAMPLE.COM - -4. Add the principals -The user principal: - -:: - - eckart@dilbert:~$ sudo kadmin -l - kadmin> add zaphod - Max ticket life [1 day]: - Max renewable life [1 week]: - Principal expiration time [never]: - Password expiration time [never]: - Attributes []: - zaphod@EXAMPLE.COM's Password: - Verifying - zaphod@EXAMPLE.COM's Password: - kadmin> quit - -The service principal: - -:: - - eckart@dilbert:~$ sudo kadmin -l - kadmin> add HTTP/localhost@EXAMPLE.COM - Max ticket life [1 day]: - Max renewable life [1 week]: - Principal expiration time [never]: - Password expiration time [never]: - Attributes []: - HTTP/localhost@EXAMPLE.COM's Password: - Verifying - HTTP/localhost@EXAMPLE.COM's Password: - kadmin> quit - -We can now try to acquire initial tickets for the principals to see if everything worked. - -:: - - eckart@dilbert:~$ kinit zaphod - zaphod@EXAMPLE.COM's Password: - -If this method returns withour error we have a success. -We can additionally list the acquired tickets: - -:: - - eckart@dilbert:~$ klist - Credentials cache: FILE:/tmp/krb5cc_1000 - Principal: zaphod@EXAMPLE.COM - - Issued Expires Principal - Oct 24 21:51:59 Oct 25 06:51:59 krbtgt/EXAMPLE.COM@EXAMPLE.COM - -This seems correct. To remove the ticket cache simply type kdestroy. - -5. Create a keytab for your service principal - -:: - - eckart@dilbert:~$ ktutil -k http.keytab add -p HTTP/localhost@EXAMPLE.COM -V 1 -e aes256-cts-hmac-sha1-96 - Password: - Verifying - Password: - eckart@dilbert:~$ - -This command will create a keytab file for the service principal named ``http.keytab`` in the current directory. You can specify other encryption methods than ‘aes256-cts-hmac-sha1-96’, but this is the e default encryption method for the heimdal client, so there is no additional configuration needed. You can specify other encryption types in the krb5.conf. - -Note that you might need to install the unlimited strength policy files for java from here: ``_ to use the aes256 encryption from your application. - -Again we can test if the keytab generation worked with the kinit command: - -:: - - eckart@dilbert:~$ kinit -t http.keytab HTTP/localhost@EXAMPLE.COM - eckart@dilbert:~$ klist - Credentials cache: FILE:/tmp/krb5cc_1000 - Principal: HTTP/localhost@EXAMPLE.COM - - Issued Expires Principal - Oct 24 21:59:20 Oct 25 06:59:20 krbtgt/EXAMPLE.COM@EXAMPLE.COM - -Now point the configuration of the key in 'akka.conf' to the correct location and set the correct service principal name. The web application should now startup and produce at least a 401 response with a header ``WWW-Authenticate`` = "Negotiate". The last step is to configure the browser. - -6. Set up Firefox to use Kerberos/SPNEGO -This is done by typing ``about:config``. Filter the config entries for ``network.neg`` and set the config entries ``network.negotiate-auth.delegation-uris`` and ``network.negotiate-auth.trusted-uris`` to ``localhost``. -and now … - -7. Access the RESTful Actor. - -8. Have fun -… but acquire an initial ticket for the user principal first: ``kinit zaphod`` diff --git a/akka-docs/scala/tutorial-chat-server.rst b/akka-docs/scala/tutorial-chat-server.rst index 78a93157a8..1319ee9432 100644 --- a/akka-docs/scala/tutorial-chat-server.rst +++ b/akka-docs/scala/tutorial-chat-server.rst @@ -72,7 +72,7 @@ The 'actorOf' factory method can be imported like this: From now on we will assume that it is imported like this and can use it directly. -Akka Actors are extremely lightweight. Each Actor consume ~600 bytes, which means that you can create 6.5 million on 4 G RAM. +Akka Actors are extremely lightweight. Each Actor consume ~600 bytes, which means that you can create 6.5 million on 4 GB RAM. Messages are sent using the '!' operator: @@ -106,7 +106,7 @@ Add the Akka SBT plugin definition to your SBT project by creating a ``Plugins.s class Plugins(info: ProjectInfo) extends PluginDefinition(info) { val akkaRepo = "Akka Repo" at "http://akka.io/repository" - val akkaPlugin = "se.scalablesolutions.akka" % "akka-sbt-plugin" % "1.1-M1" + val akkaPlugin = "se.scalablesolutions.akka" % "akka-sbt-plugin" % "2.0-SNAPSHOT" } Create a project definition ``project/build/Project.scala`` file containing:: diff --git a/akka-durable-mailboxes/akka-mailboxes-common/src/main/java/akka/actor/mailbox/MailboxProtocol.java b/akka-durable-mailboxes/akka-mailboxes-common/src/main/java/akka/actor/mailbox/MailboxProtocol.java index 1fcb87781c..94c8cfde3e 100644 --- a/akka-durable-mailboxes/akka-mailboxes-common/src/main/java/akka/actor/mailbox/MailboxProtocol.java +++ b/akka-durable-mailboxes/akka-mailboxes-common/src/main/java/akka/actor/mailbox/MailboxProtocol.java @@ -8,11 +8,32 @@ public final class MailboxProtocol { public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } + public interface DurableMailboxMessageProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required string ownerAddress = 1; + boolean hasOwnerAddress(); + String getOwnerAddress(); + + // optional string senderAddress = 2; + boolean hasSenderAddress(); + String getSenderAddress(); + + // optional .UuidProtocol futureUuid = 3; + boolean hasFutureUuid(); + akka.actor.mailbox.MailboxProtocol.UuidProtocol getFutureUuid(); + akka.actor.mailbox.MailboxProtocol.UuidProtocolOrBuilder getFutureUuidOrBuilder(); + + // required bytes message = 4; + boolean hasMessage(); + com.google.protobuf.ByteString getMessage(); + } public static final class DurableMailboxMessageProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements DurableMailboxMessageProtocolOrBuilder { // Use DurableMailboxMessageProtocol.newBuilder() to construct. - private DurableMailboxMessageProtocol() { - initFields(); + private DurableMailboxMessageProtocol(Builder builder) { + super(builder); } private DurableMailboxMessageProtocol(boolean noInit) {} @@ -35,60 +56,137 @@ public final class MailboxProtocol { return akka.actor.mailbox.MailboxProtocol.internal_static_DurableMailboxMessageProtocol_fieldAccessorTable; } + private int bitField0_; // required string ownerAddress = 1; public static final int OWNERADDRESS_FIELD_NUMBER = 1; - private boolean hasOwnerAddress; - private java.lang.String ownerAddress_ = ""; - public boolean hasOwnerAddress() { return hasOwnerAddress; } - public java.lang.String getOwnerAddress() { return ownerAddress_; } + private java.lang.Object ownerAddress_; + public boolean hasOwnerAddress() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public String getOwnerAddress() { + java.lang.Object ref = ownerAddress_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + ownerAddress_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getOwnerAddressBytes() { + java.lang.Object ref = ownerAddress_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + ownerAddress_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } // optional string senderAddress = 2; public static final int SENDERADDRESS_FIELD_NUMBER = 2; - private boolean hasSenderAddress; - private java.lang.String senderAddress_ = ""; - public boolean hasSenderAddress() { return hasSenderAddress; } - public java.lang.String getSenderAddress() { return senderAddress_; } + private java.lang.Object senderAddress_; + public boolean hasSenderAddress() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public String getSenderAddress() { + java.lang.Object ref = senderAddress_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + senderAddress_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getSenderAddressBytes() { + java.lang.Object ref = senderAddress_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + senderAddress_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } // optional .UuidProtocol futureUuid = 3; public static final int FUTUREUUID_FIELD_NUMBER = 3; - private boolean hasFutureUuid; private akka.actor.mailbox.MailboxProtocol.UuidProtocol futureUuid_; - public boolean hasFutureUuid() { return hasFutureUuid; } - public akka.actor.mailbox.MailboxProtocol.UuidProtocol getFutureUuid() { return futureUuid_; } + public boolean hasFutureUuid() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public akka.actor.mailbox.MailboxProtocol.UuidProtocol getFutureUuid() { + return futureUuid_; + } + public akka.actor.mailbox.MailboxProtocol.UuidProtocolOrBuilder getFutureUuidOrBuilder() { + return futureUuid_; + } // required bytes message = 4; public static final int MESSAGE_FIELD_NUMBER = 4; - private boolean hasMessage; - private com.google.protobuf.ByteString message_ = com.google.protobuf.ByteString.EMPTY; - public boolean hasMessage() { return hasMessage; } - public com.google.protobuf.ByteString getMessage() { return message_; } + private com.google.protobuf.ByteString message_; + public boolean hasMessage() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public com.google.protobuf.ByteString getMessage() { + return message_; + } private void initFields() { + ownerAddress_ = ""; + senderAddress_ = ""; futureUuid_ = akka.actor.mailbox.MailboxProtocol.UuidProtocol.getDefaultInstance(); + message_ = com.google.protobuf.ByteString.EMPTY; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasOwnerAddress) return false; - if (!hasMessage) return false; - if (hasFutureUuid()) { - if (!getFutureUuid().isInitialized()) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasOwnerAddress()) { + memoizedIsInitialized = 0; + return false; } + if (!hasMessage()) { + memoizedIsInitialized = 0; + return false; + } + if (hasFutureUuid()) { + if (!getFutureUuid().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasOwnerAddress()) { - output.writeString(1, getOwnerAddress()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeBytes(1, getOwnerAddressBytes()); } - if (hasSenderAddress()) { - output.writeString(2, getSenderAddress()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, getSenderAddressBytes()); } - if (hasFutureUuid()) { - output.writeMessage(3, getFutureUuid()); + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeMessage(3, futureUuid_); } - if (hasMessage()) { - output.writeBytes(4, getMessage()); + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeBytes(4, message_); } getUnknownFields().writeTo(output); } @@ -99,27 +197,34 @@ public final class MailboxProtocol { if (size != -1) return size; size = 0; - if (hasOwnerAddress()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(1, getOwnerAddress()); + .computeBytesSize(1, getOwnerAddressBytes()); } - if (hasSenderAddress()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(2, getSenderAddress()); + .computeBytesSize(2, getSenderAddressBytes()); } - if (hasFutureUuid()) { + if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(3, getFutureUuid()); + .computeMessageSize(3, futureUuid_); } - if (hasMessage()) { + if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream - .computeBytesSize(4, getMessage()); + .computeBytesSize(4, message_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -194,34 +299,62 @@ public final class MailboxProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol result; - - // Construct using akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.actor.mailbox.MailboxProtocol.internal_static_DurableMailboxMessageProtocol_descriptor; } - protected akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.actor.mailbox.MailboxProtocol.internal_static_DurableMailboxMessageProtocol_fieldAccessorTable; + } + + // Construct using akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getFutureUuidFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); + super.clear(); + ownerAddress_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + senderAddress_ = ""; + bitField0_ = (bitField0_ & ~0x00000002); + if (futureUuidBuilder_ == null) { + futureUuid_ = akka.actor.mailbox.MailboxProtocol.UuidProtocol.getDefaultInstance(); + } else { + futureUuidBuilder_.clear(); } - result = new akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol(); + bitField0_ = (bitField0_ & ~0x00000004); + message_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000008); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -233,33 +366,51 @@ public final class MailboxProtocol { return akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol build() { - if (result != null && !isInitialized()) { + akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol result = new akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.actor.mailbox.MailboxProtocol.DurableMailboxMessageProtocol returnMe = result; - result = null; - return returnMe; + result.ownerAddress_ = ownerAddress_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.senderAddress_ = senderAddress_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + if (futureUuidBuilder_ == null) { + result.futureUuid_ = futureUuid_; + } else { + result.futureUuid_ = futureUuidBuilder_.build(); + } + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + result.message_ = message_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -289,6 +440,24 @@ public final class MailboxProtocol { return this; } + public final boolean isInitialized() { + if (!hasOwnerAddress()) { + + return false; + } + if (!hasMessage()) { + + return false; + } + if (hasFutureUuid()) { + if (!getFutureUuid().isInitialized()) { + + return false; + } + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -301,21 +470,25 @@ public final class MailboxProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; } case 10: { - setOwnerAddress(input.readString()); + bitField0_ |= 0x00000001; + ownerAddress_ = input.readBytes(); break; } case 18: { - setSenderAddress(input.readString()); + bitField0_ |= 0x00000002; + senderAddress_ = input.readBytes(); break; } case 26: { @@ -328,111 +501,199 @@ public final class MailboxProtocol { break; } case 34: { - setMessage(input.readBytes()); + bitField0_ |= 0x00000008; + message_ = input.readBytes(); break; } } } } + private int bitField0_; // required string ownerAddress = 1; + private java.lang.Object ownerAddress_ = ""; public boolean hasOwnerAddress() { - return result.hasOwnerAddress(); + return ((bitField0_ & 0x00000001) == 0x00000001); } - public java.lang.String getOwnerAddress() { - return result.getOwnerAddress(); + public String getOwnerAddress() { + java.lang.Object ref = ownerAddress_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + ownerAddress_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setOwnerAddress(java.lang.String value) { + public Builder setOwnerAddress(String value) { if (value == null) { throw new NullPointerException(); } - result.hasOwnerAddress = true; - result.ownerAddress_ = value; + bitField0_ |= 0x00000001; + ownerAddress_ = value; + onChanged(); return this; } public Builder clearOwnerAddress() { - result.hasOwnerAddress = false; - result.ownerAddress_ = getDefaultInstance().getOwnerAddress(); + bitField0_ = (bitField0_ & ~0x00000001); + ownerAddress_ = getDefaultInstance().getOwnerAddress(); + onChanged(); return this; } + void setOwnerAddress(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000001; + ownerAddress_ = value; + onChanged(); + } // optional string senderAddress = 2; + private java.lang.Object senderAddress_ = ""; public boolean hasSenderAddress() { - return result.hasSenderAddress(); + return ((bitField0_ & 0x00000002) == 0x00000002); } - public java.lang.String getSenderAddress() { - return result.getSenderAddress(); + public String getSenderAddress() { + java.lang.Object ref = senderAddress_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + senderAddress_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setSenderAddress(java.lang.String value) { + public Builder setSenderAddress(String value) { if (value == null) { throw new NullPointerException(); } - result.hasSenderAddress = true; - result.senderAddress_ = value; + bitField0_ |= 0x00000002; + senderAddress_ = value; + onChanged(); return this; } public Builder clearSenderAddress() { - result.hasSenderAddress = false; - result.senderAddress_ = getDefaultInstance().getSenderAddress(); + bitField0_ = (bitField0_ & ~0x00000002); + senderAddress_ = getDefaultInstance().getSenderAddress(); + onChanged(); return this; } + void setSenderAddress(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000002; + senderAddress_ = value; + onChanged(); + } // optional .UuidProtocol futureUuid = 3; + private akka.actor.mailbox.MailboxProtocol.UuidProtocol futureUuid_ = akka.actor.mailbox.MailboxProtocol.UuidProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.actor.mailbox.MailboxProtocol.UuidProtocol, akka.actor.mailbox.MailboxProtocol.UuidProtocol.Builder, akka.actor.mailbox.MailboxProtocol.UuidProtocolOrBuilder> futureUuidBuilder_; public boolean hasFutureUuid() { - return result.hasFutureUuid(); + return ((bitField0_ & 0x00000004) == 0x00000004); } public akka.actor.mailbox.MailboxProtocol.UuidProtocol getFutureUuid() { - return result.getFutureUuid(); + if (futureUuidBuilder_ == null) { + return futureUuid_; + } else { + return futureUuidBuilder_.getMessage(); + } } public Builder setFutureUuid(akka.actor.mailbox.MailboxProtocol.UuidProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (futureUuidBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + futureUuid_ = value; + onChanged(); + } else { + futureUuidBuilder_.setMessage(value); } - result.hasFutureUuid = true; - result.futureUuid_ = value; + bitField0_ |= 0x00000004; return this; } - public Builder setFutureUuid(akka.actor.mailbox.MailboxProtocol.UuidProtocol.Builder builderForValue) { - result.hasFutureUuid = true; - result.futureUuid_ = builderForValue.build(); + public Builder setFutureUuid( + akka.actor.mailbox.MailboxProtocol.UuidProtocol.Builder builderForValue) { + if (futureUuidBuilder_ == null) { + futureUuid_ = builderForValue.build(); + onChanged(); + } else { + futureUuidBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000004; return this; } public Builder mergeFutureUuid(akka.actor.mailbox.MailboxProtocol.UuidProtocol value) { - if (result.hasFutureUuid() && - result.futureUuid_ != akka.actor.mailbox.MailboxProtocol.UuidProtocol.getDefaultInstance()) { - result.futureUuid_ = - akka.actor.mailbox.MailboxProtocol.UuidProtocol.newBuilder(result.futureUuid_).mergeFrom(value).buildPartial(); + if (futureUuidBuilder_ == null) { + if (((bitField0_ & 0x00000004) == 0x00000004) && + futureUuid_ != akka.actor.mailbox.MailboxProtocol.UuidProtocol.getDefaultInstance()) { + futureUuid_ = + akka.actor.mailbox.MailboxProtocol.UuidProtocol.newBuilder(futureUuid_).mergeFrom(value).buildPartial(); + } else { + futureUuid_ = value; + } + onChanged(); } else { - result.futureUuid_ = value; + futureUuidBuilder_.mergeFrom(value); } - result.hasFutureUuid = true; + bitField0_ |= 0x00000004; return this; } public Builder clearFutureUuid() { - result.hasFutureUuid = false; - result.futureUuid_ = akka.actor.mailbox.MailboxProtocol.UuidProtocol.getDefaultInstance(); + if (futureUuidBuilder_ == null) { + futureUuid_ = akka.actor.mailbox.MailboxProtocol.UuidProtocol.getDefaultInstance(); + onChanged(); + } else { + futureUuidBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); return this; } + public akka.actor.mailbox.MailboxProtocol.UuidProtocol.Builder getFutureUuidBuilder() { + bitField0_ |= 0x00000004; + onChanged(); + return getFutureUuidFieldBuilder().getBuilder(); + } + public akka.actor.mailbox.MailboxProtocol.UuidProtocolOrBuilder getFutureUuidOrBuilder() { + if (futureUuidBuilder_ != null) { + return futureUuidBuilder_.getMessageOrBuilder(); + } else { + return futureUuid_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.actor.mailbox.MailboxProtocol.UuidProtocol, akka.actor.mailbox.MailboxProtocol.UuidProtocol.Builder, akka.actor.mailbox.MailboxProtocol.UuidProtocolOrBuilder> + getFutureUuidFieldBuilder() { + if (futureUuidBuilder_ == null) { + futureUuidBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.actor.mailbox.MailboxProtocol.UuidProtocol, akka.actor.mailbox.MailboxProtocol.UuidProtocol.Builder, akka.actor.mailbox.MailboxProtocol.UuidProtocolOrBuilder>( + futureUuid_, + getParentForChildren(), + isClean()); + futureUuid_ = null; + } + return futureUuidBuilder_; + } // required bytes message = 4; + private com.google.protobuf.ByteString message_ = com.google.protobuf.ByteString.EMPTY; public boolean hasMessage() { - return result.hasMessage(); + return ((bitField0_ & 0x00000008) == 0x00000008); } public com.google.protobuf.ByteString getMessage() { - return result.getMessage(); + return message_; } public Builder setMessage(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } - result.hasMessage = true; - result.message_ = value; + bitField0_ |= 0x00000008; + message_ = value; + onChanged(); return this; } public Builder clearMessage() { - result.hasMessage = false; - result.message_ = getDefaultInstance().getMessage(); + bitField0_ = (bitField0_ & ~0x00000008); + message_ = getDefaultInstance().getMessage(); + onChanged(); return this; } @@ -441,18 +702,29 @@ public final class MailboxProtocol { static { defaultInstance = new DurableMailboxMessageProtocol(true); - akka.actor.mailbox.MailboxProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:DurableMailboxMessageProtocol) } + public interface UuidProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required uint64 high = 1; + boolean hasHigh(); + long getHigh(); + + // required uint64 low = 2; + boolean hasLow(); + long getLow(); + } public static final class UuidProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements UuidProtocolOrBuilder { // Use UuidProtocol.newBuilder() to construct. - private UuidProtocol() { - initFields(); + private UuidProtocol(Builder builder) { + super(builder); } private UuidProtocol(boolean noInit) {} @@ -475,36 +747,56 @@ public final class MailboxProtocol { return akka.actor.mailbox.MailboxProtocol.internal_static_UuidProtocol_fieldAccessorTable; } + private int bitField0_; // required uint64 high = 1; public static final int HIGH_FIELD_NUMBER = 1; - private boolean hasHigh; - private long high_ = 0L; - public boolean hasHigh() { return hasHigh; } - public long getHigh() { return high_; } + private long high_; + public boolean hasHigh() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public long getHigh() { + return high_; + } // required uint64 low = 2; public static final int LOW_FIELD_NUMBER = 2; - private boolean hasLow; - private long low_ = 0L; - public boolean hasLow() { return hasLow; } - public long getLow() { return low_; } + private long low_; + public boolean hasLow() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public long getLow() { + return low_; + } private void initFields() { + high_ = 0L; + low_ = 0L; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasHigh) return false; - if (!hasLow) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasHigh()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasLow()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasHigh()) { - output.writeUInt64(1, getHigh()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeUInt64(1, high_); } - if (hasLow()) { - output.writeUInt64(2, getLow()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeUInt64(2, low_); } getUnknownFields().writeTo(output); } @@ -515,19 +807,26 @@ public final class MailboxProtocol { if (size != -1) return size; size = 0; - if (hasHigh()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeUInt64Size(1, getHigh()); + .computeUInt64Size(1, high_); } - if (hasLow()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeUInt64Size(2, getLow()); + .computeUInt64Size(2, low_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.actor.mailbox.MailboxProtocol.UuidProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -602,34 +901,53 @@ public final class MailboxProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.actor.mailbox.MailboxProtocol.UuidProtocol result; - - // Construct using akka.actor.mailbox.MailboxProtocol.UuidProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.actor.mailbox.MailboxProtocol.UuidProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.actor.mailbox.MailboxProtocol.UuidProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.actor.mailbox.MailboxProtocol.internal_static_UuidProtocol_descriptor; } - protected akka.actor.mailbox.MailboxProtocol.UuidProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.actor.mailbox.MailboxProtocol.internal_static_UuidProtocol_fieldAccessorTable; + } + + // Construct using akka.actor.mailbox.MailboxProtocol.UuidProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); - } - result = new akka.actor.mailbox.MailboxProtocol.UuidProtocol(); + super.clear(); + high_ = 0L; + bitField0_ = (bitField0_ & ~0x00000001); + low_ = 0L; + bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -641,33 +959,39 @@ public final class MailboxProtocol { return akka.actor.mailbox.MailboxProtocol.UuidProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.actor.mailbox.MailboxProtocol.UuidProtocol build() { - if (result != null && !isInitialized()) { + akka.actor.mailbox.MailboxProtocol.UuidProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.actor.mailbox.MailboxProtocol.UuidProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.actor.mailbox.MailboxProtocol.UuidProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.actor.mailbox.MailboxProtocol.UuidProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.actor.mailbox.MailboxProtocol.UuidProtocol result = new akka.actor.mailbox.MailboxProtocol.UuidProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.actor.mailbox.MailboxProtocol.UuidProtocol returnMe = result; - result = null; - return returnMe; + result.high_ = high_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.low_ = low_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -691,6 +1015,18 @@ public final class MailboxProtocol { return this; } + public final boolean isInitialized() { + if (!hasHigh()) { + + return false; + } + if (!hasLow()) { + + return false; + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -703,61 +1039,72 @@ public final class MailboxProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; } case 8: { - setHigh(input.readUInt64()); + bitField0_ |= 0x00000001; + high_ = input.readUInt64(); break; } case 16: { - setLow(input.readUInt64()); + bitField0_ |= 0x00000002; + low_ = input.readUInt64(); break; } } } } + private int bitField0_; // required uint64 high = 1; + private long high_ ; public boolean hasHigh() { - return result.hasHigh(); + return ((bitField0_ & 0x00000001) == 0x00000001); } public long getHigh() { - return result.getHigh(); + return high_; } public Builder setHigh(long value) { - result.hasHigh = true; - result.high_ = value; + bitField0_ |= 0x00000001; + high_ = value; + onChanged(); return this; } public Builder clearHigh() { - result.hasHigh = false; - result.high_ = 0L; + bitField0_ = (bitField0_ & ~0x00000001); + high_ = 0L; + onChanged(); return this; } // required uint64 low = 2; + private long low_ ; public boolean hasLow() { - return result.hasLow(); + return ((bitField0_ & 0x00000002) == 0x00000002); } public long getLow() { - return result.getLow(); + return low_; } public Builder setLow(long value) { - result.hasLow = true; - result.low_ = value; + bitField0_ |= 0x00000002; + low_ = value; + onChanged(); return this; } public Builder clearLow() { - result.hasLow = false; - result.low_ = 0L; + bitField0_ = (bitField0_ & ~0x00000002); + low_ = 0L; + onChanged(); return this; } @@ -766,7 +1113,6 @@ public final class MailboxProtocol { static { defaultInstance = new UuidProtocol(true); - akka.actor.mailbox.MailboxProtocol.internalForceInit(); defaultInstance.initFields(); } @@ -829,7 +1175,5 @@ public final class MailboxProtocol { }, assigner); } - public static void internalForceInit() {} - // @@protoc_insertion_point(outer_class_scope) } diff --git a/akka-durable-mailboxes/akka-mailboxes-common/src/main/scala/akka/actor/mailbox/DurableDispatcher.scala b/akka-durable-mailboxes/akka-mailboxes-common/src/main/scala/akka/actor/mailbox/DurableDispatcher.scala index 8a1b2c60f1..de54b3fb16 100644 --- a/akka-durable-mailboxes/akka-mailboxes-common/src/main/scala/akka/actor/mailbox/DurableDispatcher.scala +++ b/akka-durable-mailboxes/akka-mailboxes-common/src/main/scala/akka/actor/mailbox/DurableDispatcher.scala @@ -56,7 +56,7 @@ case object ZooKeeperDurableMailboxStorage extends DurableMailboxStorage("akka.a * * @author Jonas Bonér */ -case class DurableEventBasedDispatcher( +case class DurableDispatcher( _name: String, _storage: DurableMailboxStorage, _throughput: Int = Dispatchers.THROUGHPUT, @@ -94,10 +94,12 @@ case class DurableEventBasedDispatcher( override def createMailbox(actorRef: ActorRef): AnyRef = _storage.createFor(actorRef) private[akka] override def dispatch(invocation: MessageInvocation): Unit = { - if (invocation.senderFuture.isDefined) - throw new IllegalArgumentException("Durable mailboxes do not support Future-based messages from !! and !!!") + if (invocation.channel.isInstanceOf[ActorPromise]) + throw new IllegalArgumentException("Durable mailboxes do not support Future-based messages from ?") super.dispatch(invocation) } + + protected override def cleanUpMailboxFor(actorRef: ActorRef) {} //No need to clean up Futures since we don't support them } /** @@ -129,21 +131,21 @@ case class DurablePinnedDispatcher( override def createMailbox(actorRef: ActorRef): AnyRef = _storage.createFor(actorRef) private[akka] override def dispatch(invocation: MessageInvocation): Unit = { - if (invocation.senderFuture.isDefined) - throw new IllegalArgumentException("Actor has a durable mailbox that does not support !! or !!!") + if (invocation.channel.isInstanceOf[ActorPromise]) + throw new IllegalArgumentException("Actor has a durable mailbox that does not support ?") super.dispatch(invocation) } } /** - * Configurator for the DurableEventBasedDispatcher + * Configurator for the DurableDispatcher * Do not forget to specify the "storage", valid values are "redis", "beanstalkd", "zookeeper" and "file" * * @author Jonas Bonér */ -class DurableEventBasedDispatcherConfigurator extends MessageDispatcherConfigurator { +class DurableDispatcherConfigurator extends MessageDispatcherConfigurator { def configure(config: Configuration): MessageDispatcher = { - configureThreadPool(config, threadPoolConfig => new DurableEventBasedDispatcher( + configureThreadPool(config, threadPoolConfig => new DurableDispatcher( config.getString("name", newUuid.toString), getStorage(config), config.getInt("throughput", Dispatchers.THROUGHPUT), @@ -161,6 +163,6 @@ class DurableEventBasedDispatcherConfigurator extends MessageDispatcherConfigura case unknown => throw new IllegalArgumentException("[%s] is not a valid storage, valid options are [redis, beanstalk, zookeeper, file]" format unknown) } - storage.getOrElse(throw new DurableMailboxException("No 'storage' defined for DurableEventBasedDispatcherConfigurator")) + storage.getOrElse(throw new DurableMailboxException("No 'storage' defined for DurableDispatcherConfigurator")) } } diff --git a/akka-durable-mailboxes/akka-mailboxes-common/src/main/scala/akka/actor/mailbox/DurableMailbox.scala b/akka-durable-mailboxes/akka-mailboxes-common/src/main/scala/akka/actor/mailbox/DurableMailbox.scala index 5b83f6a8c4..5a928ce148 100644 --- a/akka-durable-mailboxes/akka-mailboxes-common/src/main/scala/akka/actor/mailbox/DurableMailbox.scala +++ b/akka-durable-mailboxes/akka-mailboxes-common/src/main/scala/akka/actor/mailbox/DurableMailbox.scala @@ -5,7 +5,7 @@ package akka.actor.mailbox import MailboxProtocol._ -import akka.actor.{Actor, ActorRef} +import akka.actor.{Actor, ActorRef, NullChannel} import akka.dispatch._ import akka.event.EventHandler import akka.remote.MessageSerializer @@ -44,11 +44,14 @@ abstract class DurableExecutableMailbox(owner: ActorRef) extends MessageQueue wi //TODO: switch to RemoteProtocol def serialize(durableMessage: MessageInvocation) = { - val message = MessageSerializer.serialize(durableMessage.message) + val message = MessageSerializer.serialize(durableMessage.message.asInstanceOf[AnyRef]) val builder = DurableMailboxMessageProtocol.newBuilder .setOwnerAddress(ownerAddress) .setMessage(message.toByteString) - if (durableMessage.sender.isDefined) builder.setSenderAddress(durableMessage.sender.get.address) + durableMessage.channel match { + case a : ActorRef => builder.setSenderAddress(a.address) + case _ => + } builder.build.toByteArray } @@ -62,10 +65,14 @@ abstract class DurableExecutableMailbox(owner: ActorRef) extends MessageQueue wi throw new DurableMailboxException("No actor could be found for address [" + ownerAddress + "], could not deserialize message.")) - val sender = if (durableMessage.hasSenderAddress) { + val senderOption = if (durableMessage.hasSenderAddress) { Actor.registry.actorFor(durableMessage.getSenderAddress) } else None + val sender = senderOption match { + case Some(ref) => ref + case None => NullChannel + } - new MessageInvocation(owner, message, sender, None) + new MessageInvocation(owner, message, sender) } } diff --git a/akka-durable-mailboxes/akka-mailboxes-common/src/test/scala/akka/actor/mailbox/DurableMailboxSpec.scala b/akka-durable-mailboxes/akka-mailboxes-common/src/test/scala/akka/actor/mailbox/DurableMailboxSpec.scala index b1b3b57d9a..b7d2ee0ff1 100644 --- a/akka-durable-mailboxes/akka-mailboxes-common/src/test/scala/akka/actor/mailbox/DurableMailboxSpec.scala +++ b/akka-durable-mailboxes/akka-mailboxes-common/src/test/scala/akka/actor/mailbox/DurableMailboxSpec.scala @@ -32,7 +32,7 @@ abstract class DurableMailboxSpec(val backendName: String, val storage: DurableM WordSpec with MustMatchers with BeforeAndAfterEach with BeforeAndAfterAll { import DurableMailboxSpecActorFactory._ - implicit val dispatcher = DurableEventBasedDispatcher(backendName, storage, 1) + implicit val dispatcher = DurableDispatcher(backendName, storage, 1) "A " + backendName + " based mailbox backed actor" should { diff --git a/akka-http/src/main/scala/akka/http/AkkaRestServlet.scala b/akka-http/src/main/scala/akka/http/AkkaRestServlet.scala deleted file mode 100644 index 79b5337f93..0000000000 --- a/akka-http/src/main/scala/akka/http/AkkaRestServlet.scala +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (C) 2009-2011 Scalable Solutions AB - */ -package akka.http - -import com.sun.jersey.spi.container.servlet.ServletContainer - -/** - * This is just a simple wrapper on top of ServletContainer to inject some config from the akka.conf - * 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 } - - 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(",")) - - /** - * 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 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/Mist.scala b/akka-http/src/main/scala/akka/http/Mist.scala index 423ad9b291..d5139795ba 100644 --- a/akka-http/src/main/scala/akka/http/Mist.scala +++ b/akka-http/src/main/scala/akka/http/Mist.scala @@ -11,6 +11,7 @@ import akka.config.ConfigurationException import javax.servlet.http.{ HttpServletResponse, HttpServletRequest } import javax.servlet.http.HttpServlet import javax.servlet.Filter +import java.lang.UnsupportedOperationException /** * @author Garrick Evans @@ -71,27 +72,39 @@ trait Mist { /** * The root endpoint actor */ - protected val _root = Actor.registry.actorFor(RootActorID).getOrElse( - throw new ConfigurationException("akka.http.root-actor-id configuration option does not have a valid actor address [" + RootActorID + "]")) + def root: ActorRef /** * Server-specific method factory */ - protected var _factory: Option[RequestMethodFactory] = None + protected var factory: Option[RequestMethodFactory] = None /** * Handles all servlet requests */ protected def mistify(request: HttpServletRequest, - response: HttpServletResponse)(builder: (() ⇒ tAsyncRequestContext) ⇒ RequestMethod) = { - def suspend: tAsyncRequestContext = { + response: HttpServletResponse) = { + + val builder: (() ⇒ tAsyncRequestContext) ⇒ RequestMethod = + request.getMethod.toUpperCase match { + case "DELETE" ⇒ factory.get.Delete + case "GET" ⇒ factory.get.Get + case "HEAD" ⇒ factory.get.Head + case "OPTIONS" ⇒ factory.get.Options + case "POST" ⇒ factory.get.Post + case "PUT" ⇒ factory.get.Put + case "TRACE" ⇒ factory.get.Trace + case unknown ⇒ throw new UnsupportedOperationException(unknown) + } + + def suspend(closeConnection: Boolean): tAsyncRequestContext = { // set to right now, which is effectively "already expired" response.setDateHeader("Expires", System.currentTimeMillis) response.setHeader("Cache-Control", "no-cache, must-revalidate") // no keep-alive? - if (ConnectionClose) response.setHeader("Connection", "close") + if (closeConnection) response.setHeader("Connection", "close") // suspend the request // TODO: move this out to the specialized support if jetty asyncstart doesnt let us update TOs @@ -100,8 +113,8 @@ trait Mist { // 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 + val method = builder(() ⇒ suspend(ConnectionClose)) + if (method.go) root ! method } /** @@ -111,7 +124,7 @@ trait Mist { def initMist(context: ServletContext) { val server = context.getServerInfo val (major, minor) = (context.getMajorVersion, context.getMinorVersion) - _factory = if (major >= 3) { + factory = if (major >= 3) { Some(Servlet30ContextMethodFactory) } else if (server.toLowerCase startsWith JettyServer) { Some(JettyContinuationMethodFactory) @@ -121,11 +134,23 @@ trait Mist { } } +trait RootEndpointLocator { + var root: ActorRef = null + + def configureRoot(address: String) { + def findRoot(address: String): ActorRef = + Actor.registry.actorFor(address).getOrElse( + throw new ConfigurationException("akka.http.root-actor-id configuration option does not have a valid actor address [" + address + "]")) + + root = if ((address eq null) || address == "") findRoot(MistSettings.RootActorID) else findRoot(address) + } +} + /** * AkkaMistServlet adds support to bridge Http and Actors in an asynchronous fashion * Async impls currently supported: Servlet3.0, Jetty Continuations */ -class AkkaMistServlet extends HttpServlet with Mist { +class AkkaMistServlet extends HttpServlet with Mist with RootEndpointLocator { import javax.servlet.{ ServletConfig } /** @@ -134,22 +159,17 @@ class AkkaMistServlet extends HttpServlet with Mist { override def init(config: ServletConfig) { super.init(config) initMist(config.getServletContext) + configureRoot(config.getServletContext.getInitParameter("root-endpoint")) } - 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 service(req: HttpServletRequest, res: HttpServletResponse) = mistify(req, res) } /** * Proof-of-concept, use at own risk * Will be officially supported in a later release */ -class AkkaMistFilter extends Filter with Mist { +class AkkaMistFilter extends Filter with Mist with RootEndpointLocator { import javax.servlet.{ ServletRequest, ServletResponse, FilterConfig, FilterChain } /** @@ -157,6 +177,7 @@ class AkkaMistFilter extends Filter with Mist { */ def init(config: FilterConfig) { initMist(config.getServletContext) + configureRoot(config.getServletContext.getInitParameter("root-endpoint")) } /** @@ -165,16 +186,7 @@ class AkkaMistFilter extends Filter with Mist { override def doFilter(req: ServletRequest, res: ServletResponse, chain: FilterChain) { (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 ⇒ {} - } + mistify(hreq, hres) chain.doFilter(req, res) case _ ⇒ chain.doFilter(req, res) } @@ -276,7 +288,7 @@ class RootEndpoint extends Actor with Endpoint { def recv: Receive = { case NoneAvailable(uri, req) ⇒ _na(uri, req) - case unknown ⇒ {} + case unknown ⇒ } /** @@ -329,24 +341,22 @@ trait RequestMethod { def request = context.get.getRequest.asInstanceOf[HttpServletRequest] def response = context.get.getResponse.asInstanceOf[HttpServletResponse] - def getHeaderOrElse(name: String, default: Function[Any, String]): String = + def getHeaderOrElse(name: String, default: ⇒ String): String = request.getHeader(name) match { - case null ⇒ default(null) + case null ⇒ default case s ⇒ s } - def getParameterOrElse(name: String, default: Function[Any, String]): String = + def getParameterOrElse(name: String, default: ⇒ String): String = request.getParameter(name) match { - case null ⇒ default(null) + case null ⇒ default case s ⇒ s } - def complete(status: Int, body: String): Boolean = complete(status, body, Headers()) - - def complete(status: Int, body: String, headers: Headers): Boolean = + def complete(status: Int, body: String, headers: Headers = Headers()): Boolean = rawComplete { res ⇒ res.setStatus(status) - headers foreach { h ⇒ response.setHeader(h._1, h._2) } + headers foreach { case (name, value) ⇒ response.setHeader(name, value) } res.getWriter.write(body) res.getWriter.close res.flushBuffer diff --git a/akka-http/src/main/scala/akka/http/Servlet30Context.scala b/akka-http/src/main/scala/akka/http/Servlet30Context.scala index 2d354d9a10..cbafffaea3 100644 --- a/akka-http/src/main/scala/akka/http/Servlet30Context.scala +++ b/akka-http/src/main/scala/akka/http/Servlet30Context.scala @@ -45,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 ⇒ EventHandler.error(t, this, t.getMessage) } def onStartAsync(e: AsyncEvent) {} def onTimeout(e: AsyncEvent) = { diff --git a/akka-http/src/main/scala/akka/security/Security.scala b/akka-http/src/main/scala/akka/security/Security.scala deleted file mode 100644 index 969ddeabc2..0000000000 --- a/akka-http/src/main/scala/akka/security/Security.scala +++ /dev/null @@ -1,563 +0,0 @@ -/* - * Copyright 2007-2008 WorldWide Conferencing, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions - * and limitations under the License. - */ - -/* - * AKKA AAS (Authentication and Authorization Service) - * Rework of lift's (www.liftweb.com) HTTP Authentication module - * All cred to the Lift team (www.liftweb.com), especially David Pollak and Tim Perrett - */ - -package akka.security - -import akka.actor.{ Scheduler, Actor, ActorRef, IllegalActorStateException } -import akka.event.EventHandler -import akka.actor.Actor._ -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.core.util.Base64 - -import javax.ws.rs.core.{ SecurityContext, Context, Response } -import javax.ws.rs.WebApplicationException -import javax.annotation.security.{ DenyAll, PermitAll, RolesAllowed } -import java.security.Principal -import java.util.concurrent.TimeUnit - -case object OK - -/** - * Authenticate represents a message to authenticate a request - */ -case class Authenticate(val req: ContainerRequest, val rolesAllowed: List[String]) - -/** - * User info represents a sign-on with associated credentials/roles - */ -case class UserInfo(val username: String, val password: String, val roles: List[String]) - -trait Credentials - -case class BasicCredentials(username: String, password: String) extends Credentials - -case class DigestCredentials(method: String, - userName: String, - realm: String, - nonce: String, - uri: String, - qop: String, - nc: String, - cnonce: String, - response: String, - opaque: String) extends Credentials - -case class SpnegoCredentials(token: Array[Byte]) extends Credentials - -/** - * Jersey Filter for invocation intercept and authorization/authentication - */ -class AkkaSecurityFilterFactory extends ResourceFilterFactory { - class Filter(actor: ActorRef, rolesAllowed: Option[List[String]]) - extends ResourceFilter with ContainerRequestFilter { - - override def getRequestFilter: ContainerRequestFilter = this - - override def getResponseFilter: ContainerResponseFilter = null - - /** - * Here's where the magic happens. The request is authenticated by - * sending a request for authentication to the configured authenticator actor - */ - override def filter(request: ContainerRequest): ContainerRequest = - rolesAllowed match { - case Some(roles) ⇒ { - val result = (authenticator !! Authenticate(request, roles)).as[AnyRef] - result match { - 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 ⇒ { - throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR) - } - } - } - case None ⇒ throw new WebApplicationException(Response.Status.FORBIDDEN) - } - } - - lazy val authenticatorFQN = { - val auth = Config.config.getString("akka.http.authenticator", "N/A") - if (auth == "N/A") throw new IllegalActorStateException("The config option 'akka.http.authenticator' is not defined in 'akka.conf'") - auth - } - - /** - * Currently we always take the first, since there usually should be at most one authentication actor, but a round-robin - * 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 + "]")) - - def mkFilter(roles: Option[List[String]]): java.util.List[ResourceFilter] = - java.util.Collections.singletonList(new Filter(authenticator, roles)) - - /** - * The create method is invoked for each resource, and we look for javax.annotation.security annotations - * and create the appropriate Filter configurations for each. - */ - override def create(am: AbstractMethod): java.util.List[ResourceFilter] = { - - //DenyAll takes precedence - if (am.isAnnotationPresent(classOf[DenyAll])) - return mkFilter(None) - - //Method-level RolesAllowed takes precedence - val ra = am.getAnnotation(classOf[RolesAllowed]) - - if (ra ne null) - return mkFilter(Some(ra.value.toList)) - - //PermitAll takes precedence over resource-level RolesAllowed annotation - if (am.isAnnotationPresent(classOf[PermitAll])) - return null; - - //Last but not least, the resource-level RolesAllowed - val cra = am.getResource.getAnnotation(classOf[RolesAllowed]) - if (cra ne null) - return mkFilter(Some(cra.value.toList)) - - return null; - } -} - -/** - * AuthenticationActor is the super-trait for actors doing Http authentication - * It defines the common ground and the flow of execution - */ -trait AuthenticationActor[C <: Credentials] extends Actor { - type Req = ContainerRequest - - //What realm does the authentication use? - def realm: String - - //Creates a response to signal unauthorized - def unauthorized: Response - - //Used to extract information from the request, returns None if no credentials found - def extractCredentials(r: Req): Option[C] - - //returns None is unverified - def verify(c: Option[C]): Option[UserInfo] - - //Contruct a new SecurityContext from the supplied parameters - def mkSecurityContext(r: Req, user: UserInfo): SecurityContext - - //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 } - - new SecurityContext { - def getAuthenticationScheme = scheme - def getUserPrincipal = p - def isSecure = r.isSecure - def isUserInRole(role: String) = u.roles.exists(_ == role) - } - } - - /** - * Responsible for the execution flow of authentication - * - * Credentials are extracted and verified from the request, - * and a security context is created for the ContainerRequest - * this should ensure good integration with current Jersey security - */ - protected val authenticate: Receive = { - case Authenticate(req, roles) ⇒ { - verify(extractCredentials(req)) match { - 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) - } - } - } - - def receive = authenticate - - //returns the string value of the "Authorization"-header of the request - def auth(r: Req) = r.getHeaderValue("Authorization") - - //Turns the aforementioned header value into an option - def authOption(r: Req): Option[String] = { - val a = auth(r) - if ((a ne null) && a.length > 0) Some(a) else None - } -} - -/** - * This trait implements the logic for Http Basic authentication - * mix this trait into a class to create an authenticator - * Don't forget to set the authenticator FQN in the rest-part of the akka config - */ -trait BasicAuthenticationActor extends AuthenticationActor[BasicCredentials] { - override def unauthorized = - Response.status(401).header("WWW-Authenticate", "Basic realm=\"" + realm + "\"").build - - override def extractCredentials(r: Req): Option[BasicCredentials] = { - val Authorization = """(.*):(.*)""".r - - authOption(r) match { - 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 _ ⇒ None - } - } - - override def mkSecurityContext(r: Req, u: UserInfo): SecurityContext = - mkDefaultSecurityContext(r, u, SecurityContext.BASIC_AUTH) -} - -/** - * This trait implements the logic for Http Digest authentication mix this trait into a - * class to create an authenticator. Don't forget to set the authenticator FQN in the - * rest-part of the akka config - */ -trait DigestAuthenticationActor extends AuthenticationActor[DigestCredentials] { - import LiftUtils._ - - private object InvalidateNonces - - //Holds the generated nonces for the specified validity period - val nonceMap = mkNonceMap - - //Discards old nonces - protected val invalidateNonces: Receive = { - case InvalidateNonces ⇒ - val ts = System.currentTimeMillis - nonceMap.filter(tuple ⇒ (ts - tuple._2) < nonceValidityPeriod) - case unknown ⇒ {} - } - - //Schedule the invalidation of nonces - Scheduler.schedule(self, InvalidateNonces, noncePurgeInterval, noncePurgeInterval, TimeUnit.MILLISECONDS) - - //authenticate or invalidate nonces - override def receive = authenticate orElse invalidateNonces - - override def unauthorized: Response = { - val nonce = randomString(64) - nonceMap.put(nonce, System.currentTimeMillis) - unauthorized(nonce, "auth", randomString(64)) - } - - def unauthorized(nonce: String, qop: String, opaque: String): Response = { - Response.status(401).header( - "WWW-Authenticate", - "Digest realm=\"" + realm + "\", " + - "qop=\"" + qop + "\", " + - "nonce=\"" + nonce + "\", " + - "opaque=\"" + opaque + "\"").build - } - - //Tests wether the specified credentials are valid - def validate(auth: DigestCredentials, user: UserInfo): Boolean = { - def h(s: String) = hexEncode(md5(s.getBytes("UTF-8"))) - - val ha1 = h(auth.userName + ":" + auth.realm + ":" + user.password) - val ha2 = h(auth.method + ":" + auth.uri) - - val response = h( - ha1 + ":" + auth.nonce + ":" + - 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) ⇒ { - 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 _ ⇒ None - } - - override def extractCredentials(r: Req): Option[DigestCredentials] = { - authOption(r).map(s ⇒ { - val ? = splitNameValuePairs(s.substring(7, s.length)) - DigestCredentials(r.getMethod.toUpperCase, - ?("username"), ?("realm"), ?("nonce"), - ?("uri"), ?("qop"), ?("nc"), - ?("cnonce"), ?("response"), ?("opaque")) - }) - } - - override def mkSecurityContext(r: Req, u: UserInfo): SecurityContext = - mkDefaultSecurityContext(r, u, SecurityContext.DIGEST_AUTH) - - //Mandatory overrides - def userInfo(username: String): Option[UserInfo] - - def mkNonceMap: scala.collection.mutable.Map[String, Long] - - //Optional overrides - def nonceValidityPeriod = 60 * 1000 //ms - def noncePurgeInterval = 2 * 60 * 1000 //ms -} - -import java.security.Principal -import java.security.PrivilegedActionException -import java.security.PrivilegedExceptionAction - -import javax.security.auth.login.AppConfigurationEntry -import javax.security.auth.login.Configuration -import javax.security.auth.login.LoginContext -import javax.security.auth.Subject -import javax.security.auth.kerberos.KerberosPrincipal - -import org.ietf.jgss.GSSContext -import org.ietf.jgss.GSSCredential -import org.ietf.jgss.GSSManager - -trait SpnegoAuthenticationActor extends AuthenticationActor[SpnegoCredentials] { - override def unauthorized = - Response.status(401).header("WWW-Authenticate", "Negotiate").build - - // for some reason the jersey Base64 class does not work with kerberos - // but the commons Base64 does - import org.apache.commons.codec.binary.Base64 - override def extractCredentials(r: Req): Option[SpnegoCredentials] = { - val AuthHeader = """Negotiate\s(.*)""".r - - authOption(r) match { - case Some(AuthHeader(token)) ⇒ - Some(SpnegoCredentials(Base64.decodeBase64(token.trim.getBytes))) - case _ ⇒ None - } - } - - override def verify(odc: Option[SpnegoCredentials]): Option[UserInfo] = odc match { - 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 ⇒ { - EventHandler.error(e, this, e.getMessage) - None - } - } - } - case _ ⇒ None - } - - override def mkSecurityContext(r: Req, u: UserInfo): SecurityContext = - mkDefaultSecurityContext(r, u, SecurityContext.CLIENT_CERT_AUTH) // the security context does not know about spnego/kerberos - // not sure whether to use a constant from the security context or something like "SPNEGO/Kerberos" - - /** - * returns the roles for the given user - */ - def rolesFor(user: String): List[String] - - // Kerberos - - /** - * strips the realm from a kerberos principal name, returning only the user part - */ - private def stripRealmFrom(principal: String): String = principal.split("@")(0) - - /** - * principal name for the HTTP kerberos service, i.e HTTP/ { server } @ { realm } - */ - lazy val servicePrincipal = { - val p = Config.config.getString("akka.http.kerberos.servicePrincipal", "N/A") - if (p == "N/A") throw new IllegalActorStateException("The config option 'akka.http.kerberos.servicePrincipal' is not defined in 'akka.conf'") - p - } - - /** - * keytab location with credentials for the service principal - */ - lazy val keyTabLocation = { - val p = Config.config.getString("akka.http.kerberos.keyTabLocation", "N/A") - if (p == "N/A") throw new IllegalActorStateException("The config option 'akka.http.kerberos.keyTabLocation' is not defined in 'akka.conf'") - p - } - - lazy val kerberosDebug = { - val p = Config.config.getString("akka.http.kerberos.kerberosDebug", "N/A") - if (p == "N/A") throw new IllegalActorStateException("The config option 'akka.http.kerberos.kerberosDebug' is not defined in 'akka.conf'") - p - } - - /** - * is not used by this authenticator, so accept an empty value - */ - lazy val realm = Config.config.getString("akka.http.kerberos.realm", "") - - /** - * verify the kerberos token from a client with the server - */ - class KerberosValidateAction(kerberosTicket: Array[Byte]) extends PrivilegedExceptionAction[String] { - def run = { - val context = GSSManager.getInstance().createContext(null.asInstanceOf[GSSCredential]) - context.acceptSecContext(kerberosTicket, 0, kerberosTicket.length) - val user = context.getSrcName().toString() - context.dispose() - user - } - } - - // service principal login to kerberos on startup - - val serviceSubject = servicePrincipalLogin - - /** - * acquire an initial ticket from the kerberos server for the HTTP service - */ - def servicePrincipalLogin = { - val loginConfig = new LoginConfig( - new java.net.URL(this.keyTabLocation).toExternalForm(), - this.servicePrincipal, - this.kerberosDebug) - val princ = new java.util.HashSet[Principal](1) - princ.add(new KerberosPrincipal(this.servicePrincipal)) - val sub = new Subject(false, princ, new java.util.HashSet[Object], new java.util.HashSet[Object]) - val lc = new LoginContext("", sub, null, loginConfig) - lc.login() - lc.getSubject() - } - - /** - * this class simulates a login-config.xml - */ - class LoginConfig(keyTabLocation: String, servicePrincipal: String, debug: String) extends Configuration { - override def getAppConfigurationEntry(name: String): Array[AppConfigurationEntry] = { - val options = new java.util.HashMap[String, String] - options.put("useKeyTab", "true") - options.put("keyTab", this.keyTabLocation) - options.put("principal", this.servicePrincipal) - options.put("storeKey", "true") - options.put("doNotPrompt", "true") - options.put("isInitiator", "true") - options.put("debug", debug) - - Array(new AppConfigurationEntry( - "com.sun.security.auth.module.Krb5LoginModule", - AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, - options)) - } - } - -} - -/* -* Copyright 2006-2010 WorldWide Conferencing, LLC -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -object LiftUtils { - 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 - */ - 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 - }) - addChar(pos + 1, randNum >> 5, sb) - } - } - addChar(0, 0, new StringBuilder(size)).toString - } - - /** encode a Byte array as hexadecimal characters */ - def hexEncode(in: Array[Byte]): String = { - val sb = new StringBuilder - val len = in.length - def addDigit(in: Array[Byte], pos: Int, len: Int, sb: StringBuilder) { - if (pos < len) { - val b: Int = in(pos) - val msb = (b & 0xf0) >> 4 - val lsb = (b & 0x0f) - sb.append((if (msb < 10) ('0' + msb).asInstanceOf[Char] else ('a' + (msb - 10)).asInstanceOf[Char])) - sb.append((if (lsb < 10) ('0' + lsb).asInstanceOf[Char] else ('a' + (lsb - 10)).asInstanceOf[Char])) - addDigit(in, pos + 1, len, sb) - } - } - addDigit(in, 0, len, sb) - sb.toString - } - - /** - * 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 - */ - 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) - else - 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 map: Map[String, String] = Map.empty - (map /: list)((m, next) ⇒ m + (next)) - } -} diff --git a/akka-http/src/test/scala/AllTest.scala b/akka-http/src/test/scala/AllTest.scala deleted file mode 100644 index 0b473507dd..0000000000 --- a/akka-http/src/test/scala/AllTest.scala +++ /dev/null @@ -1,15 +0,0 @@ -package akka.security - -import junit.framework.Test -import junit.framework.TestCase -import junit.framework.TestSuite - -object AllTest extends TestCase { - def suite(): Test = { - val suite = new TestSuite("All Scala tests") - suite.addTestSuite(classOf[BasicAuthenticatorSpec]) - suite - } - - def main(args: Array[String]) = junit.textui.TestRunner.run(suite) -} diff --git a/akka-http/src/test/scala/SecuritySpec.scala b/akka-http/src/test/scala/SecuritySpec.scala deleted file mode 100644 index edf7b2bac0..0000000000 --- a/akka-http/src/test/scala/SecuritySpec.scala +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright (C) 2009-2011 Scalable Solutions AB - */ - -package akka.security - -import akka.config.Supervision._ -import akka.actor.Actor._ - -import org.scalatest.Suite -import org.scalatest.junit.JUnitSuite -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 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 - } - override def realm = "test" - } -} - -class BasicAuthenticatorSpec extends junit.framework.TestCase - with Suite with MockitoSugar with MustMatchers { - import BasicAuthenticatorSpec._ - - val authenticator = actorOf[BasicAuthenticator] - authenticator.start() - - @Test - def testChallenge = { - val req = mock[ContainerRequest] - - val result = (authenticator !! (Authenticate(req, List("foo")), 10000)).as[Response].get - - // the actor replies with a challenge for the browser - result.getStatus must equal(Response.Status.UNAUTHORIZED.getStatusCode) - result.getMetadata.get("WWW-Authenticate").get(0).toString must startWith("Basic") - } - - @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"))) - - // fake a request authorization -> this will authorize the user - when(req.isUserInRole("chef")).thenReturn(true) - - val result = (authenticator !! (Authenticate(req, List("chef")), 10000)).as[AnyRef].get - - result must be(OK) - // the authenticator must have set a security context - verify(req).setSecurityContext(any[SecurityContext]) - } - - @Test - def testUnauthorized = { - 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"))) - when(req.isUserInRole("chef")).thenReturn(false) // this will deny access - - val result = (authenticator !! (Authenticate(req, List("chef")), 10000)).as[Response].get - - result.getStatus must equal(Response.Status.FORBIDDEN.getStatusCode) - - // the authenticator must have set a security context - verify(req).setSecurityContext(any[SecurityContext]) - } -} - diff --git a/akka-http/src/test/scala/config/ConfigSpec.scala b/akka-http/src/test/scala/config/ConfigSpec.scala index 2b21f3cc34..fe4ad0c2f9 100644 --- a/akka-http/src/test/scala/config/ConfigSpec.scala +++ b/akka-http/src/test/scala/config/ConfigSpec.scala @@ -16,17 +16,10 @@ class ConfigSpec extends WordSpec with MustMatchers { "contain all configuration properties for akka-http that are used in code with their correct defaults" in { import Config.config._ - getString("akka.http.authenticator") must equal(Some("N/A")) getBool("akka.http.connection-close") must equal(Some(true)) getString("akka.http.expired-header-name") must equal(Some("Async-Timeout")) - getList("akka.http.filters") must equal(List("akka.security.AkkaSecurityFilterFactory")) - getList("akka.http.resource-packages") must equal(Nil) getString("akka.http.hostname") must equal(Some("localhost")) getString("akka.http.expired-header-value") must equal(Some("expired")) - getString("akka.http.kerberos.servicePrincipal") must equal(Some("N/A")) - getString("akka.http.kerberos.keyTabLocation") must equal(Some("N/A")) - getString("akka.http.kerberos.kerberosDebug") must equal(Some("N/A")) - getString("akka.http.kerberos.realm") must equal(Some("")) getInt("akka.http.port") must equal(Some(9998)) getBool("akka.http.root-actor-builtin") must equal(Some(true)) getString("akka.http.root-actor-id") must equal(Some("_httproot")) diff --git a/akka-kernel/src/main/scala/akka/kernel/EmbeddedAppServer.scala b/akka-kernel/src/main/scala/akka/kernel/EmbeddedAppServer.scala index 286d2b3b04..471f45213e 100644 --- a/akka-kernel/src/main/scala/akka/kernel/EmbeddedAppServer.scala +++ b/akka-kernel/src/main/scala/akka/kernel/EmbeddedAppServer.scala @@ -40,7 +40,7 @@ trait EmbeddedAppServer extends Bootable { super.onLoad if (isRestEnabled) { - val configuration = new XmlConfiguration(findJettyConfigXML.getOrElse(error("microkernel-server.xml not found!"))) + val configuration = new XmlConfiguration(findJettyConfigXML.getOrElse(sys.error("microkernel-server.xml not found!"))) System.setProperty("jetty.port", REST_PORT.toString) System.setProperty("jetty.host", REST_HOSTNAME) diff --git a/akka-remote/src/main/java/akka/remote/protocol/RemoteProtocol.java b/akka-remote/src/main/java/akka/remote/protocol/RemoteProtocol.java index 5ebf1f58dd..2f91c19406 100644 --- a/akka-remote/src/main/java/akka/remote/protocol/RemoteProtocol.java +++ b/akka-remote/src/main/java/akka/remote/protocol/RemoteProtocol.java @@ -14,6 +14,9 @@ public final class RemoteProtocol { SHUTDOWN(1, 2), ; + public static final int CONNECT_VALUE = 1; + public static final int SHUTDOWN_VALUE = 2; + public final int getNumber() { return value; } @@ -33,8 +36,8 @@ public final class RemoteProtocol { internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { public CommandType findValueByNumber(int number) { - return CommandType.valueOf(number) - ; } + return CommandType.valueOf(number); + } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor @@ -53,6 +56,7 @@ public final class RemoteProtocol { private static final CommandType[] VALUES = { CONNECT, SHUTDOWN, }; + public static CommandType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { @@ -61,18 +65,157 @@ public final class RemoteProtocol { } return VALUES[desc.getIndex()]; } + private final int index; private final int value; + private CommandType(int index, int value) { this.index = index; this.value = value; } - static { - akka.remote.protocol.RemoteProtocol.getDescriptor(); + // @@protoc_insertion_point(enum_scope:CommandType) + } + + public enum ReplicationStorageType + implements com.google.protobuf.ProtocolMessageEnum { + TRANSIENT(0, 1), + TRANSACTION_LOG(1, 2), + DATA_GRID(2, 3), + ; + + public static final int TRANSIENT_VALUE = 1; + public static final int TRANSACTION_LOG_VALUE = 2; + public static final int DATA_GRID_VALUE = 3; + + + public final int getNumber() { return value; } + + public static ReplicationStorageType valueOf(int value) { + switch (value) { + case 1: return TRANSIENT; + case 2: return TRANSACTION_LOG; + case 3: return DATA_GRID; + default: return null; + } } - // @@protoc_insertion_point(enum_scope:CommandType) + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static com.google.protobuf.Internal.EnumLiteMap + internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public ReplicationStorageType findValueByNumber(int number) { + return ReplicationStorageType.valueOf(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(index); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.getDescriptor().getEnumTypes().get(1); + } + + private static final ReplicationStorageType[] VALUES = { + TRANSIENT, TRANSACTION_LOG, DATA_GRID, + }; + + public static ReplicationStorageType valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + + private final int index; + private final int value; + + private ReplicationStorageType(int index, int value) { + this.index = index; + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:ReplicationStorageType) + } + + public enum ReplicationStrategyType + implements com.google.protobuf.ProtocolMessageEnum { + WRITE_THROUGH(0, 1), + WRITE_BEHIND(1, 2), + ; + + public static final int WRITE_THROUGH_VALUE = 1; + public static final int WRITE_BEHIND_VALUE = 2; + + + public final int getNumber() { return value; } + + public static ReplicationStrategyType valueOf(int value) { + switch (value) { + case 1: return WRITE_THROUGH; + case 2: return WRITE_BEHIND; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static com.google.protobuf.Internal.EnumLiteMap + internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public ReplicationStrategyType findValueByNumber(int number) { + return ReplicationStrategyType.valueOf(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(index); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.getDescriptor().getEnumTypes().get(2); + } + + private static final ReplicationStrategyType[] VALUES = { + WRITE_THROUGH, WRITE_BEHIND, + }; + + public static ReplicationStrategyType valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + + private final int index; + private final int value; + + private ReplicationStrategyType(int index, int value) { + this.index = index; + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:ReplicationStrategyType) } public enum SerializationSchemeType @@ -84,6 +227,12 @@ public final class RemoteProtocol { PROTOBUF(4, 5), ; + public static final int JAVA_VALUE = 1; + public static final int SBINARY_VALUE = 2; + public static final int SCALA_JSON_VALUE = 3; + public static final int JAVA_JSON_VALUE = 4; + public static final int PROTOBUF_VALUE = 5; + public final int getNumber() { return value; } @@ -106,8 +255,8 @@ public final class RemoteProtocol { internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { public SerializationSchemeType findValueByNumber(int number) { - return SerializationSchemeType.valueOf(number) - ; } + return SerializationSchemeType.valueOf(number); + } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor @@ -120,12 +269,13 @@ public final class RemoteProtocol { } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { - return akka.remote.protocol.RemoteProtocol.getDescriptor().getEnumTypes().get(1); + return akka.remote.protocol.RemoteProtocol.getDescriptor().getEnumTypes().get(3); } private static final SerializationSchemeType[] VALUES = { JAVA, SBINARY, SCALA_JSON, JAVA_JSON, PROTOBUF, }; + public static SerializationSchemeType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { @@ -134,17 +284,15 @@ public final class RemoteProtocol { } return VALUES[desc.getIndex()]; } + private final int index; private final int value; + private SerializationSchemeType(int index, int value) { this.index = index; this.value = value; } - static { - akka.remote.protocol.RemoteProtocol.getDescriptor(); - } - // @@protoc_insertion_point(enum_scope:SerializationSchemeType) } @@ -154,6 +302,9 @@ public final class RemoteProtocol { TEMPORARY(1, 2), ; + public static final int PERMANENT_VALUE = 1; + public static final int TEMPORARY_VALUE = 2; + public final int getNumber() { return value; } @@ -173,8 +324,8 @@ public final class RemoteProtocol { internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { public LifeCycleType findValueByNumber(int number) { - return LifeCycleType.valueOf(number) - ; } + return LifeCycleType.valueOf(number); + } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor @@ -187,12 +338,13 @@ public final class RemoteProtocol { } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { - return akka.remote.protocol.RemoteProtocol.getDescriptor().getEnumTypes().get(2); + return akka.remote.protocol.RemoteProtocol.getDescriptor().getEnumTypes().get(4); } private static final LifeCycleType[] VALUES = { PERMANENT, TEMPORARY, }; + public static LifeCycleType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { @@ -201,25 +353,37 @@ public final class RemoteProtocol { } return VALUES[desc.getIndex()]; } + private final int index; private final int value; + private LifeCycleType(int index, int value) { this.index = index; this.value = value; } - static { - akka.remote.protocol.RemoteProtocol.getDescriptor(); - } - // @@protoc_insertion_point(enum_scope:LifeCycleType) } + public interface AkkaRemoteProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional .RemoteMessageProtocol message = 1; + boolean hasMessage(); + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol getMessage(); + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocolOrBuilder getMessageOrBuilder(); + + // optional .RemoteControlProtocol instruction = 2; + boolean hasInstruction(); + akka.remote.protocol.RemoteProtocol.RemoteControlProtocol getInstruction(); + akka.remote.protocol.RemoteProtocol.RemoteControlProtocolOrBuilder getInstructionOrBuilder(); + } public static final class AkkaRemoteProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements AkkaRemoteProtocolOrBuilder { // Use AkkaRemoteProtocol.newBuilder() to construct. - private AkkaRemoteProtocol() { - initFields(); + private AkkaRemoteProtocol(Builder builder) { + super(builder); } private AkkaRemoteProtocol(boolean noInit) {} @@ -242,42 +406,66 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.internal_static_AkkaRemoteProtocol_fieldAccessorTable; } + private int bitField0_; // optional .RemoteMessageProtocol message = 1; public static final int MESSAGE_FIELD_NUMBER = 1; - private boolean hasMessage; private akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol message_; - public boolean hasMessage() { return hasMessage; } - public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol getMessage() { return message_; } + public boolean hasMessage() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol getMessage() { + return message_; + } + public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocolOrBuilder getMessageOrBuilder() { + return message_; + } // optional .RemoteControlProtocol instruction = 2; public static final int INSTRUCTION_FIELD_NUMBER = 2; - private boolean hasInstruction; private akka.remote.protocol.RemoteProtocol.RemoteControlProtocol instruction_; - public boolean hasInstruction() { return hasInstruction; } - public akka.remote.protocol.RemoteProtocol.RemoteControlProtocol getInstruction() { return instruction_; } + public boolean hasInstruction() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public akka.remote.protocol.RemoteProtocol.RemoteControlProtocol getInstruction() { + return instruction_; + } + public akka.remote.protocol.RemoteProtocol.RemoteControlProtocolOrBuilder getInstructionOrBuilder() { + return instruction_; + } private void initFields() { message_ = akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.getDefaultInstance(); instruction_ = akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.getDefaultInstance(); } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + if (hasMessage()) { - if (!getMessage().isInitialized()) return false; + if (!getMessage().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } } if (hasInstruction()) { - if (!getInstruction().isInitialized()) return false; + if (!getInstruction().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasMessage()) { - output.writeMessage(1, getMessage()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeMessage(1, message_); } - if (hasInstruction()) { - output.writeMessage(2, getInstruction()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeMessage(2, instruction_); } getUnknownFields().writeTo(output); } @@ -288,19 +476,26 @@ public final class RemoteProtocol { if (size != -1) return size; size = 0; - if (hasMessage()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(1, getMessage()); + .computeMessageSize(1, message_); } - if (hasInstruction()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(2, getInstruction()); + .computeMessageSize(2, instruction_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -375,34 +570,63 @@ public final class RemoteProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol result; - - // Construct using akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.internal_static_AkkaRemoteProtocol_descriptor; } - protected akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.remote.protocol.RemoteProtocol.internal_static_AkkaRemoteProtocol_fieldAccessorTable; + } + + // Construct using akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getMessageFieldBuilder(); + getInstructionFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); + super.clear(); + if (messageBuilder_ == null) { + message_ = akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.getDefaultInstance(); + } else { + messageBuilder_.clear(); } - result = new akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol(); + bitField0_ = (bitField0_ & ~0x00000001); + if (instructionBuilder_ == null) { + instruction_ = akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.getDefaultInstance(); + } else { + instructionBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -414,33 +638,47 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol build() { - if (result != null && !isInitialized()) { + akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol result = new akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.remote.protocol.RemoteProtocol.AkkaRemoteProtocol returnMe = result; - result = null; - return returnMe; + if (messageBuilder_ == null) { + result.message_ = message_; + } else { + result.message_ = messageBuilder_.build(); + } + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + if (instructionBuilder_ == null) { + result.instruction_ = instruction_; + } else { + result.instruction_ = instructionBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -464,6 +702,22 @@ public final class RemoteProtocol { return this; } + public final boolean isInitialized() { + if (hasMessage()) { + if (!getMessage().isInitialized()) { + + return false; + } + } + if (hasInstruction()) { + if (!getInstruction().isInitialized()) { + + return false; + } + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -476,11 +730,13 @@ public final class RemoteProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; @@ -507,98 +763,252 @@ public final class RemoteProtocol { } } + private int bitField0_; // optional .RemoteMessageProtocol message = 1; + private akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol message_ = akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocolOrBuilder> messageBuilder_; public boolean hasMessage() { - return result.hasMessage(); + return ((bitField0_ & 0x00000001) == 0x00000001); } public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol getMessage() { - return result.getMessage(); + if (messageBuilder_ == null) { + return message_; + } else { + return messageBuilder_.getMessage(); + } } public Builder setMessage(akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (messageBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + message_ = value; + onChanged(); + } else { + messageBuilder_.setMessage(value); } - result.hasMessage = true; - result.message_ = value; + bitField0_ |= 0x00000001; return this; } - public Builder setMessage(akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder builderForValue) { - result.hasMessage = true; - result.message_ = builderForValue.build(); + public Builder setMessage( + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder builderForValue) { + if (messageBuilder_ == null) { + message_ = builderForValue.build(); + onChanged(); + } else { + messageBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000001; return this; } public Builder mergeMessage(akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol value) { - if (result.hasMessage() && - result.message_ != akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.getDefaultInstance()) { - result.message_ = - akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.newBuilder(result.message_).mergeFrom(value).buildPartial(); + if (messageBuilder_ == null) { + if (((bitField0_ & 0x00000001) == 0x00000001) && + message_ != akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.getDefaultInstance()) { + message_ = + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.newBuilder(message_).mergeFrom(value).buildPartial(); + } else { + message_ = value; + } + onChanged(); } else { - result.message_ = value; + messageBuilder_.mergeFrom(value); } - result.hasMessage = true; + bitField0_ |= 0x00000001; return this; } public Builder clearMessage() { - result.hasMessage = false; - result.message_ = akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.getDefaultInstance(); + if (messageBuilder_ == null) { + message_ = akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.getDefaultInstance(); + onChanged(); + } else { + messageBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000001); return this; } + public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder getMessageBuilder() { + bitField0_ |= 0x00000001; + onChanged(); + return getMessageFieldBuilder().getBuilder(); + } + public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocolOrBuilder getMessageOrBuilder() { + if (messageBuilder_ != null) { + return messageBuilder_.getMessageOrBuilder(); + } else { + return message_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocolOrBuilder> + getMessageFieldBuilder() { + if (messageBuilder_ == null) { + messageBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocolOrBuilder>( + message_, + getParentForChildren(), + isClean()); + message_ = null; + } + return messageBuilder_; + } // optional .RemoteControlProtocol instruction = 2; + private akka.remote.protocol.RemoteProtocol.RemoteControlProtocol instruction_ = akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteControlProtocol, akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteControlProtocolOrBuilder> instructionBuilder_; public boolean hasInstruction() { - return result.hasInstruction(); + return ((bitField0_ & 0x00000002) == 0x00000002); } public akka.remote.protocol.RemoteProtocol.RemoteControlProtocol getInstruction() { - return result.getInstruction(); + if (instructionBuilder_ == null) { + return instruction_; + } else { + return instructionBuilder_.getMessage(); + } } public Builder setInstruction(akka.remote.protocol.RemoteProtocol.RemoteControlProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (instructionBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + instruction_ = value; + onChanged(); + } else { + instructionBuilder_.setMessage(value); } - result.hasInstruction = true; - result.instruction_ = value; + bitField0_ |= 0x00000002; return this; } - public Builder setInstruction(akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.Builder builderForValue) { - result.hasInstruction = true; - result.instruction_ = builderForValue.build(); + public Builder setInstruction( + akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.Builder builderForValue) { + if (instructionBuilder_ == null) { + instruction_ = builderForValue.build(); + onChanged(); + } else { + instructionBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000002; return this; } public Builder mergeInstruction(akka.remote.protocol.RemoteProtocol.RemoteControlProtocol value) { - if (result.hasInstruction() && - result.instruction_ != akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.getDefaultInstance()) { - result.instruction_ = - akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.newBuilder(result.instruction_).mergeFrom(value).buildPartial(); + if (instructionBuilder_ == null) { + if (((bitField0_ & 0x00000002) == 0x00000002) && + instruction_ != akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.getDefaultInstance()) { + instruction_ = + akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.newBuilder(instruction_).mergeFrom(value).buildPartial(); + } else { + instruction_ = value; + } + onChanged(); } else { - result.instruction_ = value; + instructionBuilder_.mergeFrom(value); } - result.hasInstruction = true; + bitField0_ |= 0x00000002; return this; } public Builder clearInstruction() { - result.hasInstruction = false; - result.instruction_ = akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.getDefaultInstance(); + if (instructionBuilder_ == null) { + instruction_ = akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.getDefaultInstance(); + onChanged(); + } else { + instructionBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); return this; } + public akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.Builder getInstructionBuilder() { + bitField0_ |= 0x00000002; + onChanged(); + return getInstructionFieldBuilder().getBuilder(); + } + public akka.remote.protocol.RemoteProtocol.RemoteControlProtocolOrBuilder getInstructionOrBuilder() { + if (instructionBuilder_ != null) { + return instructionBuilder_.getMessageOrBuilder(); + } else { + return instruction_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteControlProtocol, akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteControlProtocolOrBuilder> + getInstructionFieldBuilder() { + if (instructionBuilder_ == null) { + instructionBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteControlProtocol, akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteControlProtocolOrBuilder>( + instruction_, + getParentForChildren(), + isClean()); + instruction_ = null; + } + return instructionBuilder_; + } // @@protoc_insertion_point(builder_scope:AkkaRemoteProtocol) } static { defaultInstance = new AkkaRemoteProtocol(true); - akka.remote.protocol.RemoteProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:AkkaRemoteProtocol) } + public interface RemoteMessageProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required .UuidProtocol uuid = 1; + boolean hasUuid(); + akka.remote.protocol.RemoteProtocol.UuidProtocol getUuid(); + akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder getUuidOrBuilder(); + + // required .ActorInfoProtocol actorInfo = 2; + boolean hasActorInfo(); + akka.remote.protocol.RemoteProtocol.ActorInfoProtocol getActorInfo(); + akka.remote.protocol.RemoteProtocol.ActorInfoProtocolOrBuilder getActorInfoOrBuilder(); + + // required bool oneWay = 3; + boolean hasOneWay(); + boolean getOneWay(); + + // optional .MessageProtocol message = 4; + boolean hasMessage(); + akka.remote.protocol.RemoteProtocol.MessageProtocol getMessage(); + akka.remote.protocol.RemoteProtocol.MessageProtocolOrBuilder getMessageOrBuilder(); + + // optional .ExceptionProtocol exception = 5; + boolean hasException(); + akka.remote.protocol.RemoteProtocol.ExceptionProtocol getException(); + akka.remote.protocol.RemoteProtocol.ExceptionProtocolOrBuilder getExceptionOrBuilder(); + + // optional .UuidProtocol supervisorUuid = 6; + boolean hasSupervisorUuid(); + akka.remote.protocol.RemoteProtocol.UuidProtocol getSupervisorUuid(); + akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder getSupervisorUuidOrBuilder(); + + // optional .RemoteActorRefProtocol sender = 7; + boolean hasSender(); + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol getSender(); + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocolOrBuilder getSenderOrBuilder(); + + // repeated .MetadataEntryProtocol metadata = 8; + java.util.List + getMetadataList(); + akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol getMetadata(int index); + int getMetadataCount(); + java.util.List + getMetadataOrBuilderList(); + akka.remote.protocol.RemoteProtocol.MetadataEntryProtocolOrBuilder getMetadataOrBuilder( + int index); + } public static final class RemoteMessageProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements RemoteMessageProtocolOrBuilder { // Use RemoteMessageProtocol.newBuilder() to construct. - private RemoteMessageProtocol() { - initFields(); + private RemoteMessageProtocol(Builder builder) { + super(builder); } private RemoteMessageProtocol(boolean noInit) {} @@ -621,125 +1031,211 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.internal_static_RemoteMessageProtocol_fieldAccessorTable; } + private int bitField0_; // required .UuidProtocol uuid = 1; public static final int UUID_FIELD_NUMBER = 1; - private boolean hasUuid; private akka.remote.protocol.RemoteProtocol.UuidProtocol uuid_; - public boolean hasUuid() { return hasUuid; } - public akka.remote.protocol.RemoteProtocol.UuidProtocol getUuid() { return uuid_; } + public boolean hasUuid() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public akka.remote.protocol.RemoteProtocol.UuidProtocol getUuid() { + return uuid_; + } + public akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder getUuidOrBuilder() { + return uuid_; + } // required .ActorInfoProtocol actorInfo = 2; public static final int ACTORINFO_FIELD_NUMBER = 2; - private boolean hasActorInfo; private akka.remote.protocol.RemoteProtocol.ActorInfoProtocol actorInfo_; - public boolean hasActorInfo() { return hasActorInfo; } - public akka.remote.protocol.RemoteProtocol.ActorInfoProtocol getActorInfo() { return actorInfo_; } + public boolean hasActorInfo() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public akka.remote.protocol.RemoteProtocol.ActorInfoProtocol getActorInfo() { + return actorInfo_; + } + public akka.remote.protocol.RemoteProtocol.ActorInfoProtocolOrBuilder getActorInfoOrBuilder() { + return actorInfo_; + } // required bool oneWay = 3; public static final int ONEWAY_FIELD_NUMBER = 3; - private boolean hasOneWay; - private boolean oneWay_ = false; - public boolean hasOneWay() { return hasOneWay; } - public boolean getOneWay() { return oneWay_; } + private boolean oneWay_; + public boolean hasOneWay() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public boolean getOneWay() { + return oneWay_; + } // optional .MessageProtocol message = 4; public static final int MESSAGE_FIELD_NUMBER = 4; - private boolean hasMessage; private akka.remote.protocol.RemoteProtocol.MessageProtocol message_; - public boolean hasMessage() { return hasMessage; } - public akka.remote.protocol.RemoteProtocol.MessageProtocol getMessage() { return message_; } + public boolean hasMessage() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public akka.remote.protocol.RemoteProtocol.MessageProtocol getMessage() { + return message_; + } + public akka.remote.protocol.RemoteProtocol.MessageProtocolOrBuilder getMessageOrBuilder() { + return message_; + } // optional .ExceptionProtocol exception = 5; public static final int EXCEPTION_FIELD_NUMBER = 5; - private boolean hasException; private akka.remote.protocol.RemoteProtocol.ExceptionProtocol exception_; - public boolean hasException() { return hasException; } - public akka.remote.protocol.RemoteProtocol.ExceptionProtocol getException() { return exception_; } + public boolean hasException() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + public akka.remote.protocol.RemoteProtocol.ExceptionProtocol getException() { + return exception_; + } + public akka.remote.protocol.RemoteProtocol.ExceptionProtocolOrBuilder getExceptionOrBuilder() { + return exception_; + } // optional .UuidProtocol supervisorUuid = 6; public static final int SUPERVISORUUID_FIELD_NUMBER = 6; - private boolean hasSupervisorUuid; private akka.remote.protocol.RemoteProtocol.UuidProtocol supervisorUuid_; - public boolean hasSupervisorUuid() { return hasSupervisorUuid; } - public akka.remote.protocol.RemoteProtocol.UuidProtocol getSupervisorUuid() { return supervisorUuid_; } + public boolean hasSupervisorUuid() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + public akka.remote.protocol.RemoteProtocol.UuidProtocol getSupervisorUuid() { + return supervisorUuid_; + } + public akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder getSupervisorUuidOrBuilder() { + return supervisorUuid_; + } // optional .RemoteActorRefProtocol sender = 7; public static final int SENDER_FIELD_NUMBER = 7; - private boolean hasSender; private akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol sender_; - public boolean hasSender() { return hasSender; } - public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol getSender() { return sender_; } + public boolean hasSender() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol getSender() { + return sender_; + } + public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocolOrBuilder getSenderOrBuilder() { + return sender_; + } // repeated .MetadataEntryProtocol metadata = 8; public static final int METADATA_FIELD_NUMBER = 8; - private java.util.List metadata_ = - java.util.Collections.emptyList(); + private java.util.List metadata_; public java.util.List getMetadataList() { return metadata_; } - public int getMetadataCount() { return metadata_.size(); } + public java.util.List + getMetadataOrBuilderList() { + return metadata_; + } + public int getMetadataCount() { + return metadata_.size(); + } public akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol getMetadata(int index) { return metadata_.get(index); } + public akka.remote.protocol.RemoteProtocol.MetadataEntryProtocolOrBuilder getMetadataOrBuilder( + int index) { + return metadata_.get(index); + } private void initFields() { uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); actorInfo_ = akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.getDefaultInstance(); + oneWay_ = false; message_ = akka.remote.protocol.RemoteProtocol.MessageProtocol.getDefaultInstance(); exception_ = akka.remote.protocol.RemoteProtocol.ExceptionProtocol.getDefaultInstance(); supervisorUuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); sender_ = akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance(); + metadata_ = java.util.Collections.emptyList(); } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasUuid) return false; - if (!hasActorInfo) return false; - if (!hasOneWay) return false; - if (!getUuid().isInitialized()) return false; - if (!getActorInfo().isInitialized()) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasUuid()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasActorInfo()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasOneWay()) { + memoizedIsInitialized = 0; + return false; + } + if (!getUuid().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + if (!getActorInfo().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } if (hasMessage()) { - if (!getMessage().isInitialized()) return false; + if (!getMessage().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } } if (hasException()) { - if (!getException().isInitialized()) return false; + if (!getException().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } } if (hasSupervisorUuid()) { - if (!getSupervisorUuid().isInitialized()) return false; + if (!getSupervisorUuid().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } } if (hasSender()) { - if (!getSender().isInitialized()) return false; + if (!getSender().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } } - for (akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol element : getMetadataList()) { - if (!element.isInitialized()) return false; + for (int i = 0; i < getMetadataCount(); i++) { + if (!getMetadata(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasUuid()) { - output.writeMessage(1, getUuid()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeMessage(1, uuid_); } - if (hasActorInfo()) { - output.writeMessage(2, getActorInfo()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeMessage(2, actorInfo_); } - if (hasOneWay()) { - output.writeBool(3, getOneWay()); + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeBool(3, oneWay_); } - if (hasMessage()) { - output.writeMessage(4, getMessage()); + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeMessage(4, message_); } - if (hasException()) { - output.writeMessage(5, getException()); + if (((bitField0_ & 0x00000010) == 0x00000010)) { + output.writeMessage(5, exception_); } - if (hasSupervisorUuid()) { - output.writeMessage(6, getSupervisorUuid()); + if (((bitField0_ & 0x00000020) == 0x00000020)) { + output.writeMessage(6, supervisorUuid_); } - if (hasSender()) { - output.writeMessage(7, getSender()); + if (((bitField0_ & 0x00000040) == 0x00000040)) { + output.writeMessage(7, sender_); } - for (akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol element : getMetadataList()) { - output.writeMessage(8, element); + for (int i = 0; i < metadata_.size(); i++) { + output.writeMessage(8, metadata_.get(i)); } getUnknownFields().writeTo(output); } @@ -750,43 +1246,50 @@ public final class RemoteProtocol { if (size != -1) return size; size = 0; - if (hasUuid()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(1, getUuid()); + .computeMessageSize(1, uuid_); } - if (hasActorInfo()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(2, getActorInfo()); + .computeMessageSize(2, actorInfo_); } - if (hasOneWay()) { + if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream - .computeBoolSize(3, getOneWay()); + .computeBoolSize(3, oneWay_); } - if (hasMessage()) { + if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(4, getMessage()); + .computeMessageSize(4, message_); } - if (hasException()) { + if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(5, getException()); + .computeMessageSize(5, exception_); } - if (hasSupervisorUuid()) { + if (((bitField0_ & 0x00000020) == 0x00000020)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(6, getSupervisorUuid()); + .computeMessageSize(6, supervisorUuid_); } - if (hasSender()) { + if (((bitField0_ & 0x00000040) == 0x00000040)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(7, getSender()); + .computeMessageSize(7, sender_); } - for (akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol element : getMetadataList()) { + for (int i = 0; i < metadata_.size(); i++) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(8, element); + .computeMessageSize(8, metadata_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -861,34 +1364,100 @@ public final class RemoteProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol result; - - // Construct using akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.remote.protocol.RemoteProtocol.RemoteMessageProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.internal_static_RemoteMessageProtocol_descriptor; } - protected akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.remote.protocol.RemoteProtocol.internal_static_RemoteMessageProtocol_fieldAccessorTable; + } + + // Construct using akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getUuidFieldBuilder(); + getActorInfoFieldBuilder(); + getMessageFieldBuilder(); + getExceptionFieldBuilder(); + getSupervisorUuidFieldBuilder(); + getSenderFieldBuilder(); + getMetadataFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); + super.clear(); + if (uuidBuilder_ == null) { + uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + } else { + uuidBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000001); + if (actorInfoBuilder_ == null) { + actorInfo_ = akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.getDefaultInstance(); + } else { + actorInfoBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + oneWay_ = false; + bitField0_ = (bitField0_ & ~0x00000004); + if (messageBuilder_ == null) { + message_ = akka.remote.protocol.RemoteProtocol.MessageProtocol.getDefaultInstance(); + } else { + messageBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000008); + if (exceptionBuilder_ == null) { + exception_ = akka.remote.protocol.RemoteProtocol.ExceptionProtocol.getDefaultInstance(); + } else { + exceptionBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000010); + if (supervisorUuidBuilder_ == null) { + supervisorUuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + } else { + supervisorUuidBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000020); + if (senderBuilder_ == null) { + sender_ = akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance(); + } else { + senderBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000040); + if (metadataBuilder_ == null) { + metadata_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000080); + } else { + metadataBuilder_.clear(); } - result = new akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol(); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -900,37 +1469,92 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol build() { - if (result != null && !isInitialized()) { + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol result = new akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - if (result.metadata_ != java.util.Collections.EMPTY_LIST) { - result.metadata_ = - java.util.Collections.unmodifiableList(result.metadata_); + if (uuidBuilder_ == null) { + result.uuid_ = uuid_; + } else { + result.uuid_ = uuidBuilder_.build(); } - akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol returnMe = result; - result = null; - return returnMe; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + if (actorInfoBuilder_ == null) { + result.actorInfo_ = actorInfo_; + } else { + result.actorInfo_ = actorInfoBuilder_.build(); + } + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.oneWay_ = oneWay_; + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + if (messageBuilder_ == null) { + result.message_ = message_; + } else { + result.message_ = messageBuilder_.build(); + } + if (((from_bitField0_ & 0x00000010) == 0x00000010)) { + to_bitField0_ |= 0x00000010; + } + if (exceptionBuilder_ == null) { + result.exception_ = exception_; + } else { + result.exception_ = exceptionBuilder_.build(); + } + if (((from_bitField0_ & 0x00000020) == 0x00000020)) { + to_bitField0_ |= 0x00000020; + } + if (supervisorUuidBuilder_ == null) { + result.supervisorUuid_ = supervisorUuid_; + } else { + result.supervisorUuid_ = supervisorUuidBuilder_.build(); + } + if (((from_bitField0_ & 0x00000040) == 0x00000040)) { + to_bitField0_ |= 0x00000040; + } + if (senderBuilder_ == null) { + result.sender_ = sender_; + } else { + result.sender_ = senderBuilder_.build(); + } + if (metadataBuilder_ == null) { + if (((bitField0_ & 0x00000080) == 0x00000080)) { + metadata_ = java.util.Collections.unmodifiableList(metadata_); + bitField0_ = (bitField0_ & ~0x00000080); + } + result.metadata_ = metadata_; + } else { + result.metadata_ = metadataBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -965,16 +1589,90 @@ public final class RemoteProtocol { if (other.hasSender()) { mergeSender(other.getSender()); } - if (!other.metadata_.isEmpty()) { - if (result.metadata_.isEmpty()) { - result.metadata_ = new java.util.ArrayList(); + if (metadataBuilder_ == null) { + if (!other.metadata_.isEmpty()) { + if (metadata_.isEmpty()) { + metadata_ = other.metadata_; + bitField0_ = (bitField0_ & ~0x00000080); + } else { + ensureMetadataIsMutable(); + metadata_.addAll(other.metadata_); + } + onChanged(); + } + } else { + if (!other.metadata_.isEmpty()) { + if (metadataBuilder_.isEmpty()) { + metadataBuilder_.dispose(); + metadataBuilder_ = null; + metadata_ = other.metadata_; + bitField0_ = (bitField0_ & ~0x00000080); + metadataBuilder_ = + com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? + getMetadataFieldBuilder() : null; + } else { + metadataBuilder_.addAllMessages(other.metadata_); + } } - result.metadata_.addAll(other.metadata_); } this.mergeUnknownFields(other.getUnknownFields()); return this; } + public final boolean isInitialized() { + if (!hasUuid()) { + + return false; + } + if (!hasActorInfo()) { + + return false; + } + if (!hasOneWay()) { + + return false; + } + if (!getUuid().isInitialized()) { + + return false; + } + if (!getActorInfo().isInitialized()) { + + return false; + } + if (hasMessage()) { + if (!getMessage().isInitialized()) { + + return false; + } + } + if (hasException()) { + if (!getException().isInitialized()) { + + return false; + } + } + if (hasSupervisorUuid()) { + if (!getSupervisorUuid().isInitialized()) { + + return false; + } + } + if (hasSender()) { + if (!getSender().isInitialized()) { + + return false; + } + } + for (int i = 0; i < getMetadataCount(); i++) { + if (!getMetadata(i).isInitialized()) { + + return false; + } + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -987,11 +1685,13 @@ public final class RemoteProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; @@ -1015,7 +1715,8 @@ public final class RemoteProtocol { break; } case 24: { - setOneWay(input.readBool()); + bitField0_ |= 0x00000004; + oneWay_ = input.readBool(); break; } case 34: { @@ -1064,315 +1765,783 @@ public final class RemoteProtocol { } } + private int bitField0_; // required .UuidProtocol uuid = 1; + private akka.remote.protocol.RemoteProtocol.UuidProtocol uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.UuidProtocol, akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder, akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder> uuidBuilder_; public boolean hasUuid() { - return result.hasUuid(); + return ((bitField0_ & 0x00000001) == 0x00000001); } public akka.remote.protocol.RemoteProtocol.UuidProtocol getUuid() { - return result.getUuid(); + if (uuidBuilder_ == null) { + return uuid_; + } else { + return uuidBuilder_.getMessage(); + } } public Builder setUuid(akka.remote.protocol.RemoteProtocol.UuidProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (uuidBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + uuid_ = value; + onChanged(); + } else { + uuidBuilder_.setMessage(value); } - result.hasUuid = true; - result.uuid_ = value; + bitField0_ |= 0x00000001; return this; } - public Builder setUuid(akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder builderForValue) { - result.hasUuid = true; - result.uuid_ = builderForValue.build(); + public Builder setUuid( + akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder builderForValue) { + if (uuidBuilder_ == null) { + uuid_ = builderForValue.build(); + onChanged(); + } else { + uuidBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000001; return this; } public Builder mergeUuid(akka.remote.protocol.RemoteProtocol.UuidProtocol value) { - if (result.hasUuid() && - result.uuid_ != akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance()) { - result.uuid_ = - akka.remote.protocol.RemoteProtocol.UuidProtocol.newBuilder(result.uuid_).mergeFrom(value).buildPartial(); + if (uuidBuilder_ == null) { + if (((bitField0_ & 0x00000001) == 0x00000001) && + uuid_ != akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance()) { + uuid_ = + akka.remote.protocol.RemoteProtocol.UuidProtocol.newBuilder(uuid_).mergeFrom(value).buildPartial(); + } else { + uuid_ = value; + } + onChanged(); } else { - result.uuid_ = value; + uuidBuilder_.mergeFrom(value); } - result.hasUuid = true; + bitField0_ |= 0x00000001; return this; } public Builder clearUuid() { - result.hasUuid = false; - result.uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + if (uuidBuilder_ == null) { + uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + onChanged(); + } else { + uuidBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000001); return this; } + public akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder getUuidBuilder() { + bitField0_ |= 0x00000001; + onChanged(); + return getUuidFieldBuilder().getBuilder(); + } + public akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder getUuidOrBuilder() { + if (uuidBuilder_ != null) { + return uuidBuilder_.getMessageOrBuilder(); + } else { + return uuid_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.UuidProtocol, akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder, akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder> + getUuidFieldBuilder() { + if (uuidBuilder_ == null) { + uuidBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.UuidProtocol, akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder, akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder>( + uuid_, + getParentForChildren(), + isClean()); + uuid_ = null; + } + return uuidBuilder_; + } // required .ActorInfoProtocol actorInfo = 2; + private akka.remote.protocol.RemoteProtocol.ActorInfoProtocol actorInfo_ = akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.ActorInfoProtocol, akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.Builder, akka.remote.protocol.RemoteProtocol.ActorInfoProtocolOrBuilder> actorInfoBuilder_; public boolean hasActorInfo() { - return result.hasActorInfo(); + return ((bitField0_ & 0x00000002) == 0x00000002); } public akka.remote.protocol.RemoteProtocol.ActorInfoProtocol getActorInfo() { - return result.getActorInfo(); + if (actorInfoBuilder_ == null) { + return actorInfo_; + } else { + return actorInfoBuilder_.getMessage(); + } } public Builder setActorInfo(akka.remote.protocol.RemoteProtocol.ActorInfoProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (actorInfoBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + actorInfo_ = value; + onChanged(); + } else { + actorInfoBuilder_.setMessage(value); } - result.hasActorInfo = true; - result.actorInfo_ = value; + bitField0_ |= 0x00000002; return this; } - public Builder setActorInfo(akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.Builder builderForValue) { - result.hasActorInfo = true; - result.actorInfo_ = builderForValue.build(); + public Builder setActorInfo( + akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.Builder builderForValue) { + if (actorInfoBuilder_ == null) { + actorInfo_ = builderForValue.build(); + onChanged(); + } else { + actorInfoBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000002; return this; } public Builder mergeActorInfo(akka.remote.protocol.RemoteProtocol.ActorInfoProtocol value) { - if (result.hasActorInfo() && - result.actorInfo_ != akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.getDefaultInstance()) { - result.actorInfo_ = - akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.newBuilder(result.actorInfo_).mergeFrom(value).buildPartial(); + if (actorInfoBuilder_ == null) { + if (((bitField0_ & 0x00000002) == 0x00000002) && + actorInfo_ != akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.getDefaultInstance()) { + actorInfo_ = + akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.newBuilder(actorInfo_).mergeFrom(value).buildPartial(); + } else { + actorInfo_ = value; + } + onChanged(); } else { - result.actorInfo_ = value; + actorInfoBuilder_.mergeFrom(value); } - result.hasActorInfo = true; + bitField0_ |= 0x00000002; return this; } public Builder clearActorInfo() { - result.hasActorInfo = false; - result.actorInfo_ = akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.getDefaultInstance(); + if (actorInfoBuilder_ == null) { + actorInfo_ = akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.getDefaultInstance(); + onChanged(); + } else { + actorInfoBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); return this; } + public akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.Builder getActorInfoBuilder() { + bitField0_ |= 0x00000002; + onChanged(); + return getActorInfoFieldBuilder().getBuilder(); + } + public akka.remote.protocol.RemoteProtocol.ActorInfoProtocolOrBuilder getActorInfoOrBuilder() { + if (actorInfoBuilder_ != null) { + return actorInfoBuilder_.getMessageOrBuilder(); + } else { + return actorInfo_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.ActorInfoProtocol, akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.Builder, akka.remote.protocol.RemoteProtocol.ActorInfoProtocolOrBuilder> + getActorInfoFieldBuilder() { + if (actorInfoBuilder_ == null) { + actorInfoBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.ActorInfoProtocol, akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.Builder, akka.remote.protocol.RemoteProtocol.ActorInfoProtocolOrBuilder>( + actorInfo_, + getParentForChildren(), + isClean()); + actorInfo_ = null; + } + return actorInfoBuilder_; + } // required bool oneWay = 3; + private boolean oneWay_ ; public boolean hasOneWay() { - return result.hasOneWay(); + return ((bitField0_ & 0x00000004) == 0x00000004); } public boolean getOneWay() { - return result.getOneWay(); + return oneWay_; } public Builder setOneWay(boolean value) { - result.hasOneWay = true; - result.oneWay_ = value; + bitField0_ |= 0x00000004; + oneWay_ = value; + onChanged(); return this; } public Builder clearOneWay() { - result.hasOneWay = false; - result.oneWay_ = false; + bitField0_ = (bitField0_ & ~0x00000004); + oneWay_ = false; + onChanged(); return this; } // optional .MessageProtocol message = 4; + private akka.remote.protocol.RemoteProtocol.MessageProtocol message_ = akka.remote.protocol.RemoteProtocol.MessageProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.MessageProtocol, akka.remote.protocol.RemoteProtocol.MessageProtocol.Builder, akka.remote.protocol.RemoteProtocol.MessageProtocolOrBuilder> messageBuilder_; public boolean hasMessage() { - return result.hasMessage(); + return ((bitField0_ & 0x00000008) == 0x00000008); } public akka.remote.protocol.RemoteProtocol.MessageProtocol getMessage() { - return result.getMessage(); + if (messageBuilder_ == null) { + return message_; + } else { + return messageBuilder_.getMessage(); + } } public Builder setMessage(akka.remote.protocol.RemoteProtocol.MessageProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (messageBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + message_ = value; + onChanged(); + } else { + messageBuilder_.setMessage(value); } - result.hasMessage = true; - result.message_ = value; + bitField0_ |= 0x00000008; return this; } - public Builder setMessage(akka.remote.protocol.RemoteProtocol.MessageProtocol.Builder builderForValue) { - result.hasMessage = true; - result.message_ = builderForValue.build(); + public Builder setMessage( + akka.remote.protocol.RemoteProtocol.MessageProtocol.Builder builderForValue) { + if (messageBuilder_ == null) { + message_ = builderForValue.build(); + onChanged(); + } else { + messageBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000008; return this; } public Builder mergeMessage(akka.remote.protocol.RemoteProtocol.MessageProtocol value) { - if (result.hasMessage() && - result.message_ != akka.remote.protocol.RemoteProtocol.MessageProtocol.getDefaultInstance()) { - result.message_ = - akka.remote.protocol.RemoteProtocol.MessageProtocol.newBuilder(result.message_).mergeFrom(value).buildPartial(); + if (messageBuilder_ == null) { + if (((bitField0_ & 0x00000008) == 0x00000008) && + message_ != akka.remote.protocol.RemoteProtocol.MessageProtocol.getDefaultInstance()) { + message_ = + akka.remote.protocol.RemoteProtocol.MessageProtocol.newBuilder(message_).mergeFrom(value).buildPartial(); + } else { + message_ = value; + } + onChanged(); } else { - result.message_ = value; + messageBuilder_.mergeFrom(value); } - result.hasMessage = true; + bitField0_ |= 0x00000008; return this; } public Builder clearMessage() { - result.hasMessage = false; - result.message_ = akka.remote.protocol.RemoteProtocol.MessageProtocol.getDefaultInstance(); + if (messageBuilder_ == null) { + message_ = akka.remote.protocol.RemoteProtocol.MessageProtocol.getDefaultInstance(); + onChanged(); + } else { + messageBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000008); return this; } + public akka.remote.protocol.RemoteProtocol.MessageProtocol.Builder getMessageBuilder() { + bitField0_ |= 0x00000008; + onChanged(); + return getMessageFieldBuilder().getBuilder(); + } + public akka.remote.protocol.RemoteProtocol.MessageProtocolOrBuilder getMessageOrBuilder() { + if (messageBuilder_ != null) { + return messageBuilder_.getMessageOrBuilder(); + } else { + return message_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.MessageProtocol, akka.remote.protocol.RemoteProtocol.MessageProtocol.Builder, akka.remote.protocol.RemoteProtocol.MessageProtocolOrBuilder> + getMessageFieldBuilder() { + if (messageBuilder_ == null) { + messageBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.MessageProtocol, akka.remote.protocol.RemoteProtocol.MessageProtocol.Builder, akka.remote.protocol.RemoteProtocol.MessageProtocolOrBuilder>( + message_, + getParentForChildren(), + isClean()); + message_ = null; + } + return messageBuilder_; + } // optional .ExceptionProtocol exception = 5; + private akka.remote.protocol.RemoteProtocol.ExceptionProtocol exception_ = akka.remote.protocol.RemoteProtocol.ExceptionProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.ExceptionProtocol, akka.remote.protocol.RemoteProtocol.ExceptionProtocol.Builder, akka.remote.protocol.RemoteProtocol.ExceptionProtocolOrBuilder> exceptionBuilder_; public boolean hasException() { - return result.hasException(); + return ((bitField0_ & 0x00000010) == 0x00000010); } public akka.remote.protocol.RemoteProtocol.ExceptionProtocol getException() { - return result.getException(); + if (exceptionBuilder_ == null) { + return exception_; + } else { + return exceptionBuilder_.getMessage(); + } } public Builder setException(akka.remote.protocol.RemoteProtocol.ExceptionProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (exceptionBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + exception_ = value; + onChanged(); + } else { + exceptionBuilder_.setMessage(value); } - result.hasException = true; - result.exception_ = value; + bitField0_ |= 0x00000010; return this; } - public Builder setException(akka.remote.protocol.RemoteProtocol.ExceptionProtocol.Builder builderForValue) { - result.hasException = true; - result.exception_ = builderForValue.build(); + public Builder setException( + akka.remote.protocol.RemoteProtocol.ExceptionProtocol.Builder builderForValue) { + if (exceptionBuilder_ == null) { + exception_ = builderForValue.build(); + onChanged(); + } else { + exceptionBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000010; return this; } public Builder mergeException(akka.remote.protocol.RemoteProtocol.ExceptionProtocol value) { - if (result.hasException() && - result.exception_ != akka.remote.protocol.RemoteProtocol.ExceptionProtocol.getDefaultInstance()) { - result.exception_ = - akka.remote.protocol.RemoteProtocol.ExceptionProtocol.newBuilder(result.exception_).mergeFrom(value).buildPartial(); + if (exceptionBuilder_ == null) { + if (((bitField0_ & 0x00000010) == 0x00000010) && + exception_ != akka.remote.protocol.RemoteProtocol.ExceptionProtocol.getDefaultInstance()) { + exception_ = + akka.remote.protocol.RemoteProtocol.ExceptionProtocol.newBuilder(exception_).mergeFrom(value).buildPartial(); + } else { + exception_ = value; + } + onChanged(); } else { - result.exception_ = value; + exceptionBuilder_.mergeFrom(value); } - result.hasException = true; + bitField0_ |= 0x00000010; return this; } public Builder clearException() { - result.hasException = false; - result.exception_ = akka.remote.protocol.RemoteProtocol.ExceptionProtocol.getDefaultInstance(); + if (exceptionBuilder_ == null) { + exception_ = akka.remote.protocol.RemoteProtocol.ExceptionProtocol.getDefaultInstance(); + onChanged(); + } else { + exceptionBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000010); return this; } + public akka.remote.protocol.RemoteProtocol.ExceptionProtocol.Builder getExceptionBuilder() { + bitField0_ |= 0x00000010; + onChanged(); + return getExceptionFieldBuilder().getBuilder(); + } + public akka.remote.protocol.RemoteProtocol.ExceptionProtocolOrBuilder getExceptionOrBuilder() { + if (exceptionBuilder_ != null) { + return exceptionBuilder_.getMessageOrBuilder(); + } else { + return exception_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.ExceptionProtocol, akka.remote.protocol.RemoteProtocol.ExceptionProtocol.Builder, akka.remote.protocol.RemoteProtocol.ExceptionProtocolOrBuilder> + getExceptionFieldBuilder() { + if (exceptionBuilder_ == null) { + exceptionBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.ExceptionProtocol, akka.remote.protocol.RemoteProtocol.ExceptionProtocol.Builder, akka.remote.protocol.RemoteProtocol.ExceptionProtocolOrBuilder>( + exception_, + getParentForChildren(), + isClean()); + exception_ = null; + } + return exceptionBuilder_; + } // optional .UuidProtocol supervisorUuid = 6; + private akka.remote.protocol.RemoteProtocol.UuidProtocol supervisorUuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.UuidProtocol, akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder, akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder> supervisorUuidBuilder_; public boolean hasSupervisorUuid() { - return result.hasSupervisorUuid(); + return ((bitField0_ & 0x00000020) == 0x00000020); } public akka.remote.protocol.RemoteProtocol.UuidProtocol getSupervisorUuid() { - return result.getSupervisorUuid(); + if (supervisorUuidBuilder_ == null) { + return supervisorUuid_; + } else { + return supervisorUuidBuilder_.getMessage(); + } } public Builder setSupervisorUuid(akka.remote.protocol.RemoteProtocol.UuidProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (supervisorUuidBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + supervisorUuid_ = value; + onChanged(); + } else { + supervisorUuidBuilder_.setMessage(value); } - result.hasSupervisorUuid = true; - result.supervisorUuid_ = value; + bitField0_ |= 0x00000020; return this; } - public Builder setSupervisorUuid(akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder builderForValue) { - result.hasSupervisorUuid = true; - result.supervisorUuid_ = builderForValue.build(); + public Builder setSupervisorUuid( + akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder builderForValue) { + if (supervisorUuidBuilder_ == null) { + supervisorUuid_ = builderForValue.build(); + onChanged(); + } else { + supervisorUuidBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000020; return this; } public Builder mergeSupervisorUuid(akka.remote.protocol.RemoteProtocol.UuidProtocol value) { - if (result.hasSupervisorUuid() && - result.supervisorUuid_ != akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance()) { - result.supervisorUuid_ = - akka.remote.protocol.RemoteProtocol.UuidProtocol.newBuilder(result.supervisorUuid_).mergeFrom(value).buildPartial(); + if (supervisorUuidBuilder_ == null) { + if (((bitField0_ & 0x00000020) == 0x00000020) && + supervisorUuid_ != akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance()) { + supervisorUuid_ = + akka.remote.protocol.RemoteProtocol.UuidProtocol.newBuilder(supervisorUuid_).mergeFrom(value).buildPartial(); + } else { + supervisorUuid_ = value; + } + onChanged(); } else { - result.supervisorUuid_ = value; + supervisorUuidBuilder_.mergeFrom(value); } - result.hasSupervisorUuid = true; + bitField0_ |= 0x00000020; return this; } public Builder clearSupervisorUuid() { - result.hasSupervisorUuid = false; - result.supervisorUuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + if (supervisorUuidBuilder_ == null) { + supervisorUuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + onChanged(); + } else { + supervisorUuidBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000020); return this; } + public akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder getSupervisorUuidBuilder() { + bitField0_ |= 0x00000020; + onChanged(); + return getSupervisorUuidFieldBuilder().getBuilder(); + } + public akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder getSupervisorUuidOrBuilder() { + if (supervisorUuidBuilder_ != null) { + return supervisorUuidBuilder_.getMessageOrBuilder(); + } else { + return supervisorUuid_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.UuidProtocol, akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder, akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder> + getSupervisorUuidFieldBuilder() { + if (supervisorUuidBuilder_ == null) { + supervisorUuidBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.UuidProtocol, akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder, akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder>( + supervisorUuid_, + getParentForChildren(), + isClean()); + supervisorUuid_ = null; + } + return supervisorUuidBuilder_; + } // optional .RemoteActorRefProtocol sender = 7; + private akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol sender_ = akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol, akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocolOrBuilder> senderBuilder_; public boolean hasSender() { - return result.hasSender(); + return ((bitField0_ & 0x00000040) == 0x00000040); } public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol getSender() { - return result.getSender(); + if (senderBuilder_ == null) { + return sender_; + } else { + return senderBuilder_.getMessage(); + } } public Builder setSender(akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (senderBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + sender_ = value; + onChanged(); + } else { + senderBuilder_.setMessage(value); } - result.hasSender = true; - result.sender_ = value; + bitField0_ |= 0x00000040; return this; } - public Builder setSender(akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.Builder builderForValue) { - result.hasSender = true; - result.sender_ = builderForValue.build(); + public Builder setSender( + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.Builder builderForValue) { + if (senderBuilder_ == null) { + sender_ = builderForValue.build(); + onChanged(); + } else { + senderBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000040; return this; } public Builder mergeSender(akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol value) { - if (result.hasSender() && - result.sender_ != akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance()) { - result.sender_ = - akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.newBuilder(result.sender_).mergeFrom(value).buildPartial(); + if (senderBuilder_ == null) { + if (((bitField0_ & 0x00000040) == 0x00000040) && + sender_ != akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance()) { + sender_ = + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.newBuilder(sender_).mergeFrom(value).buildPartial(); + } else { + sender_ = value; + } + onChanged(); } else { - result.sender_ = value; + senderBuilder_.mergeFrom(value); } - result.hasSender = true; + bitField0_ |= 0x00000040; return this; } public Builder clearSender() { - result.hasSender = false; - result.sender_ = akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance(); + if (senderBuilder_ == null) { + sender_ = akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance(); + onChanged(); + } else { + senderBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000040); return this; } + public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.Builder getSenderBuilder() { + bitField0_ |= 0x00000040; + onChanged(); + return getSenderFieldBuilder().getBuilder(); + } + public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocolOrBuilder getSenderOrBuilder() { + if (senderBuilder_ != null) { + return senderBuilder_.getMessageOrBuilder(); + } else { + return sender_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol, akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocolOrBuilder> + getSenderFieldBuilder() { + if (senderBuilder_ == null) { + senderBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol, akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocolOrBuilder>( + sender_, + getParentForChildren(), + isClean()); + sender_ = null; + } + return senderBuilder_; + } // repeated .MetadataEntryProtocol metadata = 8; + private java.util.List metadata_ = + java.util.Collections.emptyList(); + private void ensureMetadataIsMutable() { + if (!((bitField0_ & 0x00000080) == 0x00000080)) { + metadata_ = new java.util.ArrayList(metadata_); + bitField0_ |= 0x00000080; + } + } + + private com.google.protobuf.RepeatedFieldBuilder< + akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol, akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.Builder, akka.remote.protocol.RemoteProtocol.MetadataEntryProtocolOrBuilder> metadataBuilder_; + public java.util.List getMetadataList() { - return java.util.Collections.unmodifiableList(result.metadata_); + if (metadataBuilder_ == null) { + return java.util.Collections.unmodifiableList(metadata_); + } else { + return metadataBuilder_.getMessageList(); + } } public int getMetadataCount() { - return result.getMetadataCount(); + if (metadataBuilder_ == null) { + return metadata_.size(); + } else { + return metadataBuilder_.getCount(); + } } public akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol getMetadata(int index) { - return result.getMetadata(index); - } - public Builder setMetadata(int index, akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (metadataBuilder_ == null) { + return metadata_.get(index); + } else { + return metadataBuilder_.getMessage(index); + } + } + public Builder setMetadata( + int index, akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol value) { + if (metadataBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureMetadataIsMutable(); + metadata_.set(index, value); + onChanged(); + } else { + metadataBuilder_.setMessage(index, value); } - result.metadata_.set(index, value); return this; } - public Builder setMetadata(int index, akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.Builder builderForValue) { - result.metadata_.set(index, builderForValue.build()); + public Builder setMetadata( + int index, akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.Builder builderForValue) { + if (metadataBuilder_ == null) { + ensureMetadataIsMutable(); + metadata_.set(index, builderForValue.build()); + onChanged(); + } else { + metadataBuilder_.setMessage(index, builderForValue.build()); + } return this; } public Builder addMetadata(akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (metadataBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureMetadataIsMutable(); + metadata_.add(value); + onChanged(); + } else { + metadataBuilder_.addMessage(value); } - if (result.metadata_.isEmpty()) { - result.metadata_ = new java.util.ArrayList(); - } - result.metadata_.add(value); return this; } - public Builder addMetadata(akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.Builder builderForValue) { - if (result.metadata_.isEmpty()) { - result.metadata_ = new java.util.ArrayList(); + public Builder addMetadata( + int index, akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol value) { + if (metadataBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureMetadataIsMutable(); + metadata_.add(index, value); + onChanged(); + } else { + metadataBuilder_.addMessage(index, value); + } + return this; + } + public Builder addMetadata( + akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.Builder builderForValue) { + if (metadataBuilder_ == null) { + ensureMetadataIsMutable(); + metadata_.add(builderForValue.build()); + onChanged(); + } else { + metadataBuilder_.addMessage(builderForValue.build()); + } + return this; + } + public Builder addMetadata( + int index, akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.Builder builderForValue) { + if (metadataBuilder_ == null) { + ensureMetadataIsMutable(); + metadata_.add(index, builderForValue.build()); + onChanged(); + } else { + metadataBuilder_.addMessage(index, builderForValue.build()); } - result.metadata_.add(builderForValue.build()); return this; } public Builder addAllMetadata( java.lang.Iterable values) { - if (result.metadata_.isEmpty()) { - result.metadata_ = new java.util.ArrayList(); + if (metadataBuilder_ == null) { + ensureMetadataIsMutable(); + super.addAll(values, metadata_); + onChanged(); + } else { + metadataBuilder_.addAllMessages(values); } - super.addAll(values, result.metadata_); return this; } public Builder clearMetadata() { - result.metadata_ = java.util.Collections.emptyList(); + if (metadataBuilder_ == null) { + metadata_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000080); + onChanged(); + } else { + metadataBuilder_.clear(); + } return this; } + public Builder removeMetadata(int index) { + if (metadataBuilder_ == null) { + ensureMetadataIsMutable(); + metadata_.remove(index); + onChanged(); + } else { + metadataBuilder_.remove(index); + } + return this; + } + public akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.Builder getMetadataBuilder( + int index) { + return getMetadataFieldBuilder().getBuilder(index); + } + public akka.remote.protocol.RemoteProtocol.MetadataEntryProtocolOrBuilder getMetadataOrBuilder( + int index) { + if (metadataBuilder_ == null) { + return metadata_.get(index); } else { + return metadataBuilder_.getMessageOrBuilder(index); + } + } + public java.util.List + getMetadataOrBuilderList() { + if (metadataBuilder_ != null) { + return metadataBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(metadata_); + } + } + public akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.Builder addMetadataBuilder() { + return getMetadataFieldBuilder().addBuilder( + akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.getDefaultInstance()); + } + public akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.Builder addMetadataBuilder( + int index) { + return getMetadataFieldBuilder().addBuilder( + index, akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.getDefaultInstance()); + } + public java.util.List + getMetadataBuilderList() { + return getMetadataFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilder< + akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol, akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.Builder, akka.remote.protocol.RemoteProtocol.MetadataEntryProtocolOrBuilder> + getMetadataFieldBuilder() { + if (metadataBuilder_ == null) { + metadataBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol, akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.Builder, akka.remote.protocol.RemoteProtocol.MetadataEntryProtocolOrBuilder>( + metadata_, + ((bitField0_ & 0x00000080) == 0x00000080), + getParentForChildren(), + isClean()); + metadata_ = null; + } + return metadataBuilder_; + } // @@protoc_insertion_point(builder_scope:RemoteMessageProtocol) } static { defaultInstance = new RemoteMessageProtocol(true); - akka.remote.protocol.RemoteProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:RemoteMessageProtocol) } + public interface RemoteControlProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional string cookie = 1; + boolean hasCookie(); + String getCookie(); + + // required .CommandType commandType = 2; + boolean hasCommandType(); + akka.remote.protocol.RemoteProtocol.CommandType getCommandType(); + } public static final class RemoteControlProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements RemoteControlProtocolOrBuilder { // Use RemoteControlProtocol.newBuilder() to construct. - private RemoteControlProtocol() { - initFields(); + private RemoteControlProtocol(Builder builder) { + super(builder); } private RemoteControlProtocol(boolean noInit) {} @@ -1395,36 +2564,74 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.internal_static_RemoteControlProtocol_fieldAccessorTable; } + private int bitField0_; // optional string cookie = 1; public static final int COOKIE_FIELD_NUMBER = 1; - private boolean hasCookie; - private java.lang.String cookie_ = ""; - public boolean hasCookie() { return hasCookie; } - public java.lang.String getCookie() { return cookie_; } + private java.lang.Object cookie_; + public boolean hasCookie() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public String getCookie() { + java.lang.Object ref = cookie_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + cookie_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getCookieBytes() { + java.lang.Object ref = cookie_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + cookie_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } // required .CommandType commandType = 2; public static final int COMMANDTYPE_FIELD_NUMBER = 2; - private boolean hasCommandType; private akka.remote.protocol.RemoteProtocol.CommandType commandType_; - public boolean hasCommandType() { return hasCommandType; } - public akka.remote.protocol.RemoteProtocol.CommandType getCommandType() { return commandType_; } + public boolean hasCommandType() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public akka.remote.protocol.RemoteProtocol.CommandType getCommandType() { + return commandType_; + } private void initFields() { + cookie_ = ""; commandType_ = akka.remote.protocol.RemoteProtocol.CommandType.CONNECT; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasCommandType) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasCommandType()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasCookie()) { - output.writeString(1, getCookie()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeBytes(1, getCookieBytes()); } - if (hasCommandType()) { - output.writeEnum(2, getCommandType().getNumber()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeEnum(2, commandType_.getNumber()); } getUnknownFields().writeTo(output); } @@ -1435,19 +2642,26 @@ public final class RemoteProtocol { if (size != -1) return size; size = 0; - if (hasCookie()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(1, getCookie()); + .computeBytesSize(1, getCookieBytes()); } - if (hasCommandType()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeEnumSize(2, getCommandType().getNumber()); + .computeEnumSize(2, commandType_.getNumber()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.remote.protocol.RemoteProtocol.RemoteControlProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -1522,34 +2736,53 @@ public final class RemoteProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.remote.protocol.RemoteProtocol.RemoteControlProtocol result; - - // Construct using akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.remote.protocol.RemoteProtocol.RemoteControlProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.remote.protocol.RemoteProtocol.RemoteControlProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.internal_static_RemoteControlProtocol_descriptor; } - protected akka.remote.protocol.RemoteProtocol.RemoteControlProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.remote.protocol.RemoteProtocol.internal_static_RemoteControlProtocol_fieldAccessorTable; + } + + // Construct using akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); - } - result = new akka.remote.protocol.RemoteProtocol.RemoteControlProtocol(); + super.clear(); + cookie_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + commandType_ = akka.remote.protocol.RemoteProtocol.CommandType.CONNECT; + bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -1561,33 +2794,39 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.RemoteControlProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.remote.protocol.RemoteProtocol.RemoteControlProtocol build() { - if (result != null && !isInitialized()) { + akka.remote.protocol.RemoteProtocol.RemoteControlProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.remote.protocol.RemoteProtocol.RemoteControlProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.remote.protocol.RemoteProtocol.RemoteControlProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.remote.protocol.RemoteProtocol.RemoteControlProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.remote.protocol.RemoteProtocol.RemoteControlProtocol result = new akka.remote.protocol.RemoteProtocol.RemoteControlProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.remote.protocol.RemoteProtocol.RemoteControlProtocol returnMe = result; - result = null; - return returnMe; + result.cookie_ = cookie_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.commandType_ = commandType_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -1611,6 +2850,14 @@ public final class RemoteProtocol { return this; } + public final boolean isInitialized() { + if (!hasCommandType()) { + + return false; + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -1623,17 +2870,20 @@ public final class RemoteProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; } case 10: { - setCookie(input.readString()); + bitField0_ |= 0x00000001; + cookie_ = input.readBytes(); break; } case 16: { @@ -1642,7 +2892,8 @@ public final class RemoteProtocol { if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { - setCommandType(value); + bitField0_ |= 0x00000002; + commandType_ = value; } break; } @@ -1650,46 +2901,65 @@ public final class RemoteProtocol { } } + private int bitField0_; // optional string cookie = 1; + private java.lang.Object cookie_ = ""; public boolean hasCookie() { - return result.hasCookie(); + return ((bitField0_ & 0x00000001) == 0x00000001); } - public java.lang.String getCookie() { - return result.getCookie(); + public String getCookie() { + java.lang.Object ref = cookie_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + cookie_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setCookie(java.lang.String value) { + public Builder setCookie(String value) { if (value == null) { throw new NullPointerException(); } - result.hasCookie = true; - result.cookie_ = value; + bitField0_ |= 0x00000001; + cookie_ = value; + onChanged(); return this; } public Builder clearCookie() { - result.hasCookie = false; - result.cookie_ = getDefaultInstance().getCookie(); + bitField0_ = (bitField0_ & ~0x00000001); + cookie_ = getDefaultInstance().getCookie(); + onChanged(); return this; } + void setCookie(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000001; + cookie_ = value; + onChanged(); + } // required .CommandType commandType = 2; + private akka.remote.protocol.RemoteProtocol.CommandType commandType_ = akka.remote.protocol.RemoteProtocol.CommandType.CONNECT; public boolean hasCommandType() { - return result.hasCommandType(); + return ((bitField0_ & 0x00000002) == 0x00000002); } public akka.remote.protocol.RemoteProtocol.CommandType getCommandType() { - return result.getCommandType(); + return commandType_; } public Builder setCommandType(akka.remote.protocol.RemoteProtocol.CommandType value) { if (value == null) { throw new NullPointerException(); } - result.hasCommandType = true; - result.commandType_ = value; + bitField0_ |= 0x00000002; + commandType_ = value; + onChanged(); return this; } public Builder clearCommandType() { - result.hasCommandType = false; - result.commandType_ = akka.remote.protocol.RemoteProtocol.CommandType.CONNECT; + bitField0_ = (bitField0_ & ~0x00000002); + commandType_ = akka.remote.protocol.RemoteProtocol.CommandType.CONNECT; + onChanged(); return this; } @@ -1698,18 +2968,33 @@ public final class RemoteProtocol { static { defaultInstance = new RemoteControlProtocol(true); - akka.remote.protocol.RemoteProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:RemoteControlProtocol) } + public interface RemoteActorRefProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required string address = 1; + boolean hasAddress(); + String getAddress(); + + // required bytes inetSocketAddress = 2; + boolean hasInetSocketAddress(); + com.google.protobuf.ByteString getInetSocketAddress(); + + // optional uint64 timeout = 3; + boolean hasTimeout(); + long getTimeout(); + } public static final class RemoteActorRefProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements RemoteActorRefProtocolOrBuilder { // Use RemoteActorRefProtocol.newBuilder() to construct. - private RemoteActorRefProtocol() { - initFields(); + private RemoteActorRefProtocol(Builder builder) { + super(builder); } private RemoteActorRefProtocol(boolean noInit) {} @@ -1732,46 +3017,92 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.internal_static_RemoteActorRefProtocol_fieldAccessorTable; } + private int bitField0_; // required string address = 1; public static final int ADDRESS_FIELD_NUMBER = 1; - private boolean hasAddress; - private java.lang.String address_ = ""; - public boolean hasAddress() { return hasAddress; } - public java.lang.String getAddress() { return address_; } + private java.lang.Object address_; + public boolean hasAddress() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public String getAddress() { + java.lang.Object ref = address_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + address_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getAddressBytes() { + java.lang.Object ref = address_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + address_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } // required bytes inetSocketAddress = 2; public static final int INETSOCKETADDRESS_FIELD_NUMBER = 2; - private boolean hasInetSocketAddress; - private com.google.protobuf.ByteString inetSocketAddress_ = com.google.protobuf.ByteString.EMPTY; - public boolean hasInetSocketAddress() { return hasInetSocketAddress; } - public com.google.protobuf.ByteString getInetSocketAddress() { return inetSocketAddress_; } + private com.google.protobuf.ByteString inetSocketAddress_; + public boolean hasInetSocketAddress() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.google.protobuf.ByteString getInetSocketAddress() { + return inetSocketAddress_; + } // optional uint64 timeout = 3; public static final int TIMEOUT_FIELD_NUMBER = 3; - private boolean hasTimeout; - private long timeout_ = 0L; - public boolean hasTimeout() { return hasTimeout; } - public long getTimeout() { return timeout_; } + private long timeout_; + public boolean hasTimeout() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public long getTimeout() { + return timeout_; + } private void initFields() { + address_ = ""; + inetSocketAddress_ = com.google.protobuf.ByteString.EMPTY; + timeout_ = 0L; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasAddress) return false; - if (!hasInetSocketAddress) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasAddress()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasInetSocketAddress()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasAddress()) { - output.writeString(1, getAddress()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeBytes(1, getAddressBytes()); } - if (hasInetSocketAddress()) { - output.writeBytes(2, getInetSocketAddress()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, inetSocketAddress_); } - if (hasTimeout()) { - output.writeUInt64(3, getTimeout()); + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeUInt64(3, timeout_); } getUnknownFields().writeTo(output); } @@ -1782,23 +3113,30 @@ public final class RemoteProtocol { if (size != -1) return size; size = 0; - if (hasAddress()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(1, getAddress()); + .computeBytesSize(1, getAddressBytes()); } - if (hasInetSocketAddress()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeBytesSize(2, getInetSocketAddress()); + .computeBytesSize(2, inetSocketAddress_); } - if (hasTimeout()) { + if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream - .computeUInt64Size(3, getTimeout()); + .computeUInt64Size(3, timeout_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -1873,34 +3211,55 @@ public final class RemoteProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol result; - - // Construct using akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.internal_static_RemoteActorRefProtocol_descriptor; } - protected akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.remote.protocol.RemoteProtocol.internal_static_RemoteActorRefProtocol_fieldAccessorTable; + } + + // Construct using akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); - } - result = new akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol(); + super.clear(); + address_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + inetSocketAddress_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000002); + timeout_ = 0L; + bitField0_ = (bitField0_ & ~0x00000004); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -1912,33 +3271,43 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol build() { - if (result != null && !isInitialized()) { + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol result = new akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol returnMe = result; - result = null; - return returnMe; + result.address_ = address_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.inetSocketAddress_ = inetSocketAddress_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.timeout_ = timeout_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -1965,6 +3334,18 @@ public final class RemoteProtocol { return this; } + public final boolean isInitialized() { + if (!hasAddress()) { + + return false; + } + if (!hasInetSocketAddress()) { + + return false; + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -1977,89 +3358,116 @@ public final class RemoteProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; } case 10: { - setAddress(input.readString()); + bitField0_ |= 0x00000001; + address_ = input.readBytes(); break; } case 18: { - setInetSocketAddress(input.readBytes()); + bitField0_ |= 0x00000002; + inetSocketAddress_ = input.readBytes(); break; } case 24: { - setTimeout(input.readUInt64()); + bitField0_ |= 0x00000004; + timeout_ = input.readUInt64(); break; } } } } + private int bitField0_; // required string address = 1; + private java.lang.Object address_ = ""; public boolean hasAddress() { - return result.hasAddress(); + return ((bitField0_ & 0x00000001) == 0x00000001); } - public java.lang.String getAddress() { - return result.getAddress(); + public String getAddress() { + java.lang.Object ref = address_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + address_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setAddress(java.lang.String value) { + public Builder setAddress(String value) { if (value == null) { throw new NullPointerException(); } - result.hasAddress = true; - result.address_ = value; + bitField0_ |= 0x00000001; + address_ = value; + onChanged(); return this; } public Builder clearAddress() { - result.hasAddress = false; - result.address_ = getDefaultInstance().getAddress(); + bitField0_ = (bitField0_ & ~0x00000001); + address_ = getDefaultInstance().getAddress(); + onChanged(); return this; } + void setAddress(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000001; + address_ = value; + onChanged(); + } // required bytes inetSocketAddress = 2; + private com.google.protobuf.ByteString inetSocketAddress_ = com.google.protobuf.ByteString.EMPTY; public boolean hasInetSocketAddress() { - return result.hasInetSocketAddress(); + return ((bitField0_ & 0x00000002) == 0x00000002); } public com.google.protobuf.ByteString getInetSocketAddress() { - return result.getInetSocketAddress(); + return inetSocketAddress_; } public Builder setInetSocketAddress(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } - result.hasInetSocketAddress = true; - result.inetSocketAddress_ = value; + bitField0_ |= 0x00000002; + inetSocketAddress_ = value; + onChanged(); return this; } public Builder clearInetSocketAddress() { - result.hasInetSocketAddress = false; - result.inetSocketAddress_ = getDefaultInstance().getInetSocketAddress(); + bitField0_ = (bitField0_ & ~0x00000002); + inetSocketAddress_ = getDefaultInstance().getInetSocketAddress(); + onChanged(); return this; } // optional uint64 timeout = 3; + private long timeout_ ; public boolean hasTimeout() { - return result.hasTimeout(); + return ((bitField0_ & 0x00000004) == 0x00000004); } public long getTimeout() { - return result.getTimeout(); + return timeout_; } public Builder setTimeout(long value) { - result.hasTimeout = true; - result.timeout_ = value; + bitField0_ |= 0x00000004; + timeout_ = value; + onChanged(); return this; } public Builder clearTimeout() { - result.hasTimeout = false; - result.timeout_ = 0L; + bitField0_ = (bitField0_ & ~0x00000004); + timeout_ = 0L; + onChanged(); return this; } @@ -2068,18 +3476,82 @@ public final class RemoteProtocol { static { defaultInstance = new RemoteActorRefProtocol(true); - akka.remote.protocol.RemoteProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:RemoteActorRefProtocol) } + public interface SerializedActorRefProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required .UuidProtocol uuid = 1; + boolean hasUuid(); + akka.remote.protocol.RemoteProtocol.UuidProtocol getUuid(); + akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder getUuidOrBuilder(); + + // required string address = 2; + boolean hasAddress(); + String getAddress(); + + // required string actorClassname = 3; + boolean hasActorClassname(); + String getActorClassname(); + + // optional bytes actorInstance = 4; + boolean hasActorInstance(); + com.google.protobuf.ByteString getActorInstance(); + + // optional string serializerClassname = 5; + boolean hasSerializerClassname(); + String getSerializerClassname(); + + // optional uint64 timeout = 6; + boolean hasTimeout(); + long getTimeout(); + + // optional uint64 receiveTimeout = 7; + boolean hasReceiveTimeout(); + long getReceiveTimeout(); + + // optional .LifeCycleProtocol lifeCycle = 8; + boolean hasLifeCycle(); + akka.remote.protocol.RemoteProtocol.LifeCycleProtocol getLifeCycle(); + akka.remote.protocol.RemoteProtocol.LifeCycleProtocolOrBuilder getLifeCycleOrBuilder(); + + // optional .RemoteActorRefProtocol supervisor = 9; + boolean hasSupervisor(); + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol getSupervisor(); + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocolOrBuilder getSupervisorOrBuilder(); + + // optional bytes hotswapStack = 10; + boolean hasHotswapStack(); + com.google.protobuf.ByteString getHotswapStack(); + + // optional .ReplicationStorageType replicationStorage = 11; + boolean hasReplicationStorage(); + akka.remote.protocol.RemoteProtocol.ReplicationStorageType getReplicationStorage(); + + // optional .ReplicationStrategyType replicationStrategy = 12; + boolean hasReplicationStrategy(); + akka.remote.protocol.RemoteProtocol.ReplicationStrategyType getReplicationStrategy(); + + // repeated .RemoteMessageProtocol messages = 13; + java.util.List + getMessagesList(); + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol getMessages(int index); + int getMessagesCount(); + java.util.List + getMessagesOrBuilderList(); + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocolOrBuilder getMessagesOrBuilder( + int index); + } public static final class SerializedActorRefProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements SerializedActorRefProtocolOrBuilder { // Use SerializedActorRefProtocol.newBuilder() to construct. - private SerializedActorRefProtocol() { - initFields(); + private SerializedActorRefProtocol(Builder builder) { + super(builder); } private SerializedActorRefProtocol(boolean noInit) {} @@ -2102,145 +3574,322 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.internal_static_SerializedActorRefProtocol_fieldAccessorTable; } + private int bitField0_; // required .UuidProtocol uuid = 1; public static final int UUID_FIELD_NUMBER = 1; - private boolean hasUuid; private akka.remote.protocol.RemoteProtocol.UuidProtocol uuid_; - public boolean hasUuid() { return hasUuid; } - public akka.remote.protocol.RemoteProtocol.UuidProtocol getUuid() { return uuid_; } + public boolean hasUuid() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public akka.remote.protocol.RemoteProtocol.UuidProtocol getUuid() { + return uuid_; + } + public akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder getUuidOrBuilder() { + return uuid_; + } // required string address = 2; public static final int ADDRESS_FIELD_NUMBER = 2; - private boolean hasAddress; - private java.lang.String address_ = ""; - public boolean hasAddress() { return hasAddress; } - public java.lang.String getAddress() { return address_; } + private java.lang.Object address_; + public boolean hasAddress() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public String getAddress() { + java.lang.Object ref = address_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + address_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getAddressBytes() { + java.lang.Object ref = address_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + address_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } // required string actorClassname = 3; public static final int ACTORCLASSNAME_FIELD_NUMBER = 3; - private boolean hasActorClassname; - private java.lang.String actorClassname_ = ""; - public boolean hasActorClassname() { return hasActorClassname; } - public java.lang.String getActorClassname() { return actorClassname_; } + private java.lang.Object actorClassname_; + public boolean hasActorClassname() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public String getActorClassname() { + java.lang.Object ref = actorClassname_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + actorClassname_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getActorClassnameBytes() { + java.lang.Object ref = actorClassname_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + actorClassname_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } // optional bytes actorInstance = 4; public static final int ACTORINSTANCE_FIELD_NUMBER = 4; - private boolean hasActorInstance; - private com.google.protobuf.ByteString actorInstance_ = com.google.protobuf.ByteString.EMPTY; - public boolean hasActorInstance() { return hasActorInstance; } - public com.google.protobuf.ByteString getActorInstance() { return actorInstance_; } + private com.google.protobuf.ByteString actorInstance_; + public boolean hasActorInstance() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public com.google.protobuf.ByteString getActorInstance() { + return actorInstance_; + } // optional string serializerClassname = 5; public static final int SERIALIZERCLASSNAME_FIELD_NUMBER = 5; - private boolean hasSerializerClassname; - private java.lang.String serializerClassname_ = ""; - public boolean hasSerializerClassname() { return hasSerializerClassname; } - public java.lang.String getSerializerClassname() { return serializerClassname_; } + private java.lang.Object serializerClassname_; + public boolean hasSerializerClassname() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + public String getSerializerClassname() { + java.lang.Object ref = serializerClassname_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + serializerClassname_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getSerializerClassnameBytes() { + java.lang.Object ref = serializerClassname_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + serializerClassname_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } // optional uint64 timeout = 6; public static final int TIMEOUT_FIELD_NUMBER = 6; - private boolean hasTimeout; - private long timeout_ = 0L; - public boolean hasTimeout() { return hasTimeout; } - public long getTimeout() { return timeout_; } + private long timeout_; + public boolean hasTimeout() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + public long getTimeout() { + return timeout_; + } // optional uint64 receiveTimeout = 7; public static final int RECEIVETIMEOUT_FIELD_NUMBER = 7; - private boolean hasReceiveTimeout; - private long receiveTimeout_ = 0L; - public boolean hasReceiveTimeout() { return hasReceiveTimeout; } - public long getReceiveTimeout() { return receiveTimeout_; } + private long receiveTimeout_; + public boolean hasReceiveTimeout() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + public long getReceiveTimeout() { + return receiveTimeout_; + } // optional .LifeCycleProtocol lifeCycle = 8; public static final int LIFECYCLE_FIELD_NUMBER = 8; - private boolean hasLifeCycle; private akka.remote.protocol.RemoteProtocol.LifeCycleProtocol lifeCycle_; - public boolean hasLifeCycle() { return hasLifeCycle; } - public akka.remote.protocol.RemoteProtocol.LifeCycleProtocol getLifeCycle() { return lifeCycle_; } + public boolean hasLifeCycle() { + return ((bitField0_ & 0x00000080) == 0x00000080); + } + public akka.remote.protocol.RemoteProtocol.LifeCycleProtocol getLifeCycle() { + return lifeCycle_; + } + public akka.remote.protocol.RemoteProtocol.LifeCycleProtocolOrBuilder getLifeCycleOrBuilder() { + return lifeCycle_; + } // optional .RemoteActorRefProtocol supervisor = 9; public static final int SUPERVISOR_FIELD_NUMBER = 9; - private boolean hasSupervisor; private akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol supervisor_; - public boolean hasSupervisor() { return hasSupervisor; } - public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol getSupervisor() { return supervisor_; } + public boolean hasSupervisor() { + return ((bitField0_ & 0x00000100) == 0x00000100); + } + public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol getSupervisor() { + return supervisor_; + } + public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocolOrBuilder getSupervisorOrBuilder() { + return supervisor_; + } // optional bytes hotswapStack = 10; public static final int HOTSWAPSTACK_FIELD_NUMBER = 10; - private boolean hasHotswapStack; - private com.google.protobuf.ByteString hotswapStack_ = com.google.protobuf.ByteString.EMPTY; - public boolean hasHotswapStack() { return hasHotswapStack; } - public com.google.protobuf.ByteString getHotswapStack() { return hotswapStack_; } + private com.google.protobuf.ByteString hotswapStack_; + public boolean hasHotswapStack() { + return ((bitField0_ & 0x00000200) == 0x00000200); + } + public com.google.protobuf.ByteString getHotswapStack() { + return hotswapStack_; + } - // repeated .RemoteMessageProtocol messages = 11; - public static final int MESSAGES_FIELD_NUMBER = 11; - private java.util.List messages_ = - java.util.Collections.emptyList(); + // optional .ReplicationStorageType replicationStorage = 11; + public static final int REPLICATIONSTORAGE_FIELD_NUMBER = 11; + private akka.remote.protocol.RemoteProtocol.ReplicationStorageType replicationStorage_; + public boolean hasReplicationStorage() { + return ((bitField0_ & 0x00000400) == 0x00000400); + } + public akka.remote.protocol.RemoteProtocol.ReplicationStorageType getReplicationStorage() { + return replicationStorage_; + } + + // optional .ReplicationStrategyType replicationStrategy = 12; + public static final int REPLICATIONSTRATEGY_FIELD_NUMBER = 12; + private akka.remote.protocol.RemoteProtocol.ReplicationStrategyType replicationStrategy_; + public boolean hasReplicationStrategy() { + return ((bitField0_ & 0x00000800) == 0x00000800); + } + public akka.remote.protocol.RemoteProtocol.ReplicationStrategyType getReplicationStrategy() { + return replicationStrategy_; + } + + // repeated .RemoteMessageProtocol messages = 13; + public static final int MESSAGES_FIELD_NUMBER = 13; + private java.util.List messages_; public java.util.List getMessagesList() { return messages_; } - public int getMessagesCount() { return messages_.size(); } + public java.util.List + getMessagesOrBuilderList() { + return messages_; + } + public int getMessagesCount() { + return messages_.size(); + } public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol getMessages(int index) { return messages_.get(index); } + public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocolOrBuilder getMessagesOrBuilder( + int index) { + return messages_.get(index); + } private void initFields() { uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + address_ = ""; + actorClassname_ = ""; + actorInstance_ = com.google.protobuf.ByteString.EMPTY; + serializerClassname_ = ""; + timeout_ = 0L; + receiveTimeout_ = 0L; lifeCycle_ = akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.getDefaultInstance(); supervisor_ = akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance(); + hotswapStack_ = com.google.protobuf.ByteString.EMPTY; + replicationStorage_ = akka.remote.protocol.RemoteProtocol.ReplicationStorageType.TRANSIENT; + replicationStrategy_ = akka.remote.protocol.RemoteProtocol.ReplicationStrategyType.WRITE_THROUGH; + messages_ = java.util.Collections.emptyList(); } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasUuid) return false; - if (!hasAddress) return false; - if (!hasActorClassname) return false; - if (!getUuid().isInitialized()) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasUuid()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasAddress()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasActorClassname()) { + memoizedIsInitialized = 0; + return false; + } + if (!getUuid().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } if (hasLifeCycle()) { - if (!getLifeCycle().isInitialized()) return false; + if (!getLifeCycle().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } } if (hasSupervisor()) { - if (!getSupervisor().isInitialized()) return false; + if (!getSupervisor().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } } - for (akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol element : getMessagesList()) { - if (!element.isInitialized()) return false; + for (int i = 0; i < getMessagesCount(); i++) { + if (!getMessages(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasUuid()) { - output.writeMessage(1, getUuid()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeMessage(1, uuid_); } - if (hasAddress()) { - output.writeString(2, getAddress()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, getAddressBytes()); } - if (hasActorClassname()) { - output.writeString(3, getActorClassname()); + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeBytes(3, getActorClassnameBytes()); } - if (hasActorInstance()) { - output.writeBytes(4, getActorInstance()); + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeBytes(4, actorInstance_); } - if (hasSerializerClassname()) { - output.writeString(5, getSerializerClassname()); + if (((bitField0_ & 0x00000010) == 0x00000010)) { + output.writeBytes(5, getSerializerClassnameBytes()); } - if (hasTimeout()) { - output.writeUInt64(6, getTimeout()); + if (((bitField0_ & 0x00000020) == 0x00000020)) { + output.writeUInt64(6, timeout_); } - if (hasReceiveTimeout()) { - output.writeUInt64(7, getReceiveTimeout()); + if (((bitField0_ & 0x00000040) == 0x00000040)) { + output.writeUInt64(7, receiveTimeout_); } - if (hasLifeCycle()) { - output.writeMessage(8, getLifeCycle()); + if (((bitField0_ & 0x00000080) == 0x00000080)) { + output.writeMessage(8, lifeCycle_); } - if (hasSupervisor()) { - output.writeMessage(9, getSupervisor()); + if (((bitField0_ & 0x00000100) == 0x00000100)) { + output.writeMessage(9, supervisor_); } - if (hasHotswapStack()) { - output.writeBytes(10, getHotswapStack()); + if (((bitField0_ & 0x00000200) == 0x00000200)) { + output.writeBytes(10, hotswapStack_); } - for (akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol element : getMessagesList()) { - output.writeMessage(11, element); + if (((bitField0_ & 0x00000400) == 0x00000400)) { + output.writeEnum(11, replicationStorage_.getNumber()); + } + if (((bitField0_ & 0x00000800) == 0x00000800)) { + output.writeEnum(12, replicationStrategy_.getNumber()); + } + for (int i = 0; i < messages_.size(); i++) { + output.writeMessage(13, messages_.get(i)); } getUnknownFields().writeTo(output); } @@ -2251,55 +3900,70 @@ public final class RemoteProtocol { if (size != -1) return size; size = 0; - if (hasUuid()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(1, getUuid()); + .computeMessageSize(1, uuid_); } - if (hasAddress()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(2, getAddress()); + .computeBytesSize(2, getAddressBytes()); } - if (hasActorClassname()) { + if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(3, getActorClassname()); + .computeBytesSize(3, getActorClassnameBytes()); } - if (hasActorInstance()) { + if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream - .computeBytesSize(4, getActorInstance()); + .computeBytesSize(4, actorInstance_); } - if (hasSerializerClassname()) { + if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(5, getSerializerClassname()); + .computeBytesSize(5, getSerializerClassnameBytes()); } - if (hasTimeout()) { + if (((bitField0_ & 0x00000020) == 0x00000020)) { size += com.google.protobuf.CodedOutputStream - .computeUInt64Size(6, getTimeout()); + .computeUInt64Size(6, timeout_); } - if (hasReceiveTimeout()) { + if (((bitField0_ & 0x00000040) == 0x00000040)) { size += com.google.protobuf.CodedOutputStream - .computeUInt64Size(7, getReceiveTimeout()); + .computeUInt64Size(7, receiveTimeout_); } - if (hasLifeCycle()) { + if (((bitField0_ & 0x00000080) == 0x00000080)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(8, getLifeCycle()); + .computeMessageSize(8, lifeCycle_); } - if (hasSupervisor()) { + if (((bitField0_ & 0x00000100) == 0x00000100)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(9, getSupervisor()); + .computeMessageSize(9, supervisor_); } - if (hasHotswapStack()) { + if (((bitField0_ & 0x00000200) == 0x00000200)) { size += com.google.protobuf.CodedOutputStream - .computeBytesSize(10, getHotswapStack()); + .computeBytesSize(10, hotswapStack_); } - for (akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol element : getMessagesList()) { + if (((bitField0_ & 0x00000400) == 0x00000400)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(11, element); + .computeEnumSize(11, replicationStorage_.getNumber()); + } + if (((bitField0_ & 0x00000800) == 0x00000800)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(12, replicationStrategy_.getNumber()); + } + for (int i = 0; i < messages_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(13, messages_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -2374,34 +4038,95 @@ public final class RemoteProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol result; - - // Construct using akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.internal_static_SerializedActorRefProtocol_descriptor; } - protected akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.remote.protocol.RemoteProtocol.internal_static_SerializedActorRefProtocol_fieldAccessorTable; + } + + // Construct using akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getUuidFieldBuilder(); + getLifeCycleFieldBuilder(); + getSupervisorFieldBuilder(); + getMessagesFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); + super.clear(); + if (uuidBuilder_ == null) { + uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + } else { + uuidBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000001); + address_ = ""; + bitField0_ = (bitField0_ & ~0x00000002); + actorClassname_ = ""; + bitField0_ = (bitField0_ & ~0x00000004); + actorInstance_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000008); + serializerClassname_ = ""; + bitField0_ = (bitField0_ & ~0x00000010); + timeout_ = 0L; + bitField0_ = (bitField0_ & ~0x00000020); + receiveTimeout_ = 0L; + bitField0_ = (bitField0_ & ~0x00000040); + if (lifeCycleBuilder_ == null) { + lifeCycle_ = akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.getDefaultInstance(); + } else { + lifeCycleBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000080); + if (supervisorBuilder_ == null) { + supervisor_ = akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance(); + } else { + supervisorBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000100); + hotswapStack_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000200); + replicationStorage_ = akka.remote.protocol.RemoteProtocol.ReplicationStorageType.TRANSIENT; + bitField0_ = (bitField0_ & ~0x00000400); + replicationStrategy_ = akka.remote.protocol.RemoteProtocol.ReplicationStrategyType.WRITE_THROUGH; + bitField0_ = (bitField0_ & ~0x00000800); + if (messagesBuilder_ == null) { + messages_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00001000); + } else { + messagesBuilder_.clear(); } - result = new akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol(); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -2413,37 +4138,100 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol build() { - if (result != null && !isInitialized()) { + akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol result = new akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - if (result.messages_ != java.util.Collections.EMPTY_LIST) { - result.messages_ = - java.util.Collections.unmodifiableList(result.messages_); + if (uuidBuilder_ == null) { + result.uuid_ = uuid_; + } else { + result.uuid_ = uuidBuilder_.build(); } - akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol returnMe = result; - result = null; - return returnMe; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.address_ = address_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.actorClassname_ = actorClassname_; + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + result.actorInstance_ = actorInstance_; + if (((from_bitField0_ & 0x00000010) == 0x00000010)) { + to_bitField0_ |= 0x00000010; + } + result.serializerClassname_ = serializerClassname_; + if (((from_bitField0_ & 0x00000020) == 0x00000020)) { + to_bitField0_ |= 0x00000020; + } + result.timeout_ = timeout_; + if (((from_bitField0_ & 0x00000040) == 0x00000040)) { + to_bitField0_ |= 0x00000040; + } + result.receiveTimeout_ = receiveTimeout_; + if (((from_bitField0_ & 0x00000080) == 0x00000080)) { + to_bitField0_ |= 0x00000080; + } + if (lifeCycleBuilder_ == null) { + result.lifeCycle_ = lifeCycle_; + } else { + result.lifeCycle_ = lifeCycleBuilder_.build(); + } + if (((from_bitField0_ & 0x00000100) == 0x00000100)) { + to_bitField0_ |= 0x00000100; + } + if (supervisorBuilder_ == null) { + result.supervisor_ = supervisor_; + } else { + result.supervisor_ = supervisorBuilder_.build(); + } + if (((from_bitField0_ & 0x00000200) == 0x00000200)) { + to_bitField0_ |= 0x00000200; + } + result.hotswapStack_ = hotswapStack_; + if (((from_bitField0_ & 0x00000400) == 0x00000400)) { + to_bitField0_ |= 0x00000400; + } + result.replicationStorage_ = replicationStorage_; + if (((from_bitField0_ & 0x00000800) == 0x00000800)) { + to_bitField0_ |= 0x00000800; + } + result.replicationStrategy_ = replicationStrategy_; + if (messagesBuilder_ == null) { + if (((bitField0_ & 0x00001000) == 0x00001000)) { + messages_ = java.util.Collections.unmodifiableList(messages_); + bitField0_ = (bitField0_ & ~0x00001000); + } + result.messages_ = messages_; + } else { + result.messages_ = messagesBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -2487,16 +4275,80 @@ public final class RemoteProtocol { if (other.hasHotswapStack()) { setHotswapStack(other.getHotswapStack()); } - if (!other.messages_.isEmpty()) { - if (result.messages_.isEmpty()) { - result.messages_ = new java.util.ArrayList(); + if (other.hasReplicationStorage()) { + setReplicationStorage(other.getReplicationStorage()); + } + if (other.hasReplicationStrategy()) { + setReplicationStrategy(other.getReplicationStrategy()); + } + if (messagesBuilder_ == null) { + if (!other.messages_.isEmpty()) { + if (messages_.isEmpty()) { + messages_ = other.messages_; + bitField0_ = (bitField0_ & ~0x00001000); + } else { + ensureMessagesIsMutable(); + messages_.addAll(other.messages_); + } + onChanged(); + } + } else { + if (!other.messages_.isEmpty()) { + if (messagesBuilder_.isEmpty()) { + messagesBuilder_.dispose(); + messagesBuilder_ = null; + messages_ = other.messages_; + bitField0_ = (bitField0_ & ~0x00001000); + messagesBuilder_ = + com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? + getMessagesFieldBuilder() : null; + } else { + messagesBuilder_.addAllMessages(other.messages_); + } } - result.messages_.addAll(other.messages_); } this.mergeUnknownFields(other.getUnknownFields()); return this; } + public final boolean isInitialized() { + if (!hasUuid()) { + + return false; + } + if (!hasAddress()) { + + return false; + } + if (!hasActorClassname()) { + + return false; + } + if (!getUuid().isInitialized()) { + + return false; + } + if (hasLifeCycle()) { + if (!getLifeCycle().isInitialized()) { + + return false; + } + } + if (hasSupervisor()) { + if (!getSupervisor().isInitialized()) { + + return false; + } + } + for (int i = 0; i < getMessagesCount(); i++) { + if (!getMessages(i).isInitialized()) { + + return false; + } + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -2509,11 +4361,13 @@ public final class RemoteProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; @@ -2528,27 +4382,33 @@ public final class RemoteProtocol { break; } case 18: { - setAddress(input.readString()); + bitField0_ |= 0x00000002; + address_ = input.readBytes(); break; } case 26: { - setActorClassname(input.readString()); + bitField0_ |= 0x00000004; + actorClassname_ = input.readBytes(); break; } case 34: { - setActorInstance(input.readBytes()); + bitField0_ |= 0x00000008; + actorInstance_ = input.readBytes(); break; } case 42: { - setSerializerClassname(input.readString()); + bitField0_ |= 0x00000010; + serializerClassname_ = input.readBytes(); break; } case 48: { - setTimeout(input.readUInt64()); + bitField0_ |= 0x00000020; + timeout_ = input.readUInt64(); break; } case 56: { - setReceiveTimeout(input.readUInt64()); + bitField0_ |= 0x00000040; + receiveTimeout_ = input.readUInt64(); break; } case 66: { @@ -2570,10 +4430,33 @@ public final class RemoteProtocol { break; } case 82: { - setHotswapStack(input.readBytes()); + bitField0_ |= 0x00000200; + hotswapStack_ = input.readBytes(); break; } - case 90: { + case 88: { + int rawValue = input.readEnum(); + akka.remote.protocol.RemoteProtocol.ReplicationStorageType value = akka.remote.protocol.RemoteProtocol.ReplicationStorageType.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(11, rawValue); + } else { + bitField0_ |= 0x00000400; + replicationStorage_ = value; + } + break; + } + case 96: { + int rawValue = input.readEnum(); + akka.remote.protocol.RemoteProtocol.ReplicationStrategyType value = akka.remote.protocol.RemoteProtocol.ReplicationStrategyType.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(12, rawValue); + } else { + bitField0_ |= 0x00000800; + replicationStrategy_ = value; + } + break; + } + case 106: { akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder subBuilder = akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.newBuilder(); input.readMessage(subBuilder, extensionRegistry); addMessages(subBuilder.buildPartial()); @@ -2583,327 +4466,739 @@ public final class RemoteProtocol { } } + private int bitField0_; // required .UuidProtocol uuid = 1; + private akka.remote.protocol.RemoteProtocol.UuidProtocol uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.UuidProtocol, akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder, akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder> uuidBuilder_; public boolean hasUuid() { - return result.hasUuid(); + return ((bitField0_ & 0x00000001) == 0x00000001); } public akka.remote.protocol.RemoteProtocol.UuidProtocol getUuid() { - return result.getUuid(); + if (uuidBuilder_ == null) { + return uuid_; + } else { + return uuidBuilder_.getMessage(); + } } public Builder setUuid(akka.remote.protocol.RemoteProtocol.UuidProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (uuidBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + uuid_ = value; + onChanged(); + } else { + uuidBuilder_.setMessage(value); } - result.hasUuid = true; - result.uuid_ = value; + bitField0_ |= 0x00000001; return this; } - public Builder setUuid(akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder builderForValue) { - result.hasUuid = true; - result.uuid_ = builderForValue.build(); + public Builder setUuid( + akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder builderForValue) { + if (uuidBuilder_ == null) { + uuid_ = builderForValue.build(); + onChanged(); + } else { + uuidBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000001; return this; } public Builder mergeUuid(akka.remote.protocol.RemoteProtocol.UuidProtocol value) { - if (result.hasUuid() && - result.uuid_ != akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance()) { - result.uuid_ = - akka.remote.protocol.RemoteProtocol.UuidProtocol.newBuilder(result.uuid_).mergeFrom(value).buildPartial(); + if (uuidBuilder_ == null) { + if (((bitField0_ & 0x00000001) == 0x00000001) && + uuid_ != akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance()) { + uuid_ = + akka.remote.protocol.RemoteProtocol.UuidProtocol.newBuilder(uuid_).mergeFrom(value).buildPartial(); + } else { + uuid_ = value; + } + onChanged(); } else { - result.uuid_ = value; + uuidBuilder_.mergeFrom(value); } - result.hasUuid = true; + bitField0_ |= 0x00000001; return this; } public Builder clearUuid() { - result.hasUuid = false; - result.uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + if (uuidBuilder_ == null) { + uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + onChanged(); + } else { + uuidBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000001); return this; } + public akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder getUuidBuilder() { + bitField0_ |= 0x00000001; + onChanged(); + return getUuidFieldBuilder().getBuilder(); + } + public akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder getUuidOrBuilder() { + if (uuidBuilder_ != null) { + return uuidBuilder_.getMessageOrBuilder(); + } else { + return uuid_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.UuidProtocol, akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder, akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder> + getUuidFieldBuilder() { + if (uuidBuilder_ == null) { + uuidBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.UuidProtocol, akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder, akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder>( + uuid_, + getParentForChildren(), + isClean()); + uuid_ = null; + } + return uuidBuilder_; + } // required string address = 2; + private java.lang.Object address_ = ""; public boolean hasAddress() { - return result.hasAddress(); + return ((bitField0_ & 0x00000002) == 0x00000002); } - public java.lang.String getAddress() { - return result.getAddress(); + public String getAddress() { + java.lang.Object ref = address_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + address_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setAddress(java.lang.String value) { + public Builder setAddress(String value) { if (value == null) { throw new NullPointerException(); } - result.hasAddress = true; - result.address_ = value; + bitField0_ |= 0x00000002; + address_ = value; + onChanged(); return this; } public Builder clearAddress() { - result.hasAddress = false; - result.address_ = getDefaultInstance().getAddress(); + bitField0_ = (bitField0_ & ~0x00000002); + address_ = getDefaultInstance().getAddress(); + onChanged(); return this; } + void setAddress(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000002; + address_ = value; + onChanged(); + } // required string actorClassname = 3; + private java.lang.Object actorClassname_ = ""; public boolean hasActorClassname() { - return result.hasActorClassname(); + return ((bitField0_ & 0x00000004) == 0x00000004); } - public java.lang.String getActorClassname() { - return result.getActorClassname(); + public String getActorClassname() { + java.lang.Object ref = actorClassname_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + actorClassname_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setActorClassname(java.lang.String value) { + public Builder setActorClassname(String value) { if (value == null) { throw new NullPointerException(); } - result.hasActorClassname = true; - result.actorClassname_ = value; + bitField0_ |= 0x00000004; + actorClassname_ = value; + onChanged(); return this; } public Builder clearActorClassname() { - result.hasActorClassname = false; - result.actorClassname_ = getDefaultInstance().getActorClassname(); + bitField0_ = (bitField0_ & ~0x00000004); + actorClassname_ = getDefaultInstance().getActorClassname(); + onChanged(); return this; } + void setActorClassname(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000004; + actorClassname_ = value; + onChanged(); + } // optional bytes actorInstance = 4; + private com.google.protobuf.ByteString actorInstance_ = com.google.protobuf.ByteString.EMPTY; public boolean hasActorInstance() { - return result.hasActorInstance(); + return ((bitField0_ & 0x00000008) == 0x00000008); } public com.google.protobuf.ByteString getActorInstance() { - return result.getActorInstance(); + return actorInstance_; } public Builder setActorInstance(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } - result.hasActorInstance = true; - result.actorInstance_ = value; + bitField0_ |= 0x00000008; + actorInstance_ = value; + onChanged(); return this; } public Builder clearActorInstance() { - result.hasActorInstance = false; - result.actorInstance_ = getDefaultInstance().getActorInstance(); + bitField0_ = (bitField0_ & ~0x00000008); + actorInstance_ = getDefaultInstance().getActorInstance(); + onChanged(); return this; } // optional string serializerClassname = 5; + private java.lang.Object serializerClassname_ = ""; public boolean hasSerializerClassname() { - return result.hasSerializerClassname(); + return ((bitField0_ & 0x00000010) == 0x00000010); } - public java.lang.String getSerializerClassname() { - return result.getSerializerClassname(); + public String getSerializerClassname() { + java.lang.Object ref = serializerClassname_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + serializerClassname_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setSerializerClassname(java.lang.String value) { + public Builder setSerializerClassname(String value) { if (value == null) { throw new NullPointerException(); } - result.hasSerializerClassname = true; - result.serializerClassname_ = value; + bitField0_ |= 0x00000010; + serializerClassname_ = value; + onChanged(); return this; } public Builder clearSerializerClassname() { - result.hasSerializerClassname = false; - result.serializerClassname_ = getDefaultInstance().getSerializerClassname(); + bitField0_ = (bitField0_ & ~0x00000010); + serializerClassname_ = getDefaultInstance().getSerializerClassname(); + onChanged(); return this; } + void setSerializerClassname(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000010; + serializerClassname_ = value; + onChanged(); + } // optional uint64 timeout = 6; + private long timeout_ ; public boolean hasTimeout() { - return result.hasTimeout(); + return ((bitField0_ & 0x00000020) == 0x00000020); } public long getTimeout() { - return result.getTimeout(); + return timeout_; } public Builder setTimeout(long value) { - result.hasTimeout = true; - result.timeout_ = value; + bitField0_ |= 0x00000020; + timeout_ = value; + onChanged(); return this; } public Builder clearTimeout() { - result.hasTimeout = false; - result.timeout_ = 0L; + bitField0_ = (bitField0_ & ~0x00000020); + timeout_ = 0L; + onChanged(); return this; } // optional uint64 receiveTimeout = 7; + private long receiveTimeout_ ; public boolean hasReceiveTimeout() { - return result.hasReceiveTimeout(); + return ((bitField0_ & 0x00000040) == 0x00000040); } public long getReceiveTimeout() { - return result.getReceiveTimeout(); + return receiveTimeout_; } public Builder setReceiveTimeout(long value) { - result.hasReceiveTimeout = true; - result.receiveTimeout_ = value; + bitField0_ |= 0x00000040; + receiveTimeout_ = value; + onChanged(); return this; } public Builder clearReceiveTimeout() { - result.hasReceiveTimeout = false; - result.receiveTimeout_ = 0L; + bitField0_ = (bitField0_ & ~0x00000040); + receiveTimeout_ = 0L; + onChanged(); return this; } // optional .LifeCycleProtocol lifeCycle = 8; + private akka.remote.protocol.RemoteProtocol.LifeCycleProtocol lifeCycle_ = akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.LifeCycleProtocol, akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.Builder, akka.remote.protocol.RemoteProtocol.LifeCycleProtocolOrBuilder> lifeCycleBuilder_; public boolean hasLifeCycle() { - return result.hasLifeCycle(); + return ((bitField0_ & 0x00000080) == 0x00000080); } public akka.remote.protocol.RemoteProtocol.LifeCycleProtocol getLifeCycle() { - return result.getLifeCycle(); + if (lifeCycleBuilder_ == null) { + return lifeCycle_; + } else { + return lifeCycleBuilder_.getMessage(); + } } public Builder setLifeCycle(akka.remote.protocol.RemoteProtocol.LifeCycleProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (lifeCycleBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + lifeCycle_ = value; + onChanged(); + } else { + lifeCycleBuilder_.setMessage(value); } - result.hasLifeCycle = true; - result.lifeCycle_ = value; + bitField0_ |= 0x00000080; return this; } - public Builder setLifeCycle(akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.Builder builderForValue) { - result.hasLifeCycle = true; - result.lifeCycle_ = builderForValue.build(); + public Builder setLifeCycle( + akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.Builder builderForValue) { + if (lifeCycleBuilder_ == null) { + lifeCycle_ = builderForValue.build(); + onChanged(); + } else { + lifeCycleBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000080; return this; } public Builder mergeLifeCycle(akka.remote.protocol.RemoteProtocol.LifeCycleProtocol value) { - if (result.hasLifeCycle() && - result.lifeCycle_ != akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.getDefaultInstance()) { - result.lifeCycle_ = - akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.newBuilder(result.lifeCycle_).mergeFrom(value).buildPartial(); + if (lifeCycleBuilder_ == null) { + if (((bitField0_ & 0x00000080) == 0x00000080) && + lifeCycle_ != akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.getDefaultInstance()) { + lifeCycle_ = + akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.newBuilder(lifeCycle_).mergeFrom(value).buildPartial(); + } else { + lifeCycle_ = value; + } + onChanged(); } else { - result.lifeCycle_ = value; + lifeCycleBuilder_.mergeFrom(value); } - result.hasLifeCycle = true; + bitField0_ |= 0x00000080; return this; } public Builder clearLifeCycle() { - result.hasLifeCycle = false; - result.lifeCycle_ = akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.getDefaultInstance(); + if (lifeCycleBuilder_ == null) { + lifeCycle_ = akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.getDefaultInstance(); + onChanged(); + } else { + lifeCycleBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000080); return this; } + public akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.Builder getLifeCycleBuilder() { + bitField0_ |= 0x00000080; + onChanged(); + return getLifeCycleFieldBuilder().getBuilder(); + } + public akka.remote.protocol.RemoteProtocol.LifeCycleProtocolOrBuilder getLifeCycleOrBuilder() { + if (lifeCycleBuilder_ != null) { + return lifeCycleBuilder_.getMessageOrBuilder(); + } else { + return lifeCycle_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.LifeCycleProtocol, akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.Builder, akka.remote.protocol.RemoteProtocol.LifeCycleProtocolOrBuilder> + getLifeCycleFieldBuilder() { + if (lifeCycleBuilder_ == null) { + lifeCycleBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.LifeCycleProtocol, akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.Builder, akka.remote.protocol.RemoteProtocol.LifeCycleProtocolOrBuilder>( + lifeCycle_, + getParentForChildren(), + isClean()); + lifeCycle_ = null; + } + return lifeCycleBuilder_; + } // optional .RemoteActorRefProtocol supervisor = 9; + private akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol supervisor_ = akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol, akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocolOrBuilder> supervisorBuilder_; public boolean hasSupervisor() { - return result.hasSupervisor(); + return ((bitField0_ & 0x00000100) == 0x00000100); } public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol getSupervisor() { - return result.getSupervisor(); + if (supervisorBuilder_ == null) { + return supervisor_; + } else { + return supervisorBuilder_.getMessage(); + } } public Builder setSupervisor(akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (supervisorBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + supervisor_ = value; + onChanged(); + } else { + supervisorBuilder_.setMessage(value); } - result.hasSupervisor = true; - result.supervisor_ = value; + bitField0_ |= 0x00000100; return this; } - public Builder setSupervisor(akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.Builder builderForValue) { - result.hasSupervisor = true; - result.supervisor_ = builderForValue.build(); + public Builder setSupervisor( + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.Builder builderForValue) { + if (supervisorBuilder_ == null) { + supervisor_ = builderForValue.build(); + onChanged(); + } else { + supervisorBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000100; return this; } public Builder mergeSupervisor(akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol value) { - if (result.hasSupervisor() && - result.supervisor_ != akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance()) { - result.supervisor_ = - akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.newBuilder(result.supervisor_).mergeFrom(value).buildPartial(); + if (supervisorBuilder_ == null) { + if (((bitField0_ & 0x00000100) == 0x00000100) && + supervisor_ != akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance()) { + supervisor_ = + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.newBuilder(supervisor_).mergeFrom(value).buildPartial(); + } else { + supervisor_ = value; + } + onChanged(); } else { - result.supervisor_ = value; + supervisorBuilder_.mergeFrom(value); } - result.hasSupervisor = true; + bitField0_ |= 0x00000100; return this; } public Builder clearSupervisor() { - result.hasSupervisor = false; - result.supervisor_ = akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance(); + if (supervisorBuilder_ == null) { + supervisor_ = akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.getDefaultInstance(); + onChanged(); + } else { + supervisorBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000100); return this; } + public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.Builder getSupervisorBuilder() { + bitField0_ |= 0x00000100; + onChanged(); + return getSupervisorFieldBuilder().getBuilder(); + } + public akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocolOrBuilder getSupervisorOrBuilder() { + if (supervisorBuilder_ != null) { + return supervisorBuilder_.getMessageOrBuilder(); + } else { + return supervisor_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol, akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocolOrBuilder> + getSupervisorFieldBuilder() { + if (supervisorBuilder_ == null) { + supervisorBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol, akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteActorRefProtocolOrBuilder>( + supervisor_, + getParentForChildren(), + isClean()); + supervisor_ = null; + } + return supervisorBuilder_; + } // optional bytes hotswapStack = 10; + private com.google.protobuf.ByteString hotswapStack_ = com.google.protobuf.ByteString.EMPTY; public boolean hasHotswapStack() { - return result.hasHotswapStack(); + return ((bitField0_ & 0x00000200) == 0x00000200); } public com.google.protobuf.ByteString getHotswapStack() { - return result.getHotswapStack(); + return hotswapStack_; } public Builder setHotswapStack(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } - result.hasHotswapStack = true; - result.hotswapStack_ = value; + bitField0_ |= 0x00000200; + hotswapStack_ = value; + onChanged(); return this; } public Builder clearHotswapStack() { - result.hasHotswapStack = false; - result.hotswapStack_ = getDefaultInstance().getHotswapStack(); + bitField0_ = (bitField0_ & ~0x00000200); + hotswapStack_ = getDefaultInstance().getHotswapStack(); + onChanged(); return this; } - // repeated .RemoteMessageProtocol messages = 11; - public java.util.List getMessagesList() { - return java.util.Collections.unmodifiableList(result.messages_); + // optional .ReplicationStorageType replicationStorage = 11; + private akka.remote.protocol.RemoteProtocol.ReplicationStorageType replicationStorage_ = akka.remote.protocol.RemoteProtocol.ReplicationStorageType.TRANSIENT; + public boolean hasReplicationStorage() { + return ((bitField0_ & 0x00000400) == 0x00000400); } - public int getMessagesCount() { - return result.getMessagesCount(); + public akka.remote.protocol.RemoteProtocol.ReplicationStorageType getReplicationStorage() { + return replicationStorage_; } - public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol getMessages(int index) { - return result.getMessages(index); - } - public Builder setMessages(int index, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol value) { + public Builder setReplicationStorage(akka.remote.protocol.RemoteProtocol.ReplicationStorageType value) { if (value == null) { throw new NullPointerException(); } - result.messages_.set(index, value); + bitField0_ |= 0x00000400; + replicationStorage_ = value; + onChanged(); return this; } - public Builder setMessages(int index, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder builderForValue) { - result.messages_.set(index, builderForValue.build()); + public Builder clearReplicationStorage() { + bitField0_ = (bitField0_ & ~0x00000400); + replicationStorage_ = akka.remote.protocol.RemoteProtocol.ReplicationStorageType.TRANSIENT; + onChanged(); + return this; + } + + // optional .ReplicationStrategyType replicationStrategy = 12; + private akka.remote.protocol.RemoteProtocol.ReplicationStrategyType replicationStrategy_ = akka.remote.protocol.RemoteProtocol.ReplicationStrategyType.WRITE_THROUGH; + public boolean hasReplicationStrategy() { + return ((bitField0_ & 0x00000800) == 0x00000800); + } + public akka.remote.protocol.RemoteProtocol.ReplicationStrategyType getReplicationStrategy() { + return replicationStrategy_; + } + public Builder setReplicationStrategy(akka.remote.protocol.RemoteProtocol.ReplicationStrategyType value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000800; + replicationStrategy_ = value; + onChanged(); + return this; + } + public Builder clearReplicationStrategy() { + bitField0_ = (bitField0_ & ~0x00000800); + replicationStrategy_ = akka.remote.protocol.RemoteProtocol.ReplicationStrategyType.WRITE_THROUGH; + onChanged(); + return this; + } + + // repeated .RemoteMessageProtocol messages = 13; + private java.util.List messages_ = + java.util.Collections.emptyList(); + private void ensureMessagesIsMutable() { + if (!((bitField0_ & 0x00001000) == 0x00001000)) { + messages_ = new java.util.ArrayList(messages_); + bitField0_ |= 0x00001000; + } + } + + private com.google.protobuf.RepeatedFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocolOrBuilder> messagesBuilder_; + + public java.util.List getMessagesList() { + if (messagesBuilder_ == null) { + return java.util.Collections.unmodifiableList(messages_); + } else { + return messagesBuilder_.getMessageList(); + } + } + public int getMessagesCount() { + if (messagesBuilder_ == null) { + return messages_.size(); + } else { + return messagesBuilder_.getCount(); + } + } + public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol getMessages(int index) { + if (messagesBuilder_ == null) { + return messages_.get(index); + } else { + return messagesBuilder_.getMessage(index); + } + } + public Builder setMessages( + int index, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol value) { + if (messagesBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureMessagesIsMutable(); + messages_.set(index, value); + onChanged(); + } else { + messagesBuilder_.setMessage(index, value); + } + return this; + } + public Builder setMessages( + int index, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder builderForValue) { + if (messagesBuilder_ == null) { + ensureMessagesIsMutable(); + messages_.set(index, builderForValue.build()); + onChanged(); + } else { + messagesBuilder_.setMessage(index, builderForValue.build()); + } return this; } public Builder addMessages(akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (messagesBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureMessagesIsMutable(); + messages_.add(value); + onChanged(); + } else { + messagesBuilder_.addMessage(value); } - if (result.messages_.isEmpty()) { - result.messages_ = new java.util.ArrayList(); - } - result.messages_.add(value); return this; } - public Builder addMessages(akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder builderForValue) { - if (result.messages_.isEmpty()) { - result.messages_ = new java.util.ArrayList(); + public Builder addMessages( + int index, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol value) { + if (messagesBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureMessagesIsMutable(); + messages_.add(index, value); + onChanged(); + } else { + messagesBuilder_.addMessage(index, value); + } + return this; + } + public Builder addMessages( + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder builderForValue) { + if (messagesBuilder_ == null) { + ensureMessagesIsMutable(); + messages_.add(builderForValue.build()); + onChanged(); + } else { + messagesBuilder_.addMessage(builderForValue.build()); + } + return this; + } + public Builder addMessages( + int index, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder builderForValue) { + if (messagesBuilder_ == null) { + ensureMessagesIsMutable(); + messages_.add(index, builderForValue.build()); + onChanged(); + } else { + messagesBuilder_.addMessage(index, builderForValue.build()); } - result.messages_.add(builderForValue.build()); return this; } public Builder addAllMessages( java.lang.Iterable values) { - if (result.messages_.isEmpty()) { - result.messages_ = new java.util.ArrayList(); + if (messagesBuilder_ == null) { + ensureMessagesIsMutable(); + super.addAll(values, messages_); + onChanged(); + } else { + messagesBuilder_.addAllMessages(values); } - super.addAll(values, result.messages_); return this; } public Builder clearMessages() { - result.messages_ = java.util.Collections.emptyList(); + if (messagesBuilder_ == null) { + messages_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00001000); + onChanged(); + } else { + messagesBuilder_.clear(); + } return this; } + public Builder removeMessages(int index) { + if (messagesBuilder_ == null) { + ensureMessagesIsMutable(); + messages_.remove(index); + onChanged(); + } else { + messagesBuilder_.remove(index); + } + return this; + } + public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder getMessagesBuilder( + int index) { + return getMessagesFieldBuilder().getBuilder(index); + } + public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocolOrBuilder getMessagesOrBuilder( + int index) { + if (messagesBuilder_ == null) { + return messages_.get(index); } else { + return messagesBuilder_.getMessageOrBuilder(index); + } + } + public java.util.List + getMessagesOrBuilderList() { + if (messagesBuilder_ != null) { + return messagesBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(messages_); + } + } + public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder addMessagesBuilder() { + return getMessagesFieldBuilder().addBuilder( + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.getDefaultInstance()); + } + public akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder addMessagesBuilder( + int index) { + return getMessagesFieldBuilder().addBuilder( + index, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.getDefaultInstance()); + } + public java.util.List + getMessagesBuilderList() { + return getMessagesFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocolOrBuilder> + getMessagesFieldBuilder() { + if (messagesBuilder_ == null) { + messagesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocol.Builder, akka.remote.protocol.RemoteProtocol.RemoteMessageProtocolOrBuilder>( + messages_, + ((bitField0_ & 0x00001000) == 0x00001000), + getParentForChildren(), + isClean()); + messages_ = null; + } + return messagesBuilder_; + } // @@protoc_insertion_point(builder_scope:SerializedActorRefProtocol) } static { defaultInstance = new SerializedActorRefProtocol(true); - akka.remote.protocol.RemoteProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:SerializedActorRefProtocol) } + public interface SerializedTypedActorRefProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required .SerializedActorRefProtocol actorRef = 1; + boolean hasActorRef(); + akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol getActorRef(); + akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocolOrBuilder getActorRefOrBuilder(); + + // required string interfaceName = 2; + boolean hasInterfaceName(); + String getInterfaceName(); + } public static final class SerializedTypedActorRefProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements SerializedTypedActorRefProtocolOrBuilder { // Use SerializedTypedActorRefProtocol.newBuilder() to construct. - private SerializedTypedActorRefProtocol() { - initFields(); + private SerializedTypedActorRefProtocol(Builder builder) { + super(builder); } private SerializedTypedActorRefProtocol(boolean noInit) {} @@ -2926,38 +5221,85 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.internal_static_SerializedTypedActorRefProtocol_fieldAccessorTable; } + private int bitField0_; // required .SerializedActorRefProtocol actorRef = 1; public static final int ACTORREF_FIELD_NUMBER = 1; - private boolean hasActorRef; private akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol actorRef_; - public boolean hasActorRef() { return hasActorRef; } - public akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol getActorRef() { return actorRef_; } + public boolean hasActorRef() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol getActorRef() { + return actorRef_; + } + public akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocolOrBuilder getActorRefOrBuilder() { + return actorRef_; + } // required string interfaceName = 2; public static final int INTERFACENAME_FIELD_NUMBER = 2; - private boolean hasInterfaceName; - private java.lang.String interfaceName_ = ""; - public boolean hasInterfaceName() { return hasInterfaceName; } - public java.lang.String getInterfaceName() { return interfaceName_; } + private java.lang.Object interfaceName_; + public boolean hasInterfaceName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public String getInterfaceName() { + java.lang.Object ref = interfaceName_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + interfaceName_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getInterfaceNameBytes() { + java.lang.Object ref = interfaceName_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + interfaceName_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } private void initFields() { actorRef_ = akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.getDefaultInstance(); + interfaceName_ = ""; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasActorRef) return false; - if (!hasInterfaceName) return false; - if (!getActorRef().isInitialized()) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasActorRef()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasInterfaceName()) { + memoizedIsInitialized = 0; + return false; + } + if (!getActorRef().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasActorRef()) { - output.writeMessage(1, getActorRef()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeMessage(1, actorRef_); } - if (hasInterfaceName()) { - output.writeString(2, getInterfaceName()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, getInterfaceNameBytes()); } getUnknownFields().writeTo(output); } @@ -2968,19 +5310,26 @@ public final class RemoteProtocol { if (size != -1) return size; size = 0; - if (hasActorRef()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(1, getActorRef()); + .computeMessageSize(1, actorRef_); } - if (hasInterfaceName()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(2, getInterfaceName()); + .computeBytesSize(2, getInterfaceNameBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -3055,34 +5404,58 @@ public final class RemoteProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol result; - - // Construct using akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.internal_static_SerializedTypedActorRefProtocol_descriptor; } - protected akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.remote.protocol.RemoteProtocol.internal_static_SerializedTypedActorRefProtocol_fieldAccessorTable; + } + + // Construct using akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getActorRefFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); + super.clear(); + if (actorRefBuilder_ == null) { + actorRef_ = akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.getDefaultInstance(); + } else { + actorRefBuilder_.clear(); } - result = new akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol(); + bitField0_ = (bitField0_ & ~0x00000001); + interfaceName_ = ""; + bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -3094,33 +5467,43 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol build() { - if (result != null && !isInitialized()) { + akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol result = new akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.remote.protocol.RemoteProtocol.SerializedTypedActorRefProtocol returnMe = result; - result = null; - return returnMe; + if (actorRefBuilder_ == null) { + result.actorRef_ = actorRef_; + } else { + result.actorRef_ = actorRefBuilder_.build(); + } + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.interfaceName_ = interfaceName_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -3144,6 +5527,22 @@ public final class RemoteProtocol { return this; } + public final boolean isInitialized() { + if (!hasActorRef()) { + + return false; + } + if (!hasInterfaceName()) { + + return false; + } + if (!getActorRef().isInitialized()) { + + return false; + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -3156,11 +5555,13 @@ public final class RemoteProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; @@ -3175,89 +5576,170 @@ public final class RemoteProtocol { break; } case 18: { - setInterfaceName(input.readString()); + bitField0_ |= 0x00000002; + interfaceName_ = input.readBytes(); break; } } } } + private int bitField0_; // required .SerializedActorRefProtocol actorRef = 1; + private akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol actorRef_ = akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol, akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.Builder, akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocolOrBuilder> actorRefBuilder_; public boolean hasActorRef() { - return result.hasActorRef(); + return ((bitField0_ & 0x00000001) == 0x00000001); } public akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol getActorRef() { - return result.getActorRef(); + if (actorRefBuilder_ == null) { + return actorRef_; + } else { + return actorRefBuilder_.getMessage(); + } } public Builder setActorRef(akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (actorRefBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + actorRef_ = value; + onChanged(); + } else { + actorRefBuilder_.setMessage(value); } - result.hasActorRef = true; - result.actorRef_ = value; + bitField0_ |= 0x00000001; return this; } - public Builder setActorRef(akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.Builder builderForValue) { - result.hasActorRef = true; - result.actorRef_ = builderForValue.build(); + public Builder setActorRef( + akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.Builder builderForValue) { + if (actorRefBuilder_ == null) { + actorRef_ = builderForValue.build(); + onChanged(); + } else { + actorRefBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000001; return this; } public Builder mergeActorRef(akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol value) { - if (result.hasActorRef() && - result.actorRef_ != akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.getDefaultInstance()) { - result.actorRef_ = - akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.newBuilder(result.actorRef_).mergeFrom(value).buildPartial(); + if (actorRefBuilder_ == null) { + if (((bitField0_ & 0x00000001) == 0x00000001) && + actorRef_ != akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.getDefaultInstance()) { + actorRef_ = + akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.newBuilder(actorRef_).mergeFrom(value).buildPartial(); + } else { + actorRef_ = value; + } + onChanged(); } else { - result.actorRef_ = value; + actorRefBuilder_.mergeFrom(value); } - result.hasActorRef = true; + bitField0_ |= 0x00000001; return this; } public Builder clearActorRef() { - result.hasActorRef = false; - result.actorRef_ = akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.getDefaultInstance(); + if (actorRefBuilder_ == null) { + actorRef_ = akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.getDefaultInstance(); + onChanged(); + } else { + actorRefBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000001); return this; } + public akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.Builder getActorRefBuilder() { + bitField0_ |= 0x00000001; + onChanged(); + return getActorRefFieldBuilder().getBuilder(); + } + public akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocolOrBuilder getActorRefOrBuilder() { + if (actorRefBuilder_ != null) { + return actorRefBuilder_.getMessageOrBuilder(); + } else { + return actorRef_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol, akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.Builder, akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocolOrBuilder> + getActorRefFieldBuilder() { + if (actorRefBuilder_ == null) { + actorRefBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol, akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.Builder, akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocolOrBuilder>( + actorRef_, + getParentForChildren(), + isClean()); + actorRef_ = null; + } + return actorRefBuilder_; + } // required string interfaceName = 2; + private java.lang.Object interfaceName_ = ""; public boolean hasInterfaceName() { - return result.hasInterfaceName(); + return ((bitField0_ & 0x00000002) == 0x00000002); } - public java.lang.String getInterfaceName() { - return result.getInterfaceName(); + public String getInterfaceName() { + java.lang.Object ref = interfaceName_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + interfaceName_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setInterfaceName(java.lang.String value) { + public Builder setInterfaceName(String value) { if (value == null) { throw new NullPointerException(); } - result.hasInterfaceName = true; - result.interfaceName_ = value; + bitField0_ |= 0x00000002; + interfaceName_ = value; + onChanged(); return this; } public Builder clearInterfaceName() { - result.hasInterfaceName = false; - result.interfaceName_ = getDefaultInstance().getInterfaceName(); + bitField0_ = (bitField0_ & ~0x00000002); + interfaceName_ = getDefaultInstance().getInterfaceName(); + onChanged(); return this; } + void setInterfaceName(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000002; + interfaceName_ = value; + onChanged(); + } // @@protoc_insertion_point(builder_scope:SerializedTypedActorRefProtocol) } static { defaultInstance = new SerializedTypedActorRefProtocol(true); - akka.remote.protocol.RemoteProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:SerializedTypedActorRefProtocol) } + public interface MessageProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required bytes message = 1; + boolean hasMessage(); + com.google.protobuf.ByteString getMessage(); + + // optional bytes messageManifest = 2; + boolean hasMessageManifest(); + com.google.protobuf.ByteString getMessageManifest(); + } public static final class MessageProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements MessageProtocolOrBuilder { // Use MessageProtocol.newBuilder() to construct. - private MessageProtocol() { - initFields(); + private MessageProtocol(Builder builder) { + super(builder); } private MessageProtocol(boolean noInit) {} @@ -3280,47 +5762,52 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.internal_static_MessageProtocol_fieldAccessorTable; } - // required .SerializationSchemeType serializationScheme = 1; - public static final int SERIALIZATIONSCHEME_FIELD_NUMBER = 1; - private boolean hasSerializationScheme; - private akka.remote.protocol.RemoteProtocol.SerializationSchemeType serializationScheme_; - public boolean hasSerializationScheme() { return hasSerializationScheme; } - public akka.remote.protocol.RemoteProtocol.SerializationSchemeType getSerializationScheme() { return serializationScheme_; } + private int bitField0_; + // required bytes message = 1; + public static final int MESSAGE_FIELD_NUMBER = 1; + private com.google.protobuf.ByteString message_; + public boolean hasMessage() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.google.protobuf.ByteString getMessage() { + return message_; + } - // required bytes message = 2; - public static final int MESSAGE_FIELD_NUMBER = 2; - private boolean hasMessage; - private com.google.protobuf.ByteString message_ = com.google.protobuf.ByteString.EMPTY; - public boolean hasMessage() { return hasMessage; } - public com.google.protobuf.ByteString getMessage() { return message_; } - - // optional bytes messageManifest = 3; - public static final int MESSAGEMANIFEST_FIELD_NUMBER = 3; - private boolean hasMessageManifest; - private com.google.protobuf.ByteString messageManifest_ = com.google.protobuf.ByteString.EMPTY; - public boolean hasMessageManifest() { return hasMessageManifest; } - public com.google.protobuf.ByteString getMessageManifest() { return messageManifest_; } + // optional bytes messageManifest = 2; + public static final int MESSAGEMANIFEST_FIELD_NUMBER = 2; + private com.google.protobuf.ByteString messageManifest_; + public boolean hasMessageManifest() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.google.protobuf.ByteString getMessageManifest() { + return messageManifest_; + } private void initFields() { - serializationScheme_ = akka.remote.protocol.RemoteProtocol.SerializationSchemeType.JAVA; + message_ = com.google.protobuf.ByteString.EMPTY; + messageManifest_ = com.google.protobuf.ByteString.EMPTY; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasSerializationScheme) return false; - if (!hasMessage) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasMessage()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasSerializationScheme()) { - output.writeEnum(1, getSerializationScheme().getNumber()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeBytes(1, message_); } - if (hasMessage()) { - output.writeBytes(2, getMessage()); - } - if (hasMessageManifest()) { - output.writeBytes(3, getMessageManifest()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, messageManifest_); } getUnknownFields().writeTo(output); } @@ -3331,23 +5818,26 @@ public final class RemoteProtocol { if (size != -1) return size; size = 0; - if (hasSerializationScheme()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeEnumSize(1, getSerializationScheme().getNumber()); + .computeBytesSize(1, message_); } - if (hasMessage()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeBytesSize(2, getMessage()); - } - if (hasMessageManifest()) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(3, getMessageManifest()); + .computeBytesSize(2, messageManifest_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.remote.protocol.RemoteProtocol.MessageProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -3422,34 +5912,53 @@ public final class RemoteProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.remote.protocol.RemoteProtocol.MessageProtocol result; - - // Construct using akka.remote.protocol.RemoteProtocol.MessageProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.remote.protocol.RemoteProtocol.MessageProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.remote.protocol.RemoteProtocol.MessageProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.internal_static_MessageProtocol_descriptor; } - protected akka.remote.protocol.RemoteProtocol.MessageProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.remote.protocol.RemoteProtocol.internal_static_MessageProtocol_fieldAccessorTable; + } + + // Construct using akka.remote.protocol.RemoteProtocol.MessageProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); - } - result = new akka.remote.protocol.RemoteProtocol.MessageProtocol(); + super.clear(); + message_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + messageManifest_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -3461,33 +5970,39 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.MessageProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.remote.protocol.RemoteProtocol.MessageProtocol build() { - if (result != null && !isInitialized()) { + akka.remote.protocol.RemoteProtocol.MessageProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.remote.protocol.RemoteProtocol.MessageProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.remote.protocol.RemoteProtocol.MessageProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.remote.protocol.RemoteProtocol.MessageProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.remote.protocol.RemoteProtocol.MessageProtocol result = new akka.remote.protocol.RemoteProtocol.MessageProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.remote.protocol.RemoteProtocol.MessageProtocol returnMe = result; - result = null; - return returnMe; + result.message_ = message_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.messageManifest_ = messageManifest_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -3501,9 +6016,6 @@ public final class RemoteProtocol { public Builder mergeFrom(akka.remote.protocol.RemoteProtocol.MessageProtocol other) { if (other == akka.remote.protocol.RemoteProtocol.MessageProtocol.getDefaultInstance()) return this; - if (other.hasSerializationScheme()) { - setSerializationScheme(other.getSerializationScheme()); - } if (other.hasMessage()) { setMessage(other.getMessage()); } @@ -3514,6 +6026,14 @@ public final class RemoteProtocol { return this; } + public final boolean isInitialized() { + if (!hasMessage()) { + + return false; + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -3526,98 +6046,78 @@ public final class RemoteProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; } - case 8: { - int rawValue = input.readEnum(); - akka.remote.protocol.RemoteProtocol.SerializationSchemeType value = akka.remote.protocol.RemoteProtocol.SerializationSchemeType.valueOf(rawValue); - if (value == null) { - unknownFields.mergeVarintField(1, rawValue); - } else { - setSerializationScheme(value); - } + case 10: { + bitField0_ |= 0x00000001; + message_ = input.readBytes(); break; } case 18: { - setMessage(input.readBytes()); - break; - } - case 26: { - setMessageManifest(input.readBytes()); + bitField0_ |= 0x00000002; + messageManifest_ = input.readBytes(); break; } } } } + private int bitField0_; - // required .SerializationSchemeType serializationScheme = 1; - public boolean hasSerializationScheme() { - return result.hasSerializationScheme(); - } - public akka.remote.protocol.RemoteProtocol.SerializationSchemeType getSerializationScheme() { - return result.getSerializationScheme(); - } - public Builder setSerializationScheme(akka.remote.protocol.RemoteProtocol.SerializationSchemeType value) { - if (value == null) { - throw new NullPointerException(); - } - result.hasSerializationScheme = true; - result.serializationScheme_ = value; - return this; - } - public Builder clearSerializationScheme() { - result.hasSerializationScheme = false; - result.serializationScheme_ = akka.remote.protocol.RemoteProtocol.SerializationSchemeType.JAVA; - return this; - } - - // required bytes message = 2; + // required bytes message = 1; + private com.google.protobuf.ByteString message_ = com.google.protobuf.ByteString.EMPTY; public boolean hasMessage() { - return result.hasMessage(); + return ((bitField0_ & 0x00000001) == 0x00000001); } public com.google.protobuf.ByteString getMessage() { - return result.getMessage(); + return message_; } public Builder setMessage(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } - result.hasMessage = true; - result.message_ = value; + bitField0_ |= 0x00000001; + message_ = value; + onChanged(); return this; } public Builder clearMessage() { - result.hasMessage = false; - result.message_ = getDefaultInstance().getMessage(); + bitField0_ = (bitField0_ & ~0x00000001); + message_ = getDefaultInstance().getMessage(); + onChanged(); return this; } - // optional bytes messageManifest = 3; + // optional bytes messageManifest = 2; + private com.google.protobuf.ByteString messageManifest_ = com.google.protobuf.ByteString.EMPTY; public boolean hasMessageManifest() { - return result.hasMessageManifest(); + return ((bitField0_ & 0x00000002) == 0x00000002); } public com.google.protobuf.ByteString getMessageManifest() { - return result.getMessageManifest(); + return messageManifest_; } public Builder setMessageManifest(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } - result.hasMessageManifest = true; - result.messageManifest_ = value; + bitField0_ |= 0x00000002; + messageManifest_ = value; + onChanged(); return this; } public Builder clearMessageManifest() { - result.hasMessageManifest = false; - result.messageManifest_ = getDefaultInstance().getMessageManifest(); + bitField0_ = (bitField0_ & ~0x00000002); + messageManifest_ = getDefaultInstance().getMessageManifest(); + onChanged(); return this; } @@ -3626,18 +6126,34 @@ public final class RemoteProtocol { static { defaultInstance = new MessageProtocol(true); - akka.remote.protocol.RemoteProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:MessageProtocol) } + public interface ActorInfoProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required .UuidProtocol uuid = 1; + boolean hasUuid(); + akka.remote.protocol.RemoteProtocol.UuidProtocol getUuid(); + akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder getUuidOrBuilder(); + + // required uint64 timeout = 2; + boolean hasTimeout(); + long getTimeout(); + + // optional string address = 3; + boolean hasAddress(); + String getAddress(); + } public static final class ActorInfoProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements ActorInfoProtocolOrBuilder { // Use ActorInfoProtocol.newBuilder() to construct. - private ActorInfoProtocol() { - initFields(); + private ActorInfoProtocol(Builder builder) { + super(builder); } private ActorInfoProtocol(boolean noInit) {} @@ -3660,48 +6176,99 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.internal_static_ActorInfoProtocol_fieldAccessorTable; } + private int bitField0_; // required .UuidProtocol uuid = 1; public static final int UUID_FIELD_NUMBER = 1; - private boolean hasUuid; private akka.remote.protocol.RemoteProtocol.UuidProtocol uuid_; - public boolean hasUuid() { return hasUuid; } - public akka.remote.protocol.RemoteProtocol.UuidProtocol getUuid() { return uuid_; } + public boolean hasUuid() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public akka.remote.protocol.RemoteProtocol.UuidProtocol getUuid() { + return uuid_; + } + public akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder getUuidOrBuilder() { + return uuid_; + } // required uint64 timeout = 2; public static final int TIMEOUT_FIELD_NUMBER = 2; - private boolean hasTimeout; - private long timeout_ = 0L; - public boolean hasTimeout() { return hasTimeout; } - public long getTimeout() { return timeout_; } + private long timeout_; + public boolean hasTimeout() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public long getTimeout() { + return timeout_; + } // optional string address = 3; public static final int ADDRESS_FIELD_NUMBER = 3; - private boolean hasAddress; - private java.lang.String address_ = ""; - public boolean hasAddress() { return hasAddress; } - public java.lang.String getAddress() { return address_; } + private java.lang.Object address_; + public boolean hasAddress() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public String getAddress() { + java.lang.Object ref = address_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + address_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getAddressBytes() { + java.lang.Object ref = address_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + address_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } private void initFields() { uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + timeout_ = 0L; + address_ = ""; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasUuid) return false; - if (!hasTimeout) return false; - if (!getUuid().isInitialized()) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasUuid()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasTimeout()) { + memoizedIsInitialized = 0; + return false; + } + if (!getUuid().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasUuid()) { - output.writeMessage(1, getUuid()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeMessage(1, uuid_); } - if (hasTimeout()) { - output.writeUInt64(2, getTimeout()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeUInt64(2, timeout_); } - if (hasAddress()) { - output.writeString(3, getAddress()); + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeBytes(3, getAddressBytes()); } getUnknownFields().writeTo(output); } @@ -3712,23 +6279,30 @@ public final class RemoteProtocol { if (size != -1) return size; size = 0; - if (hasUuid()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeMessageSize(1, getUuid()); + .computeMessageSize(1, uuid_); } - if (hasTimeout()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeUInt64Size(2, getTimeout()); + .computeUInt64Size(2, timeout_); } - if (hasAddress()) { + if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(3, getAddress()); + .computeBytesSize(3, getAddressBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.remote.protocol.RemoteProtocol.ActorInfoProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -3803,34 +6377,60 @@ public final class RemoteProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.remote.protocol.RemoteProtocol.ActorInfoProtocol result; - - // Construct using akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.remote.protocol.RemoteProtocol.ActorInfoProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.remote.protocol.RemoteProtocol.ActorInfoProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.internal_static_ActorInfoProtocol_descriptor; } - protected akka.remote.protocol.RemoteProtocol.ActorInfoProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.remote.protocol.RemoteProtocol.internal_static_ActorInfoProtocol_fieldAccessorTable; + } + + // Construct using akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getUuidFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); + super.clear(); + if (uuidBuilder_ == null) { + uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + } else { + uuidBuilder_.clear(); } - result = new akka.remote.protocol.RemoteProtocol.ActorInfoProtocol(); + bitField0_ = (bitField0_ & ~0x00000001); + timeout_ = 0L; + bitField0_ = (bitField0_ & ~0x00000002); + address_ = ""; + bitField0_ = (bitField0_ & ~0x00000004); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -3842,33 +6442,47 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.ActorInfoProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.remote.protocol.RemoteProtocol.ActorInfoProtocol build() { - if (result != null && !isInitialized()) { + akka.remote.protocol.RemoteProtocol.ActorInfoProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.remote.protocol.RemoteProtocol.ActorInfoProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.remote.protocol.RemoteProtocol.ActorInfoProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.remote.protocol.RemoteProtocol.ActorInfoProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.remote.protocol.RemoteProtocol.ActorInfoProtocol result = new akka.remote.protocol.RemoteProtocol.ActorInfoProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.remote.protocol.RemoteProtocol.ActorInfoProtocol returnMe = result; - result = null; - return returnMe; + if (uuidBuilder_ == null) { + result.uuid_ = uuid_; + } else { + result.uuid_ = uuidBuilder_.build(); + } + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.timeout_ = timeout_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.address_ = address_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -3895,6 +6509,22 @@ public final class RemoteProtocol { return this; } + public final boolean isInitialized() { + if (!hasUuid()) { + + return false; + } + if (!hasTimeout()) { + + return false; + } + if (!getUuid().isInitialized()) { + + return false; + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -3907,11 +6537,13 @@ public final class RemoteProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; @@ -3926,111 +6558,196 @@ public final class RemoteProtocol { break; } case 16: { - setTimeout(input.readUInt64()); + bitField0_ |= 0x00000002; + timeout_ = input.readUInt64(); break; } case 26: { - setAddress(input.readString()); + bitField0_ |= 0x00000004; + address_ = input.readBytes(); break; } } } } + private int bitField0_; // required .UuidProtocol uuid = 1; + private akka.remote.protocol.RemoteProtocol.UuidProtocol uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.UuidProtocol, akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder, akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder> uuidBuilder_; public boolean hasUuid() { - return result.hasUuid(); + return ((bitField0_ & 0x00000001) == 0x00000001); } public akka.remote.protocol.RemoteProtocol.UuidProtocol getUuid() { - return result.getUuid(); + if (uuidBuilder_ == null) { + return uuid_; + } else { + return uuidBuilder_.getMessage(); + } } public Builder setUuid(akka.remote.protocol.RemoteProtocol.UuidProtocol value) { - if (value == null) { - throw new NullPointerException(); + if (uuidBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + uuid_ = value; + onChanged(); + } else { + uuidBuilder_.setMessage(value); } - result.hasUuid = true; - result.uuid_ = value; + bitField0_ |= 0x00000001; return this; } - public Builder setUuid(akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder builderForValue) { - result.hasUuid = true; - result.uuid_ = builderForValue.build(); + public Builder setUuid( + akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder builderForValue) { + if (uuidBuilder_ == null) { + uuid_ = builderForValue.build(); + onChanged(); + } else { + uuidBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000001; return this; } public Builder mergeUuid(akka.remote.protocol.RemoteProtocol.UuidProtocol value) { - if (result.hasUuid() && - result.uuid_ != akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance()) { - result.uuid_ = - akka.remote.protocol.RemoteProtocol.UuidProtocol.newBuilder(result.uuid_).mergeFrom(value).buildPartial(); + if (uuidBuilder_ == null) { + if (((bitField0_ & 0x00000001) == 0x00000001) && + uuid_ != akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance()) { + uuid_ = + akka.remote.protocol.RemoteProtocol.UuidProtocol.newBuilder(uuid_).mergeFrom(value).buildPartial(); + } else { + uuid_ = value; + } + onChanged(); } else { - result.uuid_ = value; + uuidBuilder_.mergeFrom(value); } - result.hasUuid = true; + bitField0_ |= 0x00000001; return this; } public Builder clearUuid() { - result.hasUuid = false; - result.uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + if (uuidBuilder_ == null) { + uuid_ = akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); + onChanged(); + } else { + uuidBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000001); return this; } + public akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder getUuidBuilder() { + bitField0_ |= 0x00000001; + onChanged(); + return getUuidFieldBuilder().getBuilder(); + } + public akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder getUuidOrBuilder() { + if (uuidBuilder_ != null) { + return uuidBuilder_.getMessageOrBuilder(); + } else { + return uuid_; + } + } + private com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.UuidProtocol, akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder, akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder> + getUuidFieldBuilder() { + if (uuidBuilder_ == null) { + uuidBuilder_ = new com.google.protobuf.SingleFieldBuilder< + akka.remote.protocol.RemoteProtocol.UuidProtocol, akka.remote.protocol.RemoteProtocol.UuidProtocol.Builder, akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder>( + uuid_, + getParentForChildren(), + isClean()); + uuid_ = null; + } + return uuidBuilder_; + } // required uint64 timeout = 2; + private long timeout_ ; public boolean hasTimeout() { - return result.hasTimeout(); + return ((bitField0_ & 0x00000002) == 0x00000002); } public long getTimeout() { - return result.getTimeout(); + return timeout_; } public Builder setTimeout(long value) { - result.hasTimeout = true; - result.timeout_ = value; + bitField0_ |= 0x00000002; + timeout_ = value; + onChanged(); return this; } public Builder clearTimeout() { - result.hasTimeout = false; - result.timeout_ = 0L; + bitField0_ = (bitField0_ & ~0x00000002); + timeout_ = 0L; + onChanged(); return this; } // optional string address = 3; + private java.lang.Object address_ = ""; public boolean hasAddress() { - return result.hasAddress(); + return ((bitField0_ & 0x00000004) == 0x00000004); } - public java.lang.String getAddress() { - return result.getAddress(); + public String getAddress() { + java.lang.Object ref = address_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + address_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setAddress(java.lang.String value) { + public Builder setAddress(String value) { if (value == null) { throw new NullPointerException(); } - result.hasAddress = true; - result.address_ = value; + bitField0_ |= 0x00000004; + address_ = value; + onChanged(); return this; } public Builder clearAddress() { - result.hasAddress = false; - result.address_ = getDefaultInstance().getAddress(); + bitField0_ = (bitField0_ & ~0x00000004); + address_ = getDefaultInstance().getAddress(); + onChanged(); return this; } + void setAddress(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000004; + address_ = value; + onChanged(); + } // @@protoc_insertion_point(builder_scope:ActorInfoProtocol) } static { defaultInstance = new ActorInfoProtocol(true); - akka.remote.protocol.RemoteProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:ActorInfoProtocol) } + public interface UuidProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required uint64 high = 1; + boolean hasHigh(); + long getHigh(); + + // required uint64 low = 2; + boolean hasLow(); + long getLow(); + } public static final class UuidProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements UuidProtocolOrBuilder { // Use UuidProtocol.newBuilder() to construct. - private UuidProtocol() { - initFields(); + private UuidProtocol(Builder builder) { + super(builder); } private UuidProtocol(boolean noInit) {} @@ -4053,36 +6770,56 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.internal_static_UuidProtocol_fieldAccessorTable; } + private int bitField0_; // required uint64 high = 1; public static final int HIGH_FIELD_NUMBER = 1; - private boolean hasHigh; - private long high_ = 0L; - public boolean hasHigh() { return hasHigh; } - public long getHigh() { return high_; } + private long high_; + public boolean hasHigh() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public long getHigh() { + return high_; + } // required uint64 low = 2; public static final int LOW_FIELD_NUMBER = 2; - private boolean hasLow; - private long low_ = 0L; - public boolean hasLow() { return hasLow; } - public long getLow() { return low_; } + private long low_; + public boolean hasLow() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public long getLow() { + return low_; + } private void initFields() { + high_ = 0L; + low_ = 0L; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasHigh) return false; - if (!hasLow) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasHigh()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasLow()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasHigh()) { - output.writeUInt64(1, getHigh()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeUInt64(1, high_); } - if (hasLow()) { - output.writeUInt64(2, getLow()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeUInt64(2, low_); } getUnknownFields().writeTo(output); } @@ -4093,19 +6830,26 @@ public final class RemoteProtocol { if (size != -1) return size; size = 0; - if (hasHigh()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeUInt64Size(1, getHigh()); + .computeUInt64Size(1, high_); } - if (hasLow()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeUInt64Size(2, getLow()); + .computeUInt64Size(2, low_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.remote.protocol.RemoteProtocol.UuidProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -4180,34 +6924,53 @@ public final class RemoteProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.remote.protocol.RemoteProtocol.UuidProtocol result; - - // Construct using akka.remote.protocol.RemoteProtocol.UuidProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.remote.protocol.RemoteProtocol.UuidProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.remote.protocol.RemoteProtocol.UuidProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.internal_static_UuidProtocol_descriptor; } - protected akka.remote.protocol.RemoteProtocol.UuidProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.remote.protocol.RemoteProtocol.internal_static_UuidProtocol_fieldAccessorTable; + } + + // Construct using akka.remote.protocol.RemoteProtocol.UuidProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); - } - result = new akka.remote.protocol.RemoteProtocol.UuidProtocol(); + super.clear(); + high_ = 0L; + bitField0_ = (bitField0_ & ~0x00000001); + low_ = 0L; + bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -4219,33 +6982,39 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.UuidProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.remote.protocol.RemoteProtocol.UuidProtocol build() { - if (result != null && !isInitialized()) { + akka.remote.protocol.RemoteProtocol.UuidProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.remote.protocol.RemoteProtocol.UuidProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.remote.protocol.RemoteProtocol.UuidProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.remote.protocol.RemoteProtocol.UuidProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.remote.protocol.RemoteProtocol.UuidProtocol result = new akka.remote.protocol.RemoteProtocol.UuidProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.remote.protocol.RemoteProtocol.UuidProtocol returnMe = result; - result = null; - return returnMe; + result.high_ = high_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.low_ = low_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -4269,6 +7038,18 @@ public final class RemoteProtocol { return this; } + public final boolean isInitialized() { + if (!hasHigh()) { + + return false; + } + if (!hasLow()) { + + return false; + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -4281,61 +7062,72 @@ public final class RemoteProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; } case 8: { - setHigh(input.readUInt64()); + bitField0_ |= 0x00000001; + high_ = input.readUInt64(); break; } case 16: { - setLow(input.readUInt64()); + bitField0_ |= 0x00000002; + low_ = input.readUInt64(); break; } } } } + private int bitField0_; // required uint64 high = 1; + private long high_ ; public boolean hasHigh() { - return result.hasHigh(); + return ((bitField0_ & 0x00000001) == 0x00000001); } public long getHigh() { - return result.getHigh(); + return high_; } public Builder setHigh(long value) { - result.hasHigh = true; - result.high_ = value; + bitField0_ |= 0x00000001; + high_ = value; + onChanged(); return this; } public Builder clearHigh() { - result.hasHigh = false; - result.high_ = 0L; + bitField0_ = (bitField0_ & ~0x00000001); + high_ = 0L; + onChanged(); return this; } // required uint64 low = 2; + private long low_ ; public boolean hasLow() { - return result.hasLow(); + return ((bitField0_ & 0x00000002) == 0x00000002); } public long getLow() { - return result.getLow(); + return low_; } public Builder setLow(long value) { - result.hasLow = true; - result.low_ = value; + bitField0_ |= 0x00000002; + low_ = value; + onChanged(); return this; } public Builder clearLow() { - result.hasLow = false; - result.low_ = 0L; + bitField0_ = (bitField0_ & ~0x00000002); + low_ = 0L; + onChanged(); return this; } @@ -4344,18 +7136,29 @@ public final class RemoteProtocol { static { defaultInstance = new UuidProtocol(true); - akka.remote.protocol.RemoteProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:UuidProtocol) } + public interface MetadataEntryProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required string key = 1; + boolean hasKey(); + String getKey(); + + // required bytes value = 2; + boolean hasValue(); + com.google.protobuf.ByteString getValue(); + } public static final class MetadataEntryProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements MetadataEntryProtocolOrBuilder { // Use MetadataEntryProtocol.newBuilder() to construct. - private MetadataEntryProtocol() { - initFields(); + private MetadataEntryProtocol(Builder builder) { + super(builder); } private MetadataEntryProtocol(boolean noInit) {} @@ -4378,36 +7181,78 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.internal_static_MetadataEntryProtocol_fieldAccessorTable; } + private int bitField0_; // required string key = 1; public static final int KEY_FIELD_NUMBER = 1; - private boolean hasKey; - private java.lang.String key_ = ""; - public boolean hasKey() { return hasKey; } - public java.lang.String getKey() { return key_; } + private java.lang.Object key_; + public boolean hasKey() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public String getKey() { + java.lang.Object ref = key_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + key_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getKeyBytes() { + java.lang.Object ref = key_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + key_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } // required bytes value = 2; public static final int VALUE_FIELD_NUMBER = 2; - private boolean hasValue; - private com.google.protobuf.ByteString value_ = com.google.protobuf.ByteString.EMPTY; - public boolean hasValue() { return hasValue; } - public com.google.protobuf.ByteString getValue() { return value_; } + private com.google.protobuf.ByteString value_; + public boolean hasValue() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.google.protobuf.ByteString getValue() { + return value_; + } private void initFields() { + key_ = ""; + value_ = com.google.protobuf.ByteString.EMPTY; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasKey) return false; - if (!hasValue) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasKey()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasValue()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasKey()) { - output.writeString(1, getKey()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeBytes(1, getKeyBytes()); } - if (hasValue()) { - output.writeBytes(2, getValue()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, value_); } getUnknownFields().writeTo(output); } @@ -4418,19 +7263,26 @@ public final class RemoteProtocol { if (size != -1) return size; size = 0; - if (hasKey()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(1, getKey()); + .computeBytesSize(1, getKeyBytes()); } - if (hasValue()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeBytesSize(2, getValue()); + .computeBytesSize(2, value_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -4505,34 +7357,53 @@ public final class RemoteProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol result; - - // Construct using akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.remote.protocol.RemoteProtocol.MetadataEntryProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.internal_static_MetadataEntryProtocol_descriptor; } - protected akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.remote.protocol.RemoteProtocol.internal_static_MetadataEntryProtocol_fieldAccessorTable; + } + + // Construct using akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); - } - result = new akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol(); + super.clear(); + key_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + value_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -4544,33 +7415,39 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol build() { - if (result != null && !isInitialized()) { + akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol result = new akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.remote.protocol.RemoteProtocol.MetadataEntryProtocol returnMe = result; - result = null; - return returnMe; + result.key_ = key_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.value_ = value_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -4594,6 +7471,18 @@ public final class RemoteProtocol { return this; } + public final boolean isInitialized() { + if (!hasKey()) { + + return false; + } + if (!hasValue()) { + + return false; + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -4606,67 +7495,90 @@ public final class RemoteProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; } case 10: { - setKey(input.readString()); + bitField0_ |= 0x00000001; + key_ = input.readBytes(); break; } case 18: { - setValue(input.readBytes()); + bitField0_ |= 0x00000002; + value_ = input.readBytes(); break; } } } } + private int bitField0_; // required string key = 1; + private java.lang.Object key_ = ""; public boolean hasKey() { - return result.hasKey(); + return ((bitField0_ & 0x00000001) == 0x00000001); } - public java.lang.String getKey() { - return result.getKey(); + public String getKey() { + java.lang.Object ref = key_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + key_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setKey(java.lang.String value) { + public Builder setKey(String value) { if (value == null) { throw new NullPointerException(); } - result.hasKey = true; - result.key_ = value; + bitField0_ |= 0x00000001; + key_ = value; + onChanged(); return this; } public Builder clearKey() { - result.hasKey = false; - result.key_ = getDefaultInstance().getKey(); + bitField0_ = (bitField0_ & ~0x00000001); + key_ = getDefaultInstance().getKey(); + onChanged(); return this; } + void setKey(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000001; + key_ = value; + onChanged(); + } // required bytes value = 2; + private com.google.protobuf.ByteString value_ = com.google.protobuf.ByteString.EMPTY; public boolean hasValue() { - return result.hasValue(); + return ((bitField0_ & 0x00000002) == 0x00000002); } public com.google.protobuf.ByteString getValue() { - return result.getValue(); + return value_; } public Builder setValue(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } - result.hasValue = true; - result.value_ = value; + bitField0_ |= 0x00000002; + value_ = value; + onChanged(); return this; } public Builder clearValue() { - result.hasValue = false; - result.value_ = getDefaultInstance().getValue(); + bitField0_ = (bitField0_ & ~0x00000002); + value_ = getDefaultInstance().getValue(); + onChanged(); return this; } @@ -4675,18 +7587,25 @@ public final class RemoteProtocol { static { defaultInstance = new MetadataEntryProtocol(true); - akka.remote.protocol.RemoteProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:MetadataEntryProtocol) } + public interface LifeCycleProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required .LifeCycleType lifeCycle = 1; + boolean hasLifeCycle(); + akka.remote.protocol.RemoteProtocol.LifeCycleType getLifeCycle(); + } public static final class LifeCycleProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements LifeCycleProtocolOrBuilder { // Use LifeCycleProtocol.newBuilder() to construct. - private LifeCycleProtocol() { - initFields(); + private LifeCycleProtocol(Builder builder) { + super(builder); } private LifeCycleProtocol(boolean noInit) {} @@ -4709,26 +7628,38 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.internal_static_LifeCycleProtocol_fieldAccessorTable; } + private int bitField0_; // required .LifeCycleType lifeCycle = 1; public static final int LIFECYCLE_FIELD_NUMBER = 1; - private boolean hasLifeCycle; private akka.remote.protocol.RemoteProtocol.LifeCycleType lifeCycle_; - public boolean hasLifeCycle() { return hasLifeCycle; } - public akka.remote.protocol.RemoteProtocol.LifeCycleType getLifeCycle() { return lifeCycle_; } + public boolean hasLifeCycle() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public akka.remote.protocol.RemoteProtocol.LifeCycleType getLifeCycle() { + return lifeCycle_; + } private void initFields() { lifeCycle_ = akka.remote.protocol.RemoteProtocol.LifeCycleType.PERMANENT; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasLifeCycle) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasLifeCycle()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasLifeCycle()) { - output.writeEnum(1, getLifeCycle().getNumber()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeEnum(1, lifeCycle_.getNumber()); } getUnknownFields().writeTo(output); } @@ -4739,15 +7670,22 @@ public final class RemoteProtocol { if (size != -1) return size; size = 0; - if (hasLifeCycle()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeEnumSize(1, getLifeCycle().getNumber()); + .computeEnumSize(1, lifeCycle_.getNumber()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.remote.protocol.RemoteProtocol.LifeCycleProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -4822,34 +7760,51 @@ public final class RemoteProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.remote.protocol.RemoteProtocol.LifeCycleProtocol result; - - // Construct using akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.remote.protocol.RemoteProtocol.LifeCycleProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.remote.protocol.RemoteProtocol.LifeCycleProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.internal_static_LifeCycleProtocol_descriptor; } - protected akka.remote.protocol.RemoteProtocol.LifeCycleProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.remote.protocol.RemoteProtocol.internal_static_LifeCycleProtocol_fieldAccessorTable; + } + + // Construct using akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); - } - result = new akka.remote.protocol.RemoteProtocol.LifeCycleProtocol(); + super.clear(); + lifeCycle_ = akka.remote.protocol.RemoteProtocol.LifeCycleType.PERMANENT; + bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -4861,33 +7816,35 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.LifeCycleProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.remote.protocol.RemoteProtocol.LifeCycleProtocol build() { - if (result != null && !isInitialized()) { + akka.remote.protocol.RemoteProtocol.LifeCycleProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.remote.protocol.RemoteProtocol.LifeCycleProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.remote.protocol.RemoteProtocol.LifeCycleProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.remote.protocol.RemoteProtocol.LifeCycleProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.remote.protocol.RemoteProtocol.LifeCycleProtocol result = new akka.remote.protocol.RemoteProtocol.LifeCycleProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.remote.protocol.RemoteProtocol.LifeCycleProtocol returnMe = result; - result = null; - return returnMe; + result.lifeCycle_ = lifeCycle_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -4908,6 +7865,14 @@ public final class RemoteProtocol { return this; } + public final boolean isInitialized() { + if (!hasLifeCycle()) { + + return false; + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -4920,11 +7885,13 @@ public final class RemoteProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; @@ -4935,7 +7902,8 @@ public final class RemoteProtocol { if (value == null) { unknownFields.mergeVarintField(1, rawValue); } else { - setLifeCycle(value); + bitField0_ |= 0x00000001; + lifeCycle_ = value; } break; } @@ -4943,25 +7911,29 @@ public final class RemoteProtocol { } } + private int bitField0_; // required .LifeCycleType lifeCycle = 1; + private akka.remote.protocol.RemoteProtocol.LifeCycleType lifeCycle_ = akka.remote.protocol.RemoteProtocol.LifeCycleType.PERMANENT; public boolean hasLifeCycle() { - return result.hasLifeCycle(); + return ((bitField0_ & 0x00000001) == 0x00000001); } public akka.remote.protocol.RemoteProtocol.LifeCycleType getLifeCycle() { - return result.getLifeCycle(); + return lifeCycle_; } public Builder setLifeCycle(akka.remote.protocol.RemoteProtocol.LifeCycleType value) { if (value == null) { throw new NullPointerException(); } - result.hasLifeCycle = true; - result.lifeCycle_ = value; + bitField0_ |= 0x00000001; + lifeCycle_ = value; + onChanged(); return this; } public Builder clearLifeCycle() { - result.hasLifeCycle = false; - result.lifeCycle_ = akka.remote.protocol.RemoteProtocol.LifeCycleType.PERMANENT; + bitField0_ = (bitField0_ & ~0x00000001); + lifeCycle_ = akka.remote.protocol.RemoteProtocol.LifeCycleType.PERMANENT; + onChanged(); return this; } @@ -4970,18 +7942,29 @@ public final class RemoteProtocol { static { defaultInstance = new LifeCycleProtocol(true); - akka.remote.protocol.RemoteProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:LifeCycleProtocol) } + public interface AddressProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required string hostname = 1; + boolean hasHostname(); + String getHostname(); + + // required uint32 port = 2; + boolean hasPort(); + int getPort(); + } public static final class AddressProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements AddressProtocolOrBuilder { // Use AddressProtocol.newBuilder() to construct. - private AddressProtocol() { - initFields(); + private AddressProtocol(Builder builder) { + super(builder); } private AddressProtocol(boolean noInit) {} @@ -5004,36 +7987,78 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.internal_static_AddressProtocol_fieldAccessorTable; } + private int bitField0_; // required string hostname = 1; public static final int HOSTNAME_FIELD_NUMBER = 1; - private boolean hasHostname; - private java.lang.String hostname_ = ""; - public boolean hasHostname() { return hasHostname; } - public java.lang.String getHostname() { return hostname_; } + private java.lang.Object hostname_; + public boolean hasHostname() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public String getHostname() { + java.lang.Object ref = hostname_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + hostname_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getHostnameBytes() { + java.lang.Object ref = hostname_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + hostname_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } // required uint32 port = 2; public static final int PORT_FIELD_NUMBER = 2; - private boolean hasPort; - private int port_ = 0; - public boolean hasPort() { return hasPort; } - public int getPort() { return port_; } + private int port_; + public boolean hasPort() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public int getPort() { + return port_; + } private void initFields() { + hostname_ = ""; + port_ = 0; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasHostname) return false; - if (!hasPort) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasHostname()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasPort()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasHostname()) { - output.writeString(1, getHostname()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeBytes(1, getHostnameBytes()); } - if (hasPort()) { - output.writeUInt32(2, getPort()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeUInt32(2, port_); } getUnknownFields().writeTo(output); } @@ -5044,19 +8069,26 @@ public final class RemoteProtocol { if (size != -1) return size; size = 0; - if (hasHostname()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(1, getHostname()); + .computeBytesSize(1, getHostnameBytes()); } - if (hasPort()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeUInt32Size(2, getPort()); + .computeUInt32Size(2, port_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.remote.protocol.RemoteProtocol.AddressProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -5131,34 +8163,53 @@ public final class RemoteProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.remote.protocol.RemoteProtocol.AddressProtocol result; - - // Construct using akka.remote.protocol.RemoteProtocol.AddressProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.remote.protocol.RemoteProtocol.AddressProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.remote.protocol.RemoteProtocol.AddressProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.internal_static_AddressProtocol_descriptor; } - protected akka.remote.protocol.RemoteProtocol.AddressProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.remote.protocol.RemoteProtocol.internal_static_AddressProtocol_fieldAccessorTable; + } + + // Construct using akka.remote.protocol.RemoteProtocol.AddressProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); - } - result = new akka.remote.protocol.RemoteProtocol.AddressProtocol(); + super.clear(); + hostname_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + port_ = 0; + bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -5170,33 +8221,39 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.AddressProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.remote.protocol.RemoteProtocol.AddressProtocol build() { - if (result != null && !isInitialized()) { + akka.remote.protocol.RemoteProtocol.AddressProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.remote.protocol.RemoteProtocol.AddressProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.remote.protocol.RemoteProtocol.AddressProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.remote.protocol.RemoteProtocol.AddressProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.remote.protocol.RemoteProtocol.AddressProtocol result = new akka.remote.protocol.RemoteProtocol.AddressProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.remote.protocol.RemoteProtocol.AddressProtocol returnMe = result; - result = null; - return returnMe; + result.hostname_ = hostname_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.port_ = port_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -5220,6 +8277,18 @@ public final class RemoteProtocol { return this; } + public final boolean isInitialized() { + if (!hasHostname()) { + + return false; + } + if (!hasPort()) { + + return false; + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -5232,64 +8301,87 @@ public final class RemoteProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; } case 10: { - setHostname(input.readString()); + bitField0_ |= 0x00000001; + hostname_ = input.readBytes(); break; } case 16: { - setPort(input.readUInt32()); + bitField0_ |= 0x00000002; + port_ = input.readUInt32(); break; } } } } + private int bitField0_; // required string hostname = 1; + private java.lang.Object hostname_ = ""; public boolean hasHostname() { - return result.hasHostname(); + return ((bitField0_ & 0x00000001) == 0x00000001); } - public java.lang.String getHostname() { - return result.getHostname(); + public String getHostname() { + java.lang.Object ref = hostname_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + hostname_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setHostname(java.lang.String value) { + public Builder setHostname(String value) { if (value == null) { throw new NullPointerException(); } - result.hasHostname = true; - result.hostname_ = value; + bitField0_ |= 0x00000001; + hostname_ = value; + onChanged(); return this; } public Builder clearHostname() { - result.hasHostname = false; - result.hostname_ = getDefaultInstance().getHostname(); + bitField0_ = (bitField0_ & ~0x00000001); + hostname_ = getDefaultInstance().getHostname(); + onChanged(); return this; } + void setHostname(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000001; + hostname_ = value; + onChanged(); + } // required uint32 port = 2; + private int port_ ; public boolean hasPort() { - return result.hasPort(); + return ((bitField0_ & 0x00000002) == 0x00000002); } public int getPort() { - return result.getPort(); + return port_; } public Builder setPort(int value) { - result.hasPort = true; - result.port_ = value; + bitField0_ |= 0x00000002; + port_ = value; + onChanged(); return this; } public Builder clearPort() { - result.hasPort = false; - result.port_ = 0; + bitField0_ = (bitField0_ & ~0x00000002); + port_ = 0; + onChanged(); return this; } @@ -5298,18 +8390,29 @@ public final class RemoteProtocol { static { defaultInstance = new AddressProtocol(true); - akka.remote.protocol.RemoteProtocol.internalForceInit(); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:AddressProtocol) } + public interface ExceptionProtocolOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required string classname = 1; + boolean hasClassname(); + String getClassname(); + + // required string message = 2; + boolean hasMessage(); + String getMessage(); + } public static final class ExceptionProtocol extends - com.google.protobuf.GeneratedMessage { + com.google.protobuf.GeneratedMessage + implements ExceptionProtocolOrBuilder { // Use ExceptionProtocol.newBuilder() to construct. - private ExceptionProtocol() { - initFields(); + private ExceptionProtocol(Builder builder) { + super(builder); } private ExceptionProtocol(boolean noInit) {} @@ -5332,36 +8435,100 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.internal_static_ExceptionProtocol_fieldAccessorTable; } + private int bitField0_; // required string classname = 1; public static final int CLASSNAME_FIELD_NUMBER = 1; - private boolean hasClassname; - private java.lang.String classname_ = ""; - public boolean hasClassname() { return hasClassname; } - public java.lang.String getClassname() { return classname_; } + private java.lang.Object classname_; + public boolean hasClassname() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public String getClassname() { + java.lang.Object ref = classname_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + classname_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getClassnameBytes() { + java.lang.Object ref = classname_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + classname_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } // required string message = 2; public static final int MESSAGE_FIELD_NUMBER = 2; - private boolean hasMessage; - private java.lang.String message_ = ""; - public boolean hasMessage() { return hasMessage; } - public java.lang.String getMessage() { return message_; } + private java.lang.Object message_; + public boolean hasMessage() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public String getMessage() { + java.lang.Object ref = message_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + message_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } private void initFields() { + classname_ = ""; + message_ = ""; } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { - if (!hasClassname) return false; - if (!hasMessage) return false; + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasClassname()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasMessage()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); - if (hasClassname()) { - output.writeString(1, getClassname()); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeBytes(1, getClassnameBytes()); } - if (hasMessage()) { - output.writeString(2, getMessage()); + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, getMessageBytes()); } getUnknownFields().writeTo(output); } @@ -5372,19 +8539,26 @@ public final class RemoteProtocol { if (size != -1) return size; size = 0; - if (hasClassname()) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(1, getClassname()); + .computeBytesSize(1, getClassnameBytes()); } - if (hasMessage()) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream - .computeStringSize(2, getMessage()); + .computeBytesSize(2, getMessageBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + public static akka.remote.protocol.RemoteProtocol.ExceptionProtocol parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { @@ -5459,34 +8633,53 @@ public final class RemoteProtocol { } public Builder toBuilder() { return newBuilder(this); } + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder { - private akka.remote.protocol.RemoteProtocol.ExceptionProtocol result; - - // Construct using akka.remote.protocol.RemoteProtocol.ExceptionProtocol.newBuilder() - private Builder() {} - - private static Builder create() { - Builder builder = new Builder(); - builder.result = new akka.remote.protocol.RemoteProtocol.ExceptionProtocol(); - return builder; + com.google.protobuf.GeneratedMessage.Builder + implements akka.remote.protocol.RemoteProtocol.ExceptionProtocolOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.remote.protocol.RemoteProtocol.internal_static_ExceptionProtocol_descriptor; } - protected akka.remote.protocol.RemoteProtocol.ExceptionProtocol internalGetResult() { - return result; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.remote.protocol.RemoteProtocol.internal_static_ExceptionProtocol_fieldAccessorTable; + } + + // Construct using akka.remote.protocol.RemoteProtocol.ExceptionProtocol.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); } public Builder clear() { - if (result == null) { - throw new IllegalStateException( - "Cannot call clear() after build()."); - } - result = new akka.remote.protocol.RemoteProtocol.ExceptionProtocol(); + super.clear(); + classname_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + message_ = ""; + bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { - return create().mergeFrom(result); + return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor @@ -5498,33 +8691,39 @@ public final class RemoteProtocol { return akka.remote.protocol.RemoteProtocol.ExceptionProtocol.getDefaultInstance(); } - public boolean isInitialized() { - return result.isInitialized(); - } public akka.remote.protocol.RemoteProtocol.ExceptionProtocol build() { - if (result != null && !isInitialized()) { + akka.remote.protocol.RemoteProtocol.ExceptionProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException(result); } - return buildPartial(); + return result; } private akka.remote.protocol.RemoteProtocol.ExceptionProtocol buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { - if (!isInitialized()) { + akka.remote.protocol.RemoteProtocol.ExceptionProtocol result = buildPartial(); + if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } - return buildPartial(); + return result; } public akka.remote.protocol.RemoteProtocol.ExceptionProtocol buildPartial() { - if (result == null) { - throw new IllegalStateException( - "build() has already been called on this Builder."); + akka.remote.protocol.RemoteProtocol.ExceptionProtocol result = new akka.remote.protocol.RemoteProtocol.ExceptionProtocol(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; } - akka.remote.protocol.RemoteProtocol.ExceptionProtocol returnMe = result; - result = null; - return returnMe; + result.classname_ = classname_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.message_ = message_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } public Builder mergeFrom(com.google.protobuf.Message other) { @@ -5548,6 +8747,18 @@ public final class RemoteProtocol { return this; } + public final boolean isInitialized() { + if (!hasClassname()) { + + return false; + } + if (!hasMessage()) { + + return false; + } + return true; + } + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -5560,76 +8771,110 @@ public final class RemoteProtocol { switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); + onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); + onChanged(); return this; } break; } case 10: { - setClassname(input.readString()); + bitField0_ |= 0x00000001; + classname_ = input.readBytes(); break; } case 18: { - setMessage(input.readString()); + bitField0_ |= 0x00000002; + message_ = input.readBytes(); break; } } } } + private int bitField0_; // required string classname = 1; + private java.lang.Object classname_ = ""; public boolean hasClassname() { - return result.hasClassname(); + return ((bitField0_ & 0x00000001) == 0x00000001); } - public java.lang.String getClassname() { - return result.getClassname(); + public String getClassname() { + java.lang.Object ref = classname_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + classname_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setClassname(java.lang.String value) { + public Builder setClassname(String value) { if (value == null) { throw new NullPointerException(); } - result.hasClassname = true; - result.classname_ = value; + bitField0_ |= 0x00000001; + classname_ = value; + onChanged(); return this; } public Builder clearClassname() { - result.hasClassname = false; - result.classname_ = getDefaultInstance().getClassname(); + bitField0_ = (bitField0_ & ~0x00000001); + classname_ = getDefaultInstance().getClassname(); + onChanged(); return this; } + void setClassname(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000001; + classname_ = value; + onChanged(); + } // required string message = 2; + private java.lang.Object message_ = ""; public boolean hasMessage() { - return result.hasMessage(); + return ((bitField0_ & 0x00000002) == 0x00000002); } - public java.lang.String getMessage() { - return result.getMessage(); + public String getMessage() { + java.lang.Object ref = message_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + message_ = s; + return s; + } else { + return (String) ref; + } } - public Builder setMessage(java.lang.String value) { + public Builder setMessage(String value) { if (value == null) { throw new NullPointerException(); } - result.hasMessage = true; - result.message_ = value; + bitField0_ |= 0x00000002; + message_ = value; + onChanged(); return this; } public Builder clearMessage() { - result.hasMessage = false; - result.message_ = getDefaultInstance().getMessage(); + bitField0_ = (bitField0_ & ~0x00000002); + message_ = getDefaultInstance().getMessage(); + onChanged(); return this; } + void setMessage(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000002; + message_ = value; + onChanged(); + } // @@protoc_insertion_point(builder_scope:ExceptionProtocol) } static { defaultInstance = new ExceptionProtocol(true); - akka.remote.protocol.RemoteProtocol.internalForceInit(); defaultInstance.initFields(); } @@ -5725,34 +8970,39 @@ public final class RemoteProtocol { "\013commandType\030\002 \002(\0162\014.CommandType\"U\n\026Remo" + "teActorRefProtocol\022\017\n\007address\030\001 \002(\t\022\031\n\021i" + "netSocketAddress\030\002 \002(\014\022\017\n\007timeout\030\003 \001(\004\"" + - "\323\002\n\032SerializedActorRefProtocol\022\033\n\004uuid\030\001" + + "\277\003\n\032SerializedActorRefProtocol\022\033\n\004uuid\030\001" + " \002(\0132\r.UuidProtocol\022\017\n\007address\030\002 \002(\t\022\026\n\016" + "actorClassname\030\003 \002(\t\022\025\n\ractorInstance\030\004 " + "\001(\014\022\033\n\023serializerClassname\030\005 \001(\t\022\017\n\007time" + "out\030\006 \001(\004\022\026\n\016receiveTimeout\030\007 \001(\004\022%\n\tlif", "eCycle\030\010 \001(\0132\022.LifeCycleProtocol\022+\n\nsupe" + "rvisor\030\t \001(\0132\027.RemoteActorRefProtocol\022\024\n" + - "\014hotswapStack\030\n \001(\014\022(\n\010messages\030\013 \003(\0132\026." + - "RemoteMessageProtocol\"g\n\037SerializedTyped" + - "ActorRefProtocol\022-\n\010actorRef\030\001 \002(\0132\033.Ser" + - "ializedActorRefProtocol\022\025\n\rinterfaceName" + - "\030\002 \002(\t\"r\n\017MessageProtocol\0225\n\023serializati" + - "onScheme\030\001 \002(\0162\030.SerializationSchemeType" + - "\022\017\n\007message\030\002 \002(\014\022\027\n\017messageManifest\030\003 \001" + - "(\014\"R\n\021ActorInfoProtocol\022\033\n\004uuid\030\001 \002(\0132\r.", - "UuidProtocol\022\017\n\007timeout\030\002 \002(\004\022\017\n\007address" + - "\030\003 \001(\t\")\n\014UuidProtocol\022\014\n\004high\030\001 \002(\004\022\013\n\003" + - "low\030\002 \002(\004\"3\n\025MetadataEntryProtocol\022\013\n\003ke" + - "y\030\001 \002(\t\022\r\n\005value\030\002 \002(\014\"6\n\021LifeCycleProto" + - "col\022!\n\tlifeCycle\030\001 \002(\0162\016.LifeCycleType\"1" + - "\n\017AddressProtocol\022\020\n\010hostname\030\001 \002(\t\022\014\n\004p" + - "ort\030\002 \002(\r\"7\n\021ExceptionProtocol\022\021\n\tclassn" + - "ame\030\001 \002(\t\022\017\n\007message\030\002 \002(\t*(\n\013CommandTyp" + - "e\022\013\n\007CONNECT\020\001\022\014\n\010SHUTDOWN\020\002*]\n\027Serializ" + - "ationSchemeType\022\010\n\004JAVA\020\001\022\013\n\007SBINARY\020\002\022\016", - "\n\nSCALA_JSON\020\003\022\r\n\tJAVA_JSON\020\004\022\014\n\010PROTOBU" + - "F\020\005*-\n\rLifeCycleType\022\r\n\tPERMANENT\020\001\022\r\n\tT" + - "EMPORARY\020\002B\030\n\024akka.remote.protocolH\001" + "\014hotswapStack\030\n \001(\014\0223\n\022replicationStorag" + + "e\030\013 \001(\0162\027.ReplicationStorageType\0225\n\023repl" + + "icationStrategy\030\014 \001(\0162\030.ReplicationStrat" + + "egyType\022(\n\010messages\030\r \003(\0132\026.RemoteMessag" + + "eProtocol\"g\n\037SerializedTypedActorRefProt" + + "ocol\022-\n\010actorRef\030\001 \002(\0132\033.SerializedActor" + + "RefProtocol\022\025\n\rinterfaceName\030\002 \002(\t\";\n\017Me" + + "ssageProtocol\022\017\n\007message\030\001 \002(\014\022\027\n\017messag", + "eManifest\030\002 \001(\014\"R\n\021ActorInfoProtocol\022\033\n\004" + + "uuid\030\001 \002(\0132\r.UuidProtocol\022\017\n\007timeout\030\002 \002" + + "(\004\022\017\n\007address\030\003 \001(\t\")\n\014UuidProtocol\022\014\n\004h" + + "igh\030\001 \002(\004\022\013\n\003low\030\002 \002(\004\"3\n\025MetadataEntryP" + + "rotocol\022\013\n\003key\030\001 \002(\t\022\r\n\005value\030\002 \002(\014\"6\n\021L" + + "ifeCycleProtocol\022!\n\tlifeCycle\030\001 \002(\0162\016.Li" + + "feCycleType\"1\n\017AddressProtocol\022\020\n\010hostna" + + "me\030\001 \002(\t\022\014\n\004port\030\002 \002(\r\"7\n\021ExceptionProto" + + "col\022\021\n\tclassname\030\001 \002(\t\022\017\n\007message\030\002 \002(\t*" + + "(\n\013CommandType\022\013\n\007CONNECT\020\001\022\014\n\010SHUTDOWN\020", + "\002*K\n\026ReplicationStorageType\022\r\n\tTRANSIENT" + + "\020\001\022\023\n\017TRANSACTION_LOG\020\002\022\r\n\tDATA_GRID\020\003*>" + + "\n\027ReplicationStrategyType\022\021\n\rWRITE_THROU" + + "GH\020\001\022\020\n\014WRITE_BEHIND\020\002*]\n\027SerializationS" + + "chemeType\022\010\n\004JAVA\020\001\022\013\n\007SBINARY\020\002\022\016\n\nSCAL" + + "A_JSON\020\003\022\r\n\tJAVA_JSON\020\004\022\014\n\010PROTOBUF\020\005*-\n" + + "\rLifeCycleType\022\r\n\tPERMANENT\020\001\022\r\n\tTEMPORA" + + "RY\020\002B\030\n\024akka.remote.protocolH\001" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { @@ -5796,7 +9046,7 @@ public final class RemoteProtocol { internal_static_SerializedActorRefProtocol_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_SerializedActorRefProtocol_descriptor, - new java.lang.String[] { "Uuid", "Address", "ActorClassname", "ActorInstance", "SerializerClassname", "Timeout", "ReceiveTimeout", "LifeCycle", "Supervisor", "HotswapStack", "Messages", }, + new java.lang.String[] { "Uuid", "Address", "ActorClassname", "ActorInstance", "SerializerClassname", "Timeout", "ReceiveTimeout", "LifeCycle", "Supervisor", "HotswapStack", "ReplicationStorage", "ReplicationStrategy", "Messages", }, akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.class, akka.remote.protocol.RemoteProtocol.SerializedActorRefProtocol.Builder.class); internal_static_SerializedTypedActorRefProtocol_descriptor = @@ -5812,7 +9062,7 @@ public final class RemoteProtocol { internal_static_MessageProtocol_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_MessageProtocol_descriptor, - new java.lang.String[] { "SerializationScheme", "Message", "MessageManifest", }, + new java.lang.String[] { "Message", "MessageManifest", }, akka.remote.protocol.RemoteProtocol.MessageProtocol.class, akka.remote.protocol.RemoteProtocol.MessageProtocol.Builder.class); internal_static_ActorInfoProtocol_descriptor = @@ -5872,7 +9122,5 @@ public final class RemoteProtocol { }, assigner); } - public static void internalForceInit() {} - // @@protoc_insertion_point(outer_class_scope) } diff --git a/akka-remote/src/main/protocol/RemoteProtocol.proto b/akka-remote/src/main/protocol/RemoteProtocol.proto index 795a58814c..be1020fe7e 100644 --- a/akka-remote/src/main/protocol/RemoteProtocol.proto +++ b/akka-remote/src/main/protocol/RemoteProtocol.proto @@ -46,6 +46,23 @@ enum CommandType { SHUTDOWN = 2; } +/** + * Defines the type of the ReplicationStorage + */ +enum ReplicationStorageType { + TRANSIENT = 1; + TRANSACTION_LOG = 2; + DATA_GRID = 3; +} + +/** + * Defines the type of the ReplicationStrategy + */ +enum ReplicationStrategyType { + WRITE_THROUGH = 1; + WRITE_BEHIND = 2; +} + /** * Defines a remote ActorRef that "remembers" and uses its original Actor instance * on the original node. @@ -72,7 +89,9 @@ message SerializedActorRefProtocol { optional LifeCycleProtocol lifeCycle = 8; optional RemoteActorRefProtocol supervisor = 9; optional bytes hotswapStack = 10; - repeated RemoteMessageProtocol messages = 11; + optional ReplicationStorageType replicationStorage = 11; + optional ReplicationStrategyType replicationStrategy = 12; + repeated RemoteMessageProtocol messages = 13; } /** @@ -89,9 +108,8 @@ message SerializedTypedActorRefProtocol { * Defines a message. */ message MessageProtocol { - required SerializationSchemeType serializationScheme = 1; - required bytes message = 2; - optional bytes messageManifest = 3; + required bytes message = 1; + optional bytes messageManifest = 2; } /** diff --git a/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala b/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala index 98bf8400cf..181acb7f03 100644 --- a/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala +++ b/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala @@ -4,98 +4,30 @@ package akka.remote -import akka.serialization.{ Serializers, Serializable } import akka.remote.protocol.RemoteProtocol._ import akka.util._ +import akka.serialization.Serialization 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_SCALA_JSON: Serializers.ScalaJSON = Serializers.ScalaJSON - 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_SCALA_JSON.classLoader = someCl + def deserialize(messageProtocol: MessageProtocol, classLoader: Option[ClassLoader] = None): AnyRef = { + val clazz = loadManifest(classLoader, messageProtocol) + Serialization.deserialize(messageProtocol.getMessage.toByteArray, + clazz, classLoader).fold(x ⇒ throw x, o ⇒ o) } - def deserialize(messageProtocol: MessageProtocol): Any = { - messageProtocol.getSerializationScheme match { - case SerializationSchemeType.JAVA ⇒ - unbox(SERIALIZER_JAVA.fromBinary(messageProtocol.getMessage.toByteArray, None)) - - case SerializationSchemeType.PROTOBUF ⇒ - val clazz = loadManifest(SERIALIZER_PROTOBUF.classLoader, messageProtocol) - SERIALIZER_PROTOBUF.fromBinary(messageProtocol.getMessage.toByteArray, Some(clazz)) - - 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 ⇒ - val clazz = loadManifest(SERIALIZER_JAVA_JSON.classLoader, messageProtocol) - SERIALIZER_JAVA_JSON.fromBinary(messageProtocol.getMessage.toByteArray, Some(clazz)) - } - } - - def serialize(message: Any): MessageProtocol = { + def serialize(message: AnyRef): MessageProtocol = { val builder = MessageProtocol.newBuilder - if (message.isInstanceOf[Message]) { - val serializable = message.asInstanceOf[Message] - builder.setSerializationScheme(SerializationSchemeType.PROTOBUF) - builder.setMessage(ByteString.copyFrom(serializable.toByteArray)) - builder.setMessageManifest(ByteString.copyFromUtf8(serializable.getClass.getName)) - } else if (message.isInstanceOf[Serializable.ScalaJSON[_]]) { - builder.setSerializationScheme(SerializationSchemeType.SCALA_JSON) - setMessageAndManifest(builder, message.asInstanceOf[Serializable.ScalaJSON[_ <: Any]]) - } else if (message.isInstanceOf[Serializable.JavaJSON]) { - builder.setSerializationScheme(SerializationSchemeType.JAVA_JSON) - setMessageAndManifest(builder, message.asInstanceOf[Serializable.JavaJSON]) - } else { - // default, e.g. if no protocol used explicitly then use Java serialization - builder.setSerializationScheme(SerializationSchemeType.JAVA) - builder.setMessage(ByteString.copyFrom(SERIALIZER_JAVA.toBinary(box(message)))) - } + val bytes = Serialization.serialize(message).fold(x ⇒ throw x, b ⇒ b) + builder.setMessage(ByteString.copyFrom(bytes)) + builder.setMessageManifest(ByteString.copyFromUtf8(message.getClass.getName)) builder.build } private def loadManifest(classLoader: Option[ClassLoader], messageProtocol: MessageProtocol): Class[_] = { val manifest = messageProtocol.getMessageManifest.toStringUtf8 - if (classLoader.isDefined) classLoader.get.loadClass(manifest) - else Class.forName(manifest) - } - - private def setMessageAndManifest(builder: MessageProtocol.Builder, serializable: Serializable) = { - builder.setMessage(ByteString.copyFrom(serializable.toBytes)) - builder.setMessageManifest(ByteString.copyFromUtf8(serializable.getClass.getName)) - } - - 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] - } - - 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 + classLoader map (_.loadClass(manifest)) getOrElse (Class.forName(manifest)) } } diff --git a/akka-remote/src/main/scala/akka/remote/RemoteConfig.scala b/akka-remote/src/main/scala/akka/remote/RemoteConfig.scala index 0708cffae7..d6803013f2 100644 --- a/akka-remote/src/main/scala/akka/remote/RemoteConfig.scala +++ b/akka-remote/src/main/scala/akka/remote/RemoteConfig.scala @@ -9,59 +9,58 @@ import akka.config.Config._ import akka.config.ConfigurationException object RemoteClientSettings { - val SECURE_COOKIE: Option[String] = config.getString("akka.remote.secure-cookie", "") match { + val SECURE_COOKIE: Option[String] = config.getString("akka.cluster.secure-cookie", "") match { 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 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) + val RECONNECTION_TIME_WINDOW = Duration(config.getInt("akka.cluster.client.reconnection-time-window", 600), TIME_UNIT).toMillis + val READ_TIMEOUT = Duration(config.getInt("akka.cluster.client.read-timeout", 10), TIME_UNIT) + val RECONNECT_DELAY = Duration(config.getInt("akka.cluster.client.reconnect-delay", 5), TIME_UNIT) + val REAP_FUTURES_DELAY = Duration(config.getInt("akka.cluster.client.reap-futures-delay", 5), TIME_UNIT) + val MESSAGE_FRAME_SIZE = config.getInt("akka.cluster.client.message-frame-size", 1048576) } 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 isRemotingEnabled = config.getList("akka.enabled-modules").exists(_ == "cluster") + val MESSAGE_FRAME_SIZE = config.getInt("akka.cluster.server.message-frame-size", 1048576) + val SECURE_COOKIE = config.getString("akka.cluster.secure-cookie") val REQUIRE_COOKIE = { - val requireCookie = config.getBool("akka.remote.server.require-cookie", false) + val requireCookie = config.getBool("akka.cluster.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'.") + "Configuration option 'akka.cluster.server.require-cookie' is turned on but no secure cookie is defined in 'akka.cluster.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 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 UNTRUSTED_MODE = config.getBool("akka.cluster.server.untrusted-mode", false) + val PORT = config.getInt("akka.cluster.server.port", 2552) + val CONNECTION_TIMEOUT_MILLIS = Duration(config.getInt("akka.cluster.server.connection-timeout", 1), TIME_UNIT) + val COMPRESSION_SCHEME = config.getString("akka.cluster.compression-scheme", "zlib") val ZLIB_COMPRESSION_LEVEL = { - val level = config.getInt("akka.remote.zlib-compression-level", 6) + val level = config.getInt("akka.cluster.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") level } - val BACKLOG = config.getInt("akka.remote.server.backlog", 4096) + val BACKLOG = config.getInt("akka.cluster.server.backlog", 4096) - val EXECUTION_POOL_KEEPALIVE = Duration(config.getInt("akka.remote.server.execution-pool-keepalive", 60), TIME_UNIT) + val EXECUTION_POOL_KEEPALIVE = Duration(config.getInt("akka.cluster.server.execution-pool-keepalive", 60), TIME_UNIT) val EXECUTION_POOL_SIZE = { - 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") + val sz = config.getInt("akka.cluster.server.execution-pool-size", 16) + if (sz < 1) throw new IllegalArgumentException("akka.cluster.server.execution-pool-size is less than 1") sz } val MAX_CHANNEL_MEMORY_SIZE = { - val sz = config.getInt("akka.remote.server.max-channel-memory-size", 0) - if (sz < 0) throw new IllegalArgumentException("akka.remote.server.max-channel-memory-size is less than 0") + val sz = config.getInt("akka.cluster.server.max-channel-memory-size", 0) + if (sz < 0) throw new IllegalArgumentException("akka.cluster.server.max-channel-memory-size is less than 0") sz } val MAX_TOTAL_MEMORY_SIZE = { - val sz = config.getInt("akka.remote.server.max-total-memory-size", 0) - if (sz < 0) throw new IllegalArgumentException("akka.remote.server.max-total-memory-size is less than 0") + val sz = config.getInt("akka.cluster.server.max-total-memory-size", 0) + if (sz < 0) throw new IllegalArgumentException("akka.cluster.server.max-total-memory-size is less than 0") 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 5ffc4b16f3..320bf4281e 100644 --- a/akka-remote/src/main/scala/akka/remote/netty/NettyRemoteSupport.scala +++ b/akka-remote/src/main/scala/akka/remote/netty/NettyRemoteSupport.scala @@ -4,7 +4,7 @@ package akka.remote.netty -import akka.dispatch.{ DefaultPromise, Promise, Future } +import akka.dispatch.{ ActorPromise, DefaultPromise, Promise, Future } import akka.remote.{ MessageSerializer, RemoteClientSettings, RemoteServerSettings } import akka.remote.protocol.RemoteProtocol._ import akka.serialization.RemoteActorSerialization @@ -84,7 +84,7 @@ trait NettyRemoteClientModule extends RemoteClientModule { self: ListenerManagem private[akka] def withClientFor[T]( address: InetSocketAddress, loader: Option[ClassLoader])(fun: RemoteClient ⇒ T): T = { - loader.foreach(MessageSerializer.setClassLoader(_)) + // loader.foreach(MessageSerializer.setClassLoader(_)) val key = Address(address) lock.readLock.lock try { @@ -148,8 +148,8 @@ 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 transactionLogCapacity = config.getInt("akka.remote.client.buffering.capacity", -1) + val useTransactionLog = config.getBool("akka.cluster.client.buffering.retry-message-send-on-failure", true) + val transactionLogCapacity = config.getInt("akka.cluster.client.buffering.capacity", -1) val name = this.getClass.getSimpleName + "@" + remoteAddress.getAddress.getHostAddress + "::" + @@ -804,7 +804,7 @@ class RemoteServerHandler( val server: NettyRemoteServerModule) extends SimpleChannelUpstreamHandler { import RemoteServerSettings._ - applicationLoader.foreach(MessageSerializer.setClassLoader(_)) //TODO: REVISIT: THIS FEELS A BIT DODGY + // applicationLoader.foreach(MessageSerializer.setClassLoader(_)) //TODO: REVISIT: THIS FEELS A BIT DODGY val sessionActors = new ChannelLocal[ConcurrentHashMap[String, ActorRef]]() @@ -879,9 +879,13 @@ class RemoteServerHandler( case _ ⇒ None } - private def handleRemoteMessageProtocol(request: RemoteMessageProtocol, channel: Channel) = { + private def handleRemoteMessageProtocol(request: RemoteMessageProtocol, channel: Channel) = try { EventHandler.debug(this, "Received remote message [%s]".format(request)) dispatchToActor(request, channel) + } catch { + case e: Exception ⇒ + server.notifyListeners(RemoteServerError(e, server)) + EventHandler.error(e, this, e.getMessage) } private def dispatchToActor(request: RemoteMessageProtocol, channel: Channel) { @@ -913,8 +917,7 @@ class RemoteServerHandler( else actorRef.postMessageToMailboxAndCreateFutureResultWithTimeout( message, request.getActorInfo.getTimeout, - None, - Some(new DefaultPromise[Any](request.getActorInfo.getTimeout). + new ActorPromise(request.getActorInfo.getTimeout). onComplete(_.value.get match { case l: Left[Throwable, Any] ⇒ write(channel, createErrorReplyMessage(l.a, request)) case r: Right[Throwable, Any] ⇒ @@ -931,7 +934,7 @@ class RemoteServerHandler( if (request.hasSupervisorUuid) messageBuilder.setSupervisorUuid(request.getSupervisorUuid) write(channel, RemoteEncoder.encode(messageBuilder.build)) - }))) + })) } } diff --git a/akka-remote/src/main/scala/akka/serialization/Serializable.scala b/akka-remote/src/main/scala/akka/serialization/Serializable.scala deleted file mode 100644 index 3f3296d608..0000000000 --- a/akka-remote/src/main/scala/akka/serialization/Serializable.scala +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright (C) 2009-2011 Scalable Solutions AB - */ - -package akka.serialization - -import org.codehaus.jackson.map.ObjectMapper - -import com.google.protobuf.Message - -import reflect.Manifest - -import java.io.{ StringWriter, ByteArrayOutputStream, ObjectOutputStream } - -import sjson.json.{ Serializer ⇒ SJSONSerializer } - -/** - * @author Jonas Bonér - */ -trait Serializable { - def toBytes: Array[Byte] -} - -/** - * Serialization protocols. - * - * @author Jonas Bonér - */ -object Serializable { - - /** - * @author Jonas Bonér - */ - trait JSON extends Serializable { - def toJSON: String - } - - /** - * @author Jonas Bonér - */ - abstract class JavaJSON extends JSON { - - def toJSON: String = { - val out = new StringWriter - val mapper = new ObjectMapper - mapper.writeValue(out, this) - out.close - out.toString - } - - def toBytes: Array[Byte] = { - val bos = new ByteArrayOutputStream - val out = new ObjectOutputStream(bos) - val mapper = new ObjectMapper - mapper.writeValue(out, this) - out.close - bos.toByteArray - } - } - - /** - * case class Address(street: String, city: String, zip: String) - * extends ScalaJSON[Address] { - * - * implicit val AddressFormat: Format[Address] = - * asProduct3("street", "city", "zip")(Address)(Address.unapply(_).get) - * - * import dispatch.json._ - * import sjson.json._ - * import sjson.json.JsonSerialization._ - * - * def toJSON: String = JsValue.toJson(tojson(this)) - * def toBytes: Array[Byte] = tobinary(this) - * def fromBytes(bytes: Array[Byte]): Address = frombinary[Address](bytes) - * def fromJSON(js: String): Address = fromjson[Address](Js(js)) - * } - * - * val a = Address(...) - * val js = tojson(a) - * val add = fromjson[Address](js) - * - * @author Jonas Bonér - */ - trait ScalaJSON[T] extends JSON { - def toJSON: String - def fromJSON(js: String): T - def toBytes: Array[Byte] - def fromBytes(bytes: Array[Byte]): T - } -} diff --git a/akka-remote/src/main/scala/akka/serialization/SerializationProtocol.scala b/akka-remote/src/main/scala/akka/serialization/SerializationProtocol.scala index 8a34a0ec5e..c481ac899e 100644 --- a/akka-remote/src/main/scala/akka/serialization/SerializationProtocol.scala +++ b/akka-remote/src/main/scala/akka/serialization/SerializationProtocol.scala @@ -4,46 +4,56 @@ package akka.serialization -import akka.dispatch.MessageInvocation -import akka.remote.protocol.RemoteProtocol._ -import akka.remote.protocol.RemoteProtocol - import akka.config.Supervision._ import akka.actor.{ uuidFrom, newUuid } import akka.actor._ +import DeploymentConfig._ +import akka.dispatch.MessageInvocation +import akka.util.ReflectiveAccess +import akka.remote.{ RemoteClientSettings, MessageSerializer } +import akka.remote.protocol.RemoteProtocol +import RemoteProtocol._ import scala.collection.immutable.Stack -import com.google.protobuf.ByteString -import akka.util.ReflectiveAccess import java.net.InetSocketAddress -import akka.remote.{ RemoteClientSettings, MessageSerializer } + +import com.google.protobuf.ByteString /** * Module for local actor serialization. */ object ActorSerialization { - implicit val defaultSerializer = Format.Default + implicit val defaultSerializer = akka.serialization.JavaSerializer // Format.Default - def fromBinary[T <: Actor](bytes: Array[Byte], homeAddress: InetSocketAddress)(implicit format: Serializer): ActorRef = - fromBinaryToLocalActorRef(bytes, Some(homeAddress), format) + def fromBinary[T <: Actor](bytes: Array[Byte], homeAddress: InetSocketAddress): ActorRef = + fromBinaryToLocalActorRef(bytes, Some(homeAddress)) - def fromBinary[T <: Actor](bytes: Array[Byte])(implicit format: Serializer): ActorRef = - fromBinaryToLocalActorRef(bytes, None, format) + def fromBinary[T <: Actor](bytes: Array[Byte]): ActorRef = + fromBinaryToLocalActorRef(bytes, None) - def toBinary[T <: Actor](a: ActorRef, serializeMailBox: Boolean = true)(implicit format: Serializer): Array[Byte] = - toSerializedActorRefProtocol(a, format, serializeMailBox).toByteArray + def toBinary[T <: Actor]( + a: ActorRef, + serializeMailBox: Boolean = true, + replicationScheme: ReplicationScheme = Transient): Array[Byte] = + toSerializedActorRefProtocol(a, serializeMailBox, replicationScheme).toByteArray // wrapper for implicits to be used by Java - def fromBinaryJ[T <: Actor](bytes: Array[Byte], format: Serializer): ActorRef = - fromBinary(bytes)(format) + def fromBinaryJ[T <: Actor](bytes: Array[Byte]): ActorRef = + fromBinary(bytes) // wrapper for implicits to be used by Java - def toBinaryJ[T <: Actor](a: ActorRef, format: Serializer, srlMailBox: Boolean = true): Array[Byte] = - toBinary(a, srlMailBox)(format) + def toBinaryJ[T <: Actor]( + a: ActorRef, + srlMailBox: Boolean, + replicationScheme: ReplicationScheme): Array[Byte] = + toBinary(a, srlMailBox, replicationScheme) private[akka] def toSerializedActorRefProtocol[T <: Actor]( - actorRef: ActorRef, format: Serializer, serializeMailBox: Boolean = true): SerializedActorRefProtocol = { + actorRef: ActorRef, + serializeMailBox: Boolean, + replicationScheme: ReplicationScheme): SerializedActorRefProtocol = { + val lifeCycleProtocol: Option[LifeCycleProtocol] = { actorRef.lifeCycle match { case Permanent ⇒ Some(LifeCycleProtocol.newBuilder.setLifeCycle(LifeCycleType.PERMANENT).build) @@ -58,6 +68,24 @@ object ActorSerialization { .setActorClassname(actorRef.actorInstance.get.getClass.getName) .setTimeout(actorRef.timeout) + replicationScheme match { + case _: Transient | Transient ⇒ + builder.setReplicationStorage(ReplicationStorageType.TRANSIENT) + + case Replication(storage, strategy) ⇒ + val storageType = storage match { + case _: TransactionLog | TransactionLog ⇒ ReplicationStorageType.TRANSACTION_LOG + case _: DataGrid | DataGrid ⇒ ReplicationStorageType.DATA_GRID + } + builder.setReplicationStorage(storageType) + + val strategyType = strategy match { + case _: WriteBehind | WriteBehind ⇒ ReplicationStrategyType.WRITE_BEHIND + case _: WriteThrough | WriteThrough ⇒ ReplicationStrategyType.WRITE_THROUGH + } + builder.setReplicationStrategy(strategyType) + } + if (serializeMailBox == true) { if (actorRef.mailbox eq null) throw new IllegalActorStateException("Can't serialize an actor that has not been started.") val messages = @@ -84,23 +112,27 @@ object ActorSerialization { } actorRef.receiveTimeout.foreach(builder.setReceiveTimeout(_)) - builder.setActorInstance(ByteString.copyFrom(format.toBinary(actorRef.actor.asInstanceOf[T]))) + Serialization.serialize(actorRef.actor.asInstanceOf[T]) match { + case Right(bytes) ⇒ builder.setActorInstance(ByteString.copyFrom(bytes)) + case Left(exception) ⇒ throw new Exception("Error serializing : " + actorRef.actor.getClass.getName) + } + lifeCycleProtocol.foreach(builder.setLifeCycle(_)) actorRef.supervisor.foreach(s ⇒ builder.setSupervisor(RemoteActorSerialization.toRemoteActorRefProtocol(s))) - if (!actorRef.hotswap.isEmpty) builder.setHotswapStack(ByteString.copyFrom(Serializers.Java.toBinary(actorRef.hotswap))) + // if (!actorRef.hotswap.isEmpty) builder.setHotswapStack(ByteString.copyFrom(Serializers.Java.toBinary(actorRef.hotswap))) + if (!actorRef.hotswap.isEmpty) builder.setHotswapStack(ByteString.copyFrom(akka.serialization.JavaSerializer.toBinary(actorRef.hotswap))) builder.build } private def fromBinaryToLocalActorRef[T <: Actor]( bytes: Array[Byte], - homeAddress: Option[InetSocketAddress], - format: Serializer): ActorRef = { + homeAddress: Option[InetSocketAddress]): ActorRef = { val builder = SerializedActorRefProtocol.newBuilder.mergeFrom(bytes) - fromProtobufToLocalActorRef(builder.build, format, None) + fromProtobufToLocalActorRef(builder.build, None) } private[akka] def fromProtobufToLocalActorRef[T <: Actor]( - protocol: SerializedActorRefProtocol, format: Serializer, loader: Option[ClassLoader]): ActorRef = { + protocol: SerializedActorRefProtocol, loader: Option[ClassLoader]): ActorRef = { val lifeCycle = if (protocol.hasLifeCycle) { @@ -115,21 +147,51 @@ object ActorSerialization { if (protocol.hasSupervisor) Some(RemoteActorSerialization.fromProtobufToRemoteActorRef(protocol.getSupervisor, loader)) else None + import ReplicationStorageType._ + import ReplicationStrategyType._ + + val replicationScheme = + if (protocol.hasReplicationStorage) { + protocol.getReplicationStorage match { + case TRANSIENT ⇒ Transient + case store ⇒ + val storage = store match { + case TRANSACTION_LOG ⇒ TransactionLog + case DATA_GRID ⇒ DataGrid + } + val strategy = if (protocol.hasReplicationStrategy) { + protocol.getReplicationStrategy match { + case WRITE_THROUGH ⇒ WriteThrough + case WRITE_BEHIND ⇒ WriteBehind + } + } else throw new IllegalActorStateException( + "Expected replication strategy for replication storage [" + storage + "]") + Replication(storage, strategy) + } + } else Transient + val hotswap = try { - format - .fromBinary(protocol.getHotswapStack.toByteArray, Some(classOf[Stack[PartialFunction[Any, Unit]]])) - .asInstanceOf[Stack[PartialFunction[Any, Unit]]] + Serialization.deserialize( + protocol.getHotswapStack.toByteArray, + classOf[Stack[PartialFunction[Any, Unit]]], + loader) match { + case Right(r) ⇒ r.asInstanceOf[Stack[PartialFunction[Any, Unit]]] + case Left(ex) ⇒ throw new Exception("Cannot de-serialize hotswapstack") + } } catch { case e: Exception ⇒ Stack[PartialFunction[Any, Unit]]() } - val classLoader = loader.getOrElse(getClass.getClassLoader) + val classLoader = loader.getOrElse(this.getClass.getClassLoader) val factory = () ⇒ { val actorClass = classLoader.loadClass(protocol.getActorClassname) try { - format.fromBinary(protocol.getActorInstance.toByteArray, Some(actorClass)).asInstanceOf[Actor] + Serialization.deserialize(protocol.getActorInstance.toByteArray, actorClass, loader) match { + case Right(r) ⇒ r.asInstanceOf[Actor] + case Left(ex) ⇒ throw new Exception("Cannot de-serialize : " + actorClass) + } } catch { case e: Exception ⇒ actorClass.newInstance.asInstanceOf[Actor] } @@ -143,14 +205,11 @@ object ActorSerialization { lifeCycle, supervisor, hotswap, - factory) + factory, + replicationScheme) val messages = protocol.getMessagesList.toArray.toList.asInstanceOf[List[RemoteMessageProtocol]] - messages.foreach(message ⇒ ar ! MessageSerializer.deserialize(message.getMessage)) - - //if (format.isInstanceOf[SerializerBasedActorFormat[_]] == false) - // format.fromBinary(protocol.getActorInstance.toByteArray, ar.actor.asInstanceOf[T]) - //ar + messages.foreach(message ⇒ ar ! MessageSerializer.deserialize(message.getMessage, Some(classLoader))) ar } } @@ -174,7 +233,7 @@ object RemoteActorSerialization { */ private[akka] def fromProtobufToRemoteActorRef(protocol: RemoteActorRefProtocol, loader: Option[ClassLoader]): ActorRef = { RemoteActorRef( - Serializers.Java.fromBinary(protocol.getInetSocketAddress.toByteArray, Some(classOf[InetSocketAddress])).asInstanceOf[InetSocketAddress], + JavaSerializer.fromBinary(protocol.getInetSocketAddress.toByteArray, Some(classOf[InetSocketAddress]), loader).asInstanceOf[InetSocketAddress], protocol.getAddress, protocol.getTimeout, loader) @@ -194,7 +253,7 @@ object RemoteActorSerialization { ReflectiveAccess.RemoteModule.configDefaultAddress } RemoteActorRefProtocol.newBuilder - .setInetSocketAddress(ByteString.copyFrom(Serializers.Java.toBinary(remoteAddress))) + .setInetSocketAddress(ByteString.copyFrom(JavaSerializer.toBinary(remoteAddress))) .setAddress(actor.address) .setTimeout(actor.timeout) .build @@ -230,7 +289,7 @@ object RemoteActorSerialization { message match { case Right(message) ⇒ - messageBuilder.setMessage(MessageSerializer.serialize(message)) + messageBuilder.setMessage(MessageSerializer.serialize(message.asInstanceOf[AnyRef])) case Left(exception) ⇒ messageBuilder.setException(ExceptionProtocol.newBuilder .setClassname(exception.getClass.getName) diff --git a/akka-remote/src/main/scala/akka/serialization/Serializer.scala b/akka-remote/src/main/scala/akka/serialization/Serializer.scala index 9c387503d3..7ac3eea2df 100644 --- a/akka-remote/src/main/scala/akka/serialization/Serializer.scala +++ b/akka-remote/src/main/scala/akka/serialization/Serializer.scala @@ -1,149 +1,39 @@ +package akka.serialization + /** * Copyright (C) 2009-2011 Scalable Solutions AB */ -package akka.serialization - import java.io.{ ObjectOutputStream, ByteArrayOutputStream, ObjectInputStream, ByteArrayInputStream } +import akka.util.ClassLoaderObjectInputStream +import akka.actor.ActorRef -import org.apache.commons.io.input.ClassLoaderObjectInputStream - -import com.google.protobuf.Message - -import org.codehaus.jackson.map.ObjectMapper - -import sjson.json.{ Serializer ⇒ SJSONSerializer } - -// For Java API -class SerializerFactory { - import Serializers._ - def getJava: Java.type = Java - def getJavaJSON: JavaJSON.type = JavaJSON - def getScalaJSON: ScalaJSON.type = ScalaJSON - def getProtobuf: Protobuf.type = Protobuf +trait Serializer extends scala.Serializable { + def toBinary(o: AnyRef): Array[Byte] + def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]] = None, classLoader: Option[ClassLoader] = None): AnyRef } -/** - * @author Jonas Bonér - */ -object Serializers { - val ARRAY_OF_BYTE_ARRAY = Array[Class[_]](classOf[Array[Byte]]) - - object NOOP extends NOOP - class NOOP extends Serializer { - def toBinary(obj: AnyRef): Array[Byte] = Array[Byte]() - def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = null.asInstanceOf[AnyRef] +class JavaSerializer extends Serializer { + def toBinary(o: AnyRef): Array[Byte] = { + val bos = new ByteArrayOutputStream + val out = new ObjectOutputStream(bos) + out.writeObject(o) + out.close() + bos.toByteArray } - /** - * @author Jonas Bonér - */ - object Java extends Java - trait Java extends Serializer { - def toBinary(obj: AnyRef): Array[Byte] = { - val bos = new ByteArrayOutputStream - val out = new ObjectOutputStream(bos) - out.writeObject(obj) - out.close - bos.toByteArray - } - - def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = { - val in = - if (classLoader.isDefined) new ClassLoaderObjectInputStream(classLoader.get, new ByteArrayInputStream(bytes)) - else new ObjectInputStream(new ByteArrayInputStream(bytes)) - val obj = in.readObject - in.close - obj - } + def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]] = None, + classLoader: Option[ClassLoader] = None): AnyRef = { + val in = + if (classLoader.isDefined) new ClassLoaderObjectInputStream(classLoader.get, new ByteArrayInputStream(bytes)) else + new ObjectInputStream(new ByteArrayInputStream(bytes)) + val obj = in.readObject + in.close() + obj } - - /** - * @author Jonas Bonér - */ - object Protobuf extends Protobuf - trait Protobuf extends Serializer { - def toBinary(obj: AnyRef): Array[Byte] = { - if (!obj.isInstanceOf[Message]) throw new IllegalArgumentException( - "Can't serialize a non-protobuf message using protobuf [" + obj + "]") - obj.asInstanceOf[Message].toByteArray - } - - def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = { - if (!clazz.isDefined) throw new IllegalArgumentException( - "Need a protobuf message class to be able to serialize bytes using protobuf") - clazz.get.getDeclaredMethod("parseFrom", ARRAY_OF_BYTE_ARRAY: _*).invoke(null, bytes).asInstanceOf[Message] - } - - def fromBinary(bytes: Array[Byte], clazz: Class[_]): AnyRef = { - if (clazz eq null) throw new IllegalArgumentException("Protobuf message can't be null") - fromBinary(bytes, Some(clazz)) - } - } - - /** - * @author Jonas Bonér - */ - object JavaJSON extends JavaJSON - trait JavaJSON extends Serializer { - private val mapper = new ObjectMapper - - def toBinary(obj: AnyRef): Array[Byte] = { - val bos = new ByteArrayOutputStream - val out = new ObjectOutputStream(bos) - mapper.writeValue(out, obj) - out.close - bos.toByteArray - } - - def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = { - if (!clazz.isDefined) throw new IllegalArgumentException( - "Can't deserialize JSON to instance if no class is provided") - val in = - if (classLoader.isDefined) new ClassLoaderObjectInputStream(classLoader.get, new ByteArrayInputStream(bytes)) - else new ObjectInputStream(new ByteArrayInputStream(bytes)) - val obj = mapper.readValue(in, clazz.get).asInstanceOf[AnyRef] - in.close - obj - } - - def fromJSON(json: String, clazz: Class[_]): AnyRef = { - if (clazz eq null) throw new IllegalArgumentException("Can't deserialize JSON to instance if no class is provided") - mapper.readValue(json, clazz).asInstanceOf[AnyRef] - } - } - - /** - * @author Jonas Bonér - */ - trait ScalaJSON { - import sjson.json._ - - var classLoader: Option[ClassLoader] = None - - def tojson[T](o: T)(implicit tjs: Writes[T]): JsValue = JsonSerialization.tojson(o)(tjs) - - def fromjson[T](json: JsValue)(implicit fjs: Reads[T]): T = JsonSerialization.fromjson(json)(fjs) - - def tobinary[T](o: T)(implicit tjs: Writes[T]): Array[Byte] = JsonSerialization.tobinary(o)(tjs) - - def frombinary[T](bytes: Array[Byte])(implicit fjs: Reads[T]): T = JsonSerialization.frombinary(bytes)(fjs) - - // backward compatibility - // implemented using refelction based json serialization - def toBinary(obj: AnyRef): Array[Byte] = SJSONSerializer.SJSON.out(obj) - - def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = SJSONSerializer.SJSON.in(bytes) - - import scala.reflect.Manifest - def fromJSON[T](json: String)(implicit m: Manifest[T]): AnyRef = { - SJSONSerializer.SJSON.in(json)(m) - } - - def fromBinary[T](bytes: Array[Byte])(implicit m: Manifest[T]): AnyRef = { - SJSONSerializer.SJSON.in(bytes)(m) - } - } - object ScalaJSON extends ScalaJSON } +object JavaSerializer extends JavaSerializer +object Serializer { + val defaultSerializerName = JavaSerializer.getClass.getName +} diff --git a/akka-remote/src/test/java/akka/actor/ProtobufProtocol.java b/akka-remote/src/test/java/akka/actor/ProtobufProtocol.java new file mode 100644 index 0000000000..38d929f4e5 --- /dev/null +++ b/akka-remote/src/test/java/akka/actor/ProtobufProtocol.java @@ -0,0 +1,565 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: ProtobufProtocol.proto + +package akka.actor; + +public final class ProtobufProtocol { + private ProtobufProtocol() {} + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistry registry) { + } + public interface MyMessageOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // required uint64 id = 1; + boolean hasId(); + long getId(); + + // required string name = 2; + boolean hasName(); + String getName(); + + // required bool status = 3; + boolean hasStatus(); + boolean getStatus(); + } + public static final class MyMessage extends + com.google.protobuf.GeneratedMessage + implements MyMessageOrBuilder { + // Use MyMessage.newBuilder() to construct. + private MyMessage(Builder builder) { + super(builder); + } + private MyMessage(boolean noInit) {} + + private static final MyMessage defaultInstance; + public static MyMessage getDefaultInstance() { + return defaultInstance; + } + + public MyMessage getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.actor.ProtobufProtocol.internal_static_akka_actor_MyMessage_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.actor.ProtobufProtocol.internal_static_akka_actor_MyMessage_fieldAccessorTable; + } + + private int bitField0_; + // required uint64 id = 1; + public static final int ID_FIELD_NUMBER = 1; + private long id_; + public boolean hasId() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public long getId() { + return id_; + } + + // required string name = 2; + public static final int NAME_FIELD_NUMBER = 2; + private java.lang.Object name_; + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public String getName() { + java.lang.Object ref = name_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + name_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + // required bool status = 3; + public static final int STATUS_FIELD_NUMBER = 3; + private boolean status_; + public boolean hasStatus() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public boolean getStatus() { + return status_; + } + + private void initFields() { + id_ = 0L; + name_ = ""; + status_ = false; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasId()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasName()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasStatus()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeUInt64(1, id_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, getNameBytes()); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeBool(3, status_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt64Size(1, id_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(2, getNameBytes()); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeBoolSize(3, status_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static akka.actor.ProtobufProtocol.MyMessage parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static akka.actor.ProtobufProtocol.MyMessage parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static akka.actor.ProtobufProtocol.MyMessage parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static akka.actor.ProtobufProtocol.MyMessage parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static akka.actor.ProtobufProtocol.MyMessage parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static akka.actor.ProtobufProtocol.MyMessage parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static akka.actor.ProtobufProtocol.MyMessage parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static akka.actor.ProtobufProtocol.MyMessage parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static akka.actor.ProtobufProtocol.MyMessage parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static akka.actor.ProtobufProtocol.MyMessage parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(akka.actor.ProtobufProtocol.MyMessage prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements akka.actor.ProtobufProtocol.MyMessageOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return akka.actor.ProtobufProtocol.internal_static_akka_actor_MyMessage_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return akka.actor.ProtobufProtocol.internal_static_akka_actor_MyMessage_fieldAccessorTable; + } + + // Construct using akka.actor.ProtobufProtocol.MyMessage.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + id_ = 0L; + bitField0_ = (bitField0_ & ~0x00000001); + name_ = ""; + bitField0_ = (bitField0_ & ~0x00000002); + status_ = false; + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return akka.actor.ProtobufProtocol.MyMessage.getDescriptor(); + } + + public akka.actor.ProtobufProtocol.MyMessage getDefaultInstanceForType() { + return akka.actor.ProtobufProtocol.MyMessage.getDefaultInstance(); + } + + public akka.actor.ProtobufProtocol.MyMessage build() { + akka.actor.ProtobufProtocol.MyMessage result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private akka.actor.ProtobufProtocol.MyMessage buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + akka.actor.ProtobufProtocol.MyMessage result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public akka.actor.ProtobufProtocol.MyMessage buildPartial() { + akka.actor.ProtobufProtocol.MyMessage result = new akka.actor.ProtobufProtocol.MyMessage(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.id_ = id_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.name_ = name_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.status_ = status_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof akka.actor.ProtobufProtocol.MyMessage) { + return mergeFrom((akka.actor.ProtobufProtocol.MyMessage)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(akka.actor.ProtobufProtocol.MyMessage other) { + if (other == akka.actor.ProtobufProtocol.MyMessage.getDefaultInstance()) return this; + if (other.hasId()) { + setId(other.getId()); + } + if (other.hasName()) { + setName(other.getName()); + } + if (other.hasStatus()) { + setStatus(other.getStatus()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + if (!hasId()) { + + return false; + } + if (!hasName()) { + + return false; + } + if (!hasStatus()) { + + return false; + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + id_ = input.readUInt64(); + break; + } + case 18: { + bitField0_ |= 0x00000002; + name_ = input.readBytes(); + break; + } + case 24: { + bitField0_ |= 0x00000004; + status_ = input.readBool(); + break; + } + } + } + } + + private int bitField0_; + + // required uint64 id = 1; + private long id_ ; + public boolean hasId() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public long getId() { + return id_; + } + public Builder setId(long value) { + bitField0_ |= 0x00000001; + id_ = value; + onChanged(); + return this; + } + public Builder clearId() { + bitField0_ = (bitField0_ & ~0x00000001); + id_ = 0L; + onChanged(); + return this; + } + + // required string name = 2; + private java.lang.Object name_ = ""; + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public String getName() { + java.lang.Object ref = name_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + name_ = s; + return s; + } else { + return (String) ref; + } + } + public Builder setName(String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + name_ = value; + onChanged(); + return this; + } + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000002); + name_ = getDefaultInstance().getName(); + onChanged(); + return this; + } + void setName(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000002; + name_ = value; + onChanged(); + } + + // required bool status = 3; + private boolean status_ ; + public boolean hasStatus() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public boolean getStatus() { + return status_; + } + public Builder setStatus(boolean value) { + bitField0_ |= 0x00000004; + status_ = value; + onChanged(); + return this; + } + public Builder clearStatus() { + bitField0_ = (bitField0_ & ~0x00000004); + status_ = false; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:akka.actor.MyMessage) + } + + static { + defaultInstance = new MyMessage(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:akka.actor.MyMessage) + } + + private static com.google.protobuf.Descriptors.Descriptor + internal_static_akka_actor_MyMessage_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_akka_actor_MyMessage_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor + getDescriptor() { + return descriptor; + } + private static com.google.protobuf.Descriptors.FileDescriptor + descriptor; + static { + java.lang.String[] descriptorData = { + "\n\026ProtobufProtocol.proto\022\nakka.actor\"5\n\t" + + "MyMessage\022\n\n\002id\030\001 \002(\004\022\014\n\004name\030\002 \002(\t\022\016\n\006s" + + "tatus\030\003 \002(\010" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + internal_static_akka_actor_MyMessage_descriptor = + getDescriptor().getMessageTypes().get(0); + internal_static_akka_actor_MyMessage_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_akka_actor_MyMessage_descriptor, + new java.lang.String[] { "Id", "Name", "Status", }, + akka.actor.ProtobufProtocol.MyMessage.class, + akka.actor.ProtobufProtocol.MyMessage.Builder.class); + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor + .internalBuildGeneratedFileFrom(descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + }, assigner); + } + + // @@protoc_insertion_point(outer_class_scope) +} diff --git a/akka-remote/src/test/protocol/ProtobufProtocol.proto b/akka-remote/src/test/protocol/ProtobufProtocol.proto new file mode 100644 index 0000000000..5e41f75978 --- /dev/null +++ b/akka-remote/src/test/protocol/ProtobufProtocol.proto @@ -0,0 +1,18 @@ +/** + * Copyright (C) 2009-2011 Scalable Solutions AB + */ + +package akka.actor; + +/* + Compile with: + cd ./akka-remote/src/test/protocol + protoc ProtobufProtocol.proto --java_out ../java +*/ + +message MyMessage { + required uint64 id = 1; + required string name = 2; + required bool status = 3; +} + diff --git a/akka-remote/src/test/scala/akka/serialization/ActorSerializeSpec.scala b/akka-remote/src/test/scala/akka/serialization/ActorSerializeSpec.scala new file mode 100644 index 0000000000..0104555109 --- /dev/null +++ b/akka-remote/src/test/scala/akka/serialization/ActorSerializeSpec.scala @@ -0,0 +1,169 @@ +package akka.serialization + +import org.scalatest.Spec +import org.scalatest.matchers.ShouldMatchers +import org.scalatest.BeforeAndAfterAll +import org.scalatest.junit.JUnitRunner +import org.junit.runner.RunWith + +import com.google.protobuf.Message + +import akka.serialization.ActorSerialization._ +import akka.actor._ +import Actor._ +import SerializeSpec._ + +case class MyMessage(id: Long, name: String, status: Boolean) +@RunWith(classOf[JUnitRunner]) +class ActorSerializeSpec extends Spec with ShouldMatchers with BeforeAndAfterAll { + + describe("Serializable actor") { + it("should be able to serialize and de-serialize a stateful actor with a given serializer") { + + val actor1 = actorOf[MyJavaSerializableActor].start() + (actor1 !! "hello").getOrElse("_") should equal("world 1") + (actor1 !! "hello").getOrElse("_") should equal("world 2") + + val bytes = toBinary(actor1) + val actor2 = fromBinary(bytes) + actor2.start() + (actor2 !! "hello").getOrElse("_") should equal("world 3") + + actor2.receiveTimeout should equal(Some(1000)) + actor1.stop() + actor2.stop() + } + + it("should be able to serialize and deserialize a MyStatelessActorWithMessagesInMailbox") { + + val actor1 = actorOf[MyStatelessActorWithMessagesInMailbox].start() + (actor1 ! "hello") + (actor1 ! "hello") + (actor1 ! "hello") + (actor1 ! "hello") + (actor1 ! "hello") + (actor1 ! "hello") + (actor1 ! "hello") + (actor1 ! "hello") + (actor1 ! "hello") + (actor1 ! "hello") + actor1.getDispatcher.mailboxSize(actor1) should be > (0) + val actor2 = fromBinary(toBinary(actor1)) + Thread.sleep(1000) + actor2.getDispatcher.mailboxSize(actor1) should be > (0) + (actor2 !! "hello-reply").getOrElse("_") should equal("world") + + val actor3 = fromBinary(toBinary(actor1, false)) + Thread.sleep(1000) + actor3.getDispatcher.mailboxSize(actor1) should equal(0) + (actor3 !! "hello-reply").getOrElse("_") should equal("world") + } + + it("should be able to serialize and deserialize a PersonActorWithMessagesInMailbox") { + + val p1 = Person("debasish ghosh", 25, SerializeSpec.Address("120", "Monroe Street", "Santa Clara", "95050")) + val actor1 = actorOf[PersonActorWithMessagesInMailbox].start() + (actor1 ! p1) + (actor1 ! p1) + (actor1 ! p1) + (actor1 ! p1) + (actor1 ! p1) + (actor1 ! p1) + (actor1 ! p1) + (actor1 ! p1) + (actor1 ! p1) + (actor1 ! p1) + actor1.getDispatcher.mailboxSize(actor1) should be > (0) + val actor2 = fromBinary(toBinary(actor1)) + Thread.sleep(1000) + actor2.getDispatcher.mailboxSize(actor1) should be > (0) + (actor2 !! "hello-reply").getOrElse("_") should equal("hello") + + val actor3 = fromBinary(toBinary(actor1, false)) + Thread.sleep(1000) + actor3.getDispatcher.mailboxSize(actor1) should equal(0) + (actor3 !! "hello-reply").getOrElse("_") should equal("hello") + } + } + + describe("serialize protobuf") { + it("should serialize") { + val msg = MyMessage(123, "debasish ghosh", true) + import akka.serialization.Serialization._ + val b = serialize(ProtobufProtocol.MyMessage.newBuilder.setId(msg.id).setName(msg.name).setStatus(msg.status).build) match { + case Left(exception) ⇒ fail(exception) + case Right(bytes) ⇒ bytes + } + val in = deserialize(b, classOf[ProtobufProtocol.MyMessage], None) match { + case Left(exception) ⇒ fail(exception) + case Right(i) ⇒ i + } + val m = in.asInstanceOf[ProtobufProtocol.MyMessage] + MyMessage(m.getId, m.getName, m.getStatus) should equal(msg) + } + } + + describe("serialize actor that accepts protobuf message") { + it("should serialize") { + + val actor1 = actorOf[MyActorWithProtobufMessagesInMailbox].start() + val msg = MyMessage(123, "debasish ghosh", true) + val b = ProtobufProtocol.MyMessage.newBuilder.setId(msg.id).setName(msg.name).setStatus(msg.status).build + (actor1 ! b) + (actor1 ! b) + (actor1 ! b) + (actor1 ! b) + (actor1 ! b) + (actor1 ! b) + (actor1 ! b) + (actor1 ! b) + (actor1 ! b) + (actor1 ! b) + actor1.getDispatcher.mailboxSize(actor1) should be > (0) + val actor2 = fromBinary(toBinary(actor1)) + Thread.sleep(1000) + actor2.getDispatcher.mailboxSize(actor1) should be > (0) + (actor2 !! "hello-reply").getOrElse("_") should equal("world") + + val actor3 = fromBinary(toBinary(actor1, false)) + Thread.sleep(1000) + actor3.getDispatcher.mailboxSize(actor1) should equal(0) + (actor3 !! "hello-reply").getOrElse("_") should equal("world") + } + } +} + +class MyJavaSerializableActor extends Actor with scala.Serializable { + var count = 0 + self.receiveTimeout = Some(1000) + + def receive = { + case "hello" ⇒ + count = count + 1 + self.reply("world " + count) + } +} + +class MyStatelessActorWithMessagesInMailbox extends Actor with scala.Serializable { + def receive = { + case "hello" ⇒ + Thread.sleep(500) + case "hello-reply" ⇒ self.reply("world") + } +} + +class MyActorWithProtobufMessagesInMailbox extends Actor with scala.Serializable { + def receive = { + case m: Message ⇒ + Thread.sleep(500) + case "hello-reply" ⇒ self.reply("world") + } +} + +class PersonActorWithMessagesInMailbox extends Actor with scala.Serializable { + def receive = { + case p: Person ⇒ + Thread.sleep(500) + case "hello-reply" ⇒ self.reply("hello") + } +} diff --git a/akka-samples/akka-sample-hello/config/akka.conf b/akka-samples/akka-sample-hello/config/akka.conf new file mode 100644 index 0000000000..1278bd0e70 --- /dev/null +++ b/akka-samples/akka-sample-hello/config/akka.conf @@ -0,0 +1,27 @@ +#################### +# Akka Config File # +#################### + +akka { + version = "2.0-SNAPSHOT" + + enabled-modules = ["http"] + + time-unit = "seconds" + + event-handlers = ["akka.event.EventHandler$DefaultListener"] + + boot = ["sample.hello.Boot"] + + http { + hostname = "localhost" + port = 9998 + + connection-close = true + root-actor-id = "_httproot" + root-actor-builtin = true + timeout = 1000 + expired-header-name = "Async-Timeout" + expired-header-value = "expired" + } +} diff --git a/akka-samples/akka-sample-hello/config/microkernel-server.xml b/akka-samples/akka-sample-hello/config/microkernel-server.xml new file mode 100644 index 0000000000..7180bca3f4 --- /dev/null +++ b/akka-samples/akka-sample-hello/config/microkernel-server.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + 300000 + 2 + false + 8443 + 20000 + 5000 + + + + + + + + + + + + + + / + + akka.http.AkkaMistServlet + /* + + + + + + + + + + + + + + + true + true + true + 1000 + + diff --git a/akka-samples/akka-sample-hello/src/main/scala/sample/hello/Boot.scala b/akka-samples/akka-sample-hello/src/main/scala/sample/hello/Boot.scala new file mode 100644 index 0000000000..91f413e1fc --- /dev/null +++ b/akka-samples/akka-sample-hello/src/main/scala/sample/hello/Boot.scala @@ -0,0 +1,20 @@ +/** + * Copyright (C) 2009-2011 Scalable Solutions AB + */ + +package sample.hello + +import akka.actor._ +import akka.http._ +import akka.config.Supervision._ + +class Boot { + val factory = + SupervisorFactory( + SupervisorConfig( + OneForOneStrategy(List(classOf[Exception]), 3, 100), + Supervise(Actor.actorOf[RootEndpoint], Permanent) :: + Supervise(Actor.actorOf[HelloEndpoint], Permanent) :: Nil)) + + factory.newInstance.start +} diff --git a/akka-samples/akka-sample-hello/src/main/scala/sample/hello/HelloEndpoint.scala b/akka-samples/akka-sample-hello/src/main/scala/sample/hello/HelloEndpoint.scala new file mode 100644 index 0000000000..fec6f55470 --- /dev/null +++ b/akka-samples/akka-sample-hello/src/main/scala/sample/hello/HelloEndpoint.scala @@ -0,0 +1,29 @@ +/** + * Copyright (C) 2009-2011 Scalable Solutions AB + */ + +package sample.hello + +import akka.actor._ +import akka.http._ + +import java.text.DateFormat +import java.util.Date + +class HelloEndpoint extends Actor with Endpoint { + self.dispatcher = Endpoint.Dispatcher + + lazy val hello = Actor.actorOf( + new Actor { + def time = DateFormat.getTimeInstance.format(new Date) + def receive = { + case get: Get => get OK "Hello at " + time + } + }).start + + def hook: Endpoint.Hook = { case _ => hello } + + override def preStart = Actor.registry.actorFor(MistSettings.RootActorID).get ! Endpoint.Attach(hook) + + def receive = handleHttpRequest +} diff --git a/akka-samples/akka-sample-osgi/src/main/scala/OsgiExample.scala b/akka-samples/akka-sample-osgi/src/main/scala/OsgiExample.scala index 092fcf9d36..5ee3f016a9 100644 --- a/akka-samples/akka-sample-osgi/src/main/scala/OsgiExample.scala +++ b/akka-samples/akka-sample-osgi/src/main/scala/OsgiExample.scala @@ -3,8 +3,8 @@ */ package sample.osgi -import akka.actor.{ Actor, ActorRegistry } -import Actor._ +import akka.actor.Actor +import akka.actor.Actor._ import org.osgi.framework.{ BundleActivator, BundleContext } @@ -13,7 +13,7 @@ class Activator extends BundleActivator { def start(context: BundleContext) { println("Starting the OSGi example ...") val echo = actorOf[EchoActor].start() - val answer = (echo !! "OSGi example") + val answer = (echo ? "OSGi example").as[String] println(answer getOrElse "No answer!") } 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 7a1f9d2c5d..4ab3d1976e 100644 --- a/akka-slf4j/src/main/scala/akka/event/slf4j/SLF4J.scala +++ b/akka-slf4j/src/main/scala/akka/event/slf4j/SLF4J.scala @@ -39,7 +39,7 @@ class Slf4jEventHandler extends Actor with Logging { def receive = { case Error(cause, instance, message) ⇒ log.error("\n\t[{}]\n\t[{}]\n\t[{}]", - Array[Any](instance.getClass.getName, message, stackTraceFor(cause))) + Array[AnyRef](instance.getClass.getName, message.asInstanceOf[AnyRef], stackTraceFor(cause))) case Warning(instance, message) ⇒ log.warn("\n\t[{}]\n\t[{}]", instance.getClass.getName, message) diff --git a/akka-spring/src/test/resources/akka-test.conf b/akka-spring/src/test/resources/akka-test.conf index bb9c0e347d..a32dc0f338 100644 --- a/akka-spring/src/test/resources/akka-test.conf +++ b/akka-spring/src/test/resources/akka-test.conf @@ -25,8 +25,8 @@ akka { actor { timeout = 2000 # Default timeout for Future based invocations - # - Actor: !! && !!! - # - UntypedActor: sendRequestReply && sendRequestReplyFuture + # - Actor: !! && ? + # - UntypedActor: sendRequestReply && ask # - TypedActor: methods with non-void return type serialize-messages = off # Does a deep clone of (non-primitive) messages to ensure immutability throughput = 5 # Default throughput for all ExecutorBasedEventDrivenDispatcher, set to 1 for complete fairness diff --git a/akka-spring/src/test/resources/property-config.xml b/akka-spring/src/test/resources/property-config.xml index f199df7074..43d36852ed 100644 --- a/akka-spring/src/test/resources/property-config.xml +++ b/akka-spring/src/test/resources/property-config.xml @@ -15,7 +15,7 @@ http://akka.io/akka-2.0-SNAPSHOT.xsd"> - + diff --git a/akka-stm/src/main/scala/akka/agent/Agent.scala b/akka-stm/src/main/scala/akka/agent/Agent.scala index dfa3cfd6b8..be30615b85 100644 --- a/akka-stm/src/main/scala/akka/agent/Agent.scala +++ b/akka-stm/src/main/scala/akka/agent/Agent.scala @@ -120,7 +120,7 @@ class Agent[T](initialValue: T) { * within the given timeout */ def alter(f: T ⇒ T)(timeout: Long): Future[T] = { - def dispatch = updater.!!!(Update(f), timeout) + def dispatch = updater.?(Update(f), timeout).asInstanceOf[Future[T]] if (Stm.activeTransaction) { val result = new DefaultPromise[T](timeout) get //Join xa @@ -168,7 +168,7 @@ class Agent[T](initialValue: T) { send((value: T) ⇒ { suspend val threadBased = Actor.actorOf(new ThreadBasedAgentUpdater(this)).start() - result completeWith threadBased.!!!(Update(f), timeout) + result completeWith threadBased.?(Update(f), timeout).asInstanceOf[Future[T]] value }) result @@ -178,7 +178,7 @@ class Agent[T](initialValue: T) { * A future to the current value that will be completed after any currently * queued updates. */ - def future(): Future[T] = (updater !!! Get).asInstanceOf[Future[T]] + def future(): Future[T] = (updater ? Get).asInstanceOf[Future[T]] /** * Gets this agent's value after all currently queued updates have completed. diff --git a/akka-stm/src/test/java/akka/transactor/example/UntypedCoordinatedExample.java b/akka-stm/src/test/java/akka/transactor/example/UntypedCoordinatedExample.java index 127a911677..f3ac18fb73 100644 --- a/akka-stm/src/test/java/akka/transactor/example/UntypedCoordinatedExample.java +++ b/akka-stm/src/test/java/akka/transactor/example/UntypedCoordinatedExample.java @@ -19,8 +19,8 @@ public class UntypedCoordinatedExample { Thread.sleep(3000); - Future future1 = counter1.sendRequestReplyFuture("GetCount"); - Future future2 = counter2.sendRequestReplyFuture("GetCount"); + Future future1 = counter1.ask("GetCount"); + Future future2 = counter2.ask("GetCount"); future1.await(); if (future1.isCompleted()) { diff --git a/akka-stm/src/test/java/akka/transactor/example/UntypedTransactorExample.java b/akka-stm/src/test/java/akka/transactor/example/UntypedTransactorExample.java index d2f83ff25e..34e2e2edec 100644 --- a/akka-stm/src/test/java/akka/transactor/example/UntypedTransactorExample.java +++ b/akka-stm/src/test/java/akka/transactor/example/UntypedTransactorExample.java @@ -18,8 +18,8 @@ public class UntypedTransactorExample { Thread.sleep(3000); - Future future1 = counter1.sendRequestReplyFuture("GetCount"); - Future future2 = counter2.sendRequestReplyFuture("GetCount"); + Future future1 = counter1.ask("GetCount"); + Future future2 = counter2.ask("GetCount"); future1.await(); if (future1.isCompleted()) { diff --git a/akka-stm/src/test/java/akka/transactor/test/UntypedCoordinatedIncrementTest.java b/akka-stm/src/test/java/akka/transactor/test/UntypedCoordinatedIncrementTest.java index a9eabe7be1..84773d7d5d 100644 --- a/akka-stm/src/test/java/akka/transactor/test/UntypedCoordinatedIncrementTest.java +++ b/akka-stm/src/test/java/akka/transactor/test/UntypedCoordinatedIncrementTest.java @@ -49,7 +49,7 @@ public class UntypedCoordinatedIncrementTest { incrementLatch.await(timeout, TimeUnit.SECONDS); } catch (InterruptedException exception) {} for (ActorRef counter : counters) { - Future future = counter.sendRequestReplyFuture("GetCount"); + Future future = counter.ask("GetCount"); future.await(); if (future.isCompleted()) { Option resultOption = future.result(); @@ -72,7 +72,7 @@ public class UntypedCoordinatedIncrementTest { incrementLatch.await(timeout, TimeUnit.SECONDS); } catch (InterruptedException exception) {} for (ActorRef counter : counters) { - Future future = counter.sendRequestReplyFuture("GetCount"); + Future future = counter.ask("GetCount"); future.await(); if (future.isCompleted()) { Option resultOption = future.result(); diff --git a/akka-stm/src/test/java/akka/transactor/test/UntypedTransactorTest.java b/akka-stm/src/test/java/akka/transactor/test/UntypedTransactorTest.java index 9610aa2ebe..97446d2cda 100644 --- a/akka-stm/src/test/java/akka/transactor/test/UntypedTransactorTest.java +++ b/akka-stm/src/test/java/akka/transactor/test/UntypedTransactorTest.java @@ -48,7 +48,7 @@ public class UntypedTransactorTest { incrementLatch.await(timeout, TimeUnit.SECONDS); } catch (InterruptedException exception) {} for (ActorRef counter : counters) { - Future future = counter.sendRequestReplyFuture("GetCount"); + Future future = counter.ask("GetCount"); future.await(); if (future.isCompleted()) { Option resultOption = future.result(); @@ -71,7 +71,7 @@ public class UntypedTransactorTest { incrementLatch.await(timeout, TimeUnit.SECONDS); } catch (InterruptedException exception) {} for (ActorRef counter : counters) { - Future future = counter.sendRequestReplyFuture("GetCount"); + Future future = counter.ask("GetCount"); future.await(); if (future.isCompleted()) { Option resultOption = future.result(); diff --git a/akka-stm/src/test/scala/transactor/CoordinatedIncrementSpec.scala b/akka-stm/src/test/scala/transactor/CoordinatedIncrementSpec.scala index 5615c97322..8e589c6ff8 100644 --- a/akka-stm/src/test/scala/transactor/CoordinatedIncrementSpec.scala +++ b/akka-stm/src/test/scala/transactor/CoordinatedIncrementSpec.scala @@ -64,7 +64,7 @@ class CoordinatedIncrementSpec extends WordSpec with MustMatchers { counters(0) ! coordinated(Increment(counters.tail)) coordinated.await for (counter ← counters) { - (counter !! GetCount).get must be === 1 + (counter ? GetCount).as[Int].get must be === 1 } counters foreach (_.stop()) failer.stop() @@ -76,7 +76,7 @@ class CoordinatedIncrementSpec extends WordSpec with MustMatchers { counters(0) ! Coordinated(Increment(counters.tail :+ failer)) coordinated.await for (counter ← counters) { - (counter !! GetCount).get must be === 0 + (counter ? GetCount).as[Int].get must be === 0 } counters foreach (_.stop()) failer.stop() diff --git a/akka-stm/src/test/scala/transactor/FickleFriendsSpec.scala b/akka-stm/src/test/scala/transactor/FickleFriendsSpec.scala index b275c1a071..f7b0277656 100644 --- a/akka-stm/src/test/scala/transactor/FickleFriendsSpec.scala +++ b/akka-stm/src/test/scala/transactor/FickleFriendsSpec.scala @@ -109,9 +109,9 @@ class FickleFriendsSpec extends WordSpec with MustMatchers { val latch = new CountDownLatch(1) coordinator ! FriendlyIncrement(counters, latch) latch.await // this could take a while - (coordinator !! GetCount).get must be === 1 + (coordinator ? GetCount).as[Int].get must be === 1 for (counter ← counters) { - (counter !! GetCount).get must be === 1 + (counter ? GetCount).as[Int].get must be === 1 } counters foreach (_.stop()) coordinator.stop() diff --git a/akka-stm/src/test/scala/transactor/TransactorSpec.scala b/akka-stm/src/test/scala/transactor/TransactorSpec.scala index 33ca14402f..8cccdf430c 100644 --- a/akka-stm/src/test/scala/transactor/TransactorSpec.scala +++ b/akka-stm/src/test/scala/transactor/TransactorSpec.scala @@ -92,7 +92,7 @@ class TransactorSpec extends WordSpec with MustMatchers { counters(0) ! Increment(counters.tail, incrementLatch) incrementLatch.await(timeout.length, timeout.unit) for (counter ← counters) { - (counter !! GetCount).get must be === 1 + (counter ? GetCount).as[Int].get must be === 1 } counters foreach (_.stop()) failer.stop() @@ -104,7 +104,7 @@ class TransactorSpec extends WordSpec with MustMatchers { counters(0) ! Increment(counters.tail :+ failer, failLatch) failLatch.await(timeout.length, timeout.unit) for (counter ← counters) { - (counter !! GetCount).get must be === 0 + (counter ? GetCount).as[Int].get must be === 0 } counters foreach (_.stop()) failer.stop() diff --git a/akka-testkit/src/main/scala/akka/testkit/CallingThreadDispatcher.scala b/akka-testkit/src/main/scala/akka/testkit/CallingThreadDispatcher.scala index 90d9bfda83..19058b4951 100644 --- a/akka-testkit/src/main/scala/akka/testkit/CallingThreadDispatcher.scala +++ b/akka-testkit/src/main/scala/akka/testkit/CallingThreadDispatcher.scala @@ -5,7 +5,7 @@ package akka.testkit import akka.event.EventHandler import akka.actor.ActorRef -import akka.dispatch.{ MessageDispatcher, MessageInvocation, FutureInvocation } +import akka.dispatch.{ MessageDispatcher, MessageInvocation, FutureInvocation, Promise, ActorPromise } import java.util.concurrent.locks.ReentrantLock import java.util.LinkedList import java.util.concurrent.RejectedExecutionException @@ -135,19 +135,21 @@ class CallingThreadDispatcher(val warnings: Boolean = true) extends MessageDispa override def mailboxSize(actor: ActorRef) = getMailbox(actor).queue.size + def mailboxIsEmpty(actorRef: ActorRef): Boolean = getMailbox(actorRef).queue.isEmpty + private[akka] override def dispatch(handle: MessageInvocation) { val mbox = getMailbox(handle.receiver) val queue = mbox.queue val execute = mbox.suspended.ifElseYield { queue.push(handle) - if (warnings && handle.senderFuture.isDefined) { + if (warnings && handle.channel.isInstanceOf[Promise[_]]) { 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) { + if (warnings && handle.channel.isInstanceOf[Promise[_]]) { EventHandler.warning(this, "blocked on this thread, creating Future could deadlock; target: %s" format handle.receiver) } false @@ -186,14 +188,18 @@ class CallingThreadDispatcher(val warnings: Boolean = true) extends MessageDispa if (handle ne null) { try { handle.invoke - val f = handle.senderFuture - if (warnings && f.isDefined && !f.get.isCompleted) { - EventHandler.warning(this, "calling %s with message %s did not reply as expected, might deadlock" format (handle.receiver, handle.message)) + if (warnings) handle.channel match { + case f: ActorPromise if !f.isCompleted ⇒ + EventHandler.warning(this, "calling %s with message %s did not reply as expected, might deadlock" format (handle.receiver, handle.message)) + case _ ⇒ } + true } catch { - case _ ⇒ queue.leave + case e ⇒ + EventHandler.error(this, e) + queue.leave + false } - true } else if (queue.isActive) { queue.leave false @@ -210,6 +216,7 @@ class CallingThreadDispatcher(val warnings: Boolean = true) extends MessageDispa class NestingQueue { private var q = new LinkedList[MessageInvocation]() def size = q.size + def isEmpty = q.isEmpty def push(handle: MessageInvocation) { q.offer(handle) } def peek = q.peek def pop = q.poll diff --git a/akka-testkit/src/main/scala/akka/testkit/TestActorRef.scala b/akka-testkit/src/main/scala/akka/testkit/TestActorRef.scala index 7b656278b8..a940d5ce01 100644 --- a/akka-testkit/src/main/scala/akka/testkit/TestActorRef.scala +++ b/akka-testkit/src/main/scala/akka/testkit/TestActorRef.scala @@ -15,20 +15,15 @@ import com.eaio.uuid.UUID * overrides the dispatcher to CallingThreadDispatcher and sets the receiveTimeout to None. Otherwise, * it acts just like a normal ActorRef. You may retrieve a reference to the underlying actor to test internal logic. * - * * @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, DeploymentConfig.Transient) { dispatcher = CallingThreadDispatcher.global receiveTimeout = None - /** - * Query actor's current receive behavior. - */ - 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 diff --git a/akka-testkit/src/main/scala/akka/testkit/TestKit.scala b/akka-testkit/src/main/scala/akka/testkit/TestKit.scala index c13787fb0e..4598749ae2 100644 --- a/akka-testkit/src/main/scala/akka/testkit/TestKit.scala +++ b/akka-testkit/src/main/scala/akka/testkit/TestKit.scala @@ -3,7 +3,7 @@ */ package akka.testkit -import akka.actor.{ Actor, FSM } +import akka.actor._ import Actor._ import akka.util.Duration import akka.util.duration._ @@ -17,9 +17,19 @@ object TestActor { case class SetTimeout(d: Duration) case class SetIgnore(i: Ignore) + + trait Message { + def msg: AnyRef + def channel: UntypedChannel + } + case class RealMessage(msg: AnyRef, channel: UntypedChannel) extends Message + case object NullMessage extends Message { + override def msg: AnyRef = throw new IllegalActorStateException("last receive did not dequeue a message") + override def channel: UntypedChannel = throw new IllegalActorStateException("last receive did not dequeue a message") + } } -class TestActor(queue: BlockingDeque[AnyRef]) extends Actor with FSM[Int, TestActor.Ignore] { +class TestActor(queue: BlockingDeque[TestActor.Message]) extends Actor with FSM[Int, TestActor.Ignore] { import FSM._ import TestActor._ @@ -36,7 +46,7 @@ class TestActor(queue: BlockingDeque[AnyRef]) extends Actor with FSM[Int, TestAc 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) + queue.offerLast(RealMessage(x, self.channel)) } stay } @@ -76,19 +86,23 @@ class TestActor(queue: BlockingDeque[AnyRef]) extends Actor with FSM[Int, TestAc */ trait TestKit { - private val queue = new LinkedBlockingDeque[AnyRef]() + import TestActor.{ Message, RealMessage, NullMessage } + + private val queue = new LinkedBlockingDeque[Message]() + private[akka] var lastMessage: Message = NullMessage /** * ActorRef of the test actor. Access is provided to enable e.g. * registration as message target. */ - protected val testActor = actorOf(new TestActor(queue)).start() + implicit val testActor = actorOf(new TestActor(queue)).start() /** * Implicit sender reference so that replies are possible for messages sent * from the test class. */ - protected implicit val senderOption = Some(testActor) + @deprecated("will be removed after 1.2, replaced by implicit testActor", "1.2") + val senderOption = Some(testActor) private var end: Duration = Duration.Inf /* @@ -183,6 +197,14 @@ trait TestKit { */ def within[T](max: Duration)(f: ⇒ T): T = within(0 seconds, max)(f) + /** + * Send reply to the last dequeued message. Will throw + * IllegalActorStateException if no message has been dequeued, yet. Dequeuing + * means reception of the message as part of an expect... or receive... call, + * not reception by the testActor. + */ + def reply(msg: AnyRef) { lastMessage.channel ! msg } + /** * Same as `expectMsg`, but takes the maximum wait time from the innermost * enclosing `within` block. @@ -396,16 +418,21 @@ trait TestKit { */ def receiveWhile[T](max: Duration)(f: PartialFunction[AnyRef, T]): Seq[T] = { val stop = now + max + var msg: Message = NullMessage @tailrec def doit(acc: List[T]): List[T] = { - receiveOne(stop - now) match { - case null ⇒ + receiveOne(stop - now) + lastMessage match { + case NullMessage ⇒ + lastMessage = msg acc.reverse - case o if (f isDefinedAt o) ⇒ + case RealMessage(o, _) if (f isDefinedAt o) ⇒ + msg = lastMessage doit(f(o) :: acc) - case o ⇒ - queue.offerFirst(o) + case RealMessage(o, _) ⇒ + queue.offerFirst(lastMessage) + lastMessage = msg acc.reverse } } @@ -415,7 +442,10 @@ trait TestKit { ret } - private def receiveN(n: Int, stop: Duration): Seq[AnyRef] = { + /** + * Receive N messages in a row before the given deadline. + */ + def receiveN(n: Int, stop: Duration): Seq[AnyRef] = { for { x ← 1 to n } yield { val timeout = stop - now val o = receiveOne(timeout) @@ -424,17 +454,65 @@ trait TestKit { } } - private def receiveOne(max: Duration): AnyRef = { - if (max == 0.seconds) { - queue.pollFirst - } else if (max.finite_?) { - queue.pollFirst(max.length, max.unit) - } else { - queue.takeFirst + /** + * Receive one message from the internal queue of the TestActor. If the given + * duration is zero, the queue is polled (non-blocking). + */ + def receiveOne(max: Duration): AnyRef = { + val message = + if (max == 0.seconds) { + queue.pollFirst + } else if (max.finite_?) { + queue.pollFirst(max.length, max.unit) + } else { + queue.takeFirst + } + message match { + case null ⇒ + lastMessage = NullMessage + null + case RealMessage(msg, _) ⇒ + lastMessage = message + msg } } private def format(u: TimeUnit, d: Duration) = "%.3f %s".format(d.toUnit(u), u.toString.toLowerCase) } -// vim: set ts=2 sw=2 et: +/** + * TestKit-based probe which allows sending, reception and reply. + */ +class TestProbe extends TestKit { + + /** + * Shorthand to get the testActor. + */ + def ref = testActor + + /** + * Send message to an actor while using the probe's TestActor as the sender. + * Replies will be available for inspection with all of TestKit's assertion + * methods. + */ + def send(actor: ActorRef, msg: AnyRef) = { + actor ! msg + } + + /** + * Forward this message as if in the TestActor's receive method with self.forward. + */ + def forward(actor: ActorRef, msg: AnyRef = lastMessage.msg) { + actor.!(msg)(lastMessage.channel) + } + + /** + * Get channel of last received message. + */ + def channel = lastMessage.channel + +} + +object TestProbe { + def apply() = new TestProbe +} diff --git a/akka-testkit/src/test/scala/akka/testkit/TestActorRefSpec.scala b/akka-testkit/src/test/scala/akka/testkit/TestActorRefSpec.scala index ffe39dee57..3ef904fe88 100644 --- a/akka-testkit/src/test/scala/akka/testkit/TestActorRefSpec.scala +++ b/akka-testkit/src/test/scala/akka/testkit/TestActorRefSpec.scala @@ -8,7 +8,7 @@ import org.scalatest.{ BeforeAndAfterEach, WordSpec } import akka.actor._ import akka.config.Supervision.OneForOneStrategy import akka.event.EventHandler -import akka.dispatch.Future +import akka.dispatch.{ Future, Promise } /** * Test whether TestActorRef behaves as an ActorRef should, besides its own spec. @@ -114,7 +114,7 @@ class TestActorRefSpec extends WordSpec with MustMatchers with BeforeAndAfterEac def receive = { case _ ⇒ self reply nested } }).start() a must not be (null) - val nested = (a !! "any").get.asInstanceOf[ActorRef] + val nested = (a ? "any").as[ActorRef].get nested must not be (null) a must not be theSameInstanceAs(nested) } @@ -125,7 +125,7 @@ class TestActorRefSpec extends WordSpec with MustMatchers with BeforeAndAfterEac def receive = { case _ ⇒ self reply nested } }).start() a must not be (null) - val nested = (a !! "any").get.asInstanceOf[ActorRef] + val nested = (a ? "any").as[ActorRef].get nested must not be (null) a must not be theSameInstanceAs(nested) } @@ -160,7 +160,7 @@ class TestActorRefSpec extends WordSpec with MustMatchers with BeforeAndAfterEac "stop when sent a poison pill" in { val a = TestActorRef[WorkerActor].start() intercept[ActorKilledException] { - a !! PoisonPill + (a ? PoisonPill).get } a must not be ('running) a must be('shutdown) @@ -190,7 +190,7 @@ class TestActorRefSpec extends WordSpec with MustMatchers with BeforeAndAfterEac "support futures" in { val a = TestActorRef[WorkerActor].start() - val f: Future[String] = a !!! "work" + val f = a ? "work" mapTo manifest[String] f must be('completed) f.get must equal("workDone") } @@ -234,16 +234,13 @@ class TestActorRefSpec extends WordSpec with MustMatchers with BeforeAndAfterEac EventHandler.removeListener(log) } - "proxy isDefinedAt/apply for the underlying actor" in { + "proxy apply for the underlying actor" in { val ref = TestActorRef[WorkerActor].start() - ref.isDefinedAt("work") must be(true) - ref.isDefinedAt("sleep") must be(false) intercept[IllegalActorStateException] { ref("work") } - val ch = Future.channel() + val ch = Promise.channel() ref ! ch - val f = ch.future - f must be('completed) - f.get must be("complexReply") + ch must be('completed) + ch.get must be("complexReply") } } diff --git a/akka-testkit/src/test/scala/akka/testkit/TestProbeSpec.scala b/akka-testkit/src/test/scala/akka/testkit/TestProbeSpec.scala new file mode 100644 index 0000000000..f12d8a2e19 --- /dev/null +++ b/akka-testkit/src/test/scala/akka/testkit/TestProbeSpec.scala @@ -0,0 +1,45 @@ +package akka.testkit + +import org.scalatest.WordSpec +import org.scalatest.matchers.MustMatchers +import org.scalatest.{ BeforeAndAfterEach, WordSpec } +import akka.actor._ +import akka.config.Supervision.OneForOneStrategy +import akka.event.EventHandler +import akka.dispatch.Future +import akka.util.duration._ + +class TestProbeSpec extends WordSpec with MustMatchers { + + "A TestProbe" must { + + "reply to futures" in { + val tk = TestProbe() + val future = tk.ref ? "hello" + tk.expectMsg(0 millis, "hello") // TestActor runs on CallingThreadDispatcher + tk.reply("world") + future must be('completed) + future.get must equal("world") + } + + "reply to messages" in { + val tk1 = TestProbe() + val tk2 = TestProbe() + tk1.ref.!("hello")(tk2.ref) + tk1.expectMsg(0 millis, "hello") + tk1.reply("world") + tk2.expectMsg(0 millis, "world") + } + + "properly send and reply to messages" in { + val probe1 = TestProbe() + val probe2 = TestProbe() + probe1.send(probe2.ref, "hello") + probe2.expectMsg(0 millis, "hello") + probe2.reply("world") + probe1.expectMsg(0 millis, "world") + } + + } + +} diff --git a/akka-tutorials/akka-tutorial-second/src/main/java/akka/tutorial/java/second/Pi.java b/akka-tutorials/akka-tutorial-second/src/main/java/akka/tutorial/java/second/Pi.java index 5caae5e365..673aeddf42 100644 --- a/akka-tutorials/akka-tutorial-second/src/main/java/akka/tutorial/java/second/Pi.java +++ b/akka-tutorials/akka-tutorial-second/src/main/java/akka/tutorial/java/second/Pi.java @@ -184,10 +184,10 @@ public class Pi { // send calculate message long timeout = 60000; - Future replyFuture = master.sendRequestReplyFuture(new Calculate(), timeout, null); - Option result = replyFuture.await().resultOrException(); + Future replyFuture = master.ask(new Calculate(), timeout, null); + Option result = replyFuture.await().resultOrException(); if (result.isDefined()) { - double pi = result.get(); + double pi = (Double) result.get(); // TODO java api for EventHandler? // EventHandler.info(this, String.format("\n\tPi estimate: \t\t%s\n\tCalculation time: \t%s millis", pi, (currentTimeMillis() - start))); System.out.println(String.format("\n\tPi estimate: \t\t%s\n\tCalculation time: \t%s millis", pi, (currentTimeMillis() - start))); diff --git a/akka-tutorials/akka-tutorial-second/src/main/scala/Pi.scala b/akka-tutorials/akka-tutorial-second/src/main/scala/Pi.scala index ff4b8d9c4a..72ee614752 100644 --- a/akka-tutorials/akka-tutorial-second/src/main/scala/Pi.scala +++ b/akka-tutorials/akka-tutorial-second/src/main/scala/Pi.scala @@ -104,7 +104,7 @@ object Pi extends App { val start = now //send calculate message - master.!!![Double](Calculate, timeout = 60000). + master.?(Calculate, Actor.Timeout(60000)). await.resultOrException match {//wait for the result, with a 60 seconds timeout case Some(pi) => EventHandler.info(this, "\n\tPi estimate: \t\t%s\n\tCalculation time: \t%s millis".format(pi, (now - start))) diff --git a/config/akka-reference.conf b/config/akka-reference.conf index f2385f19fe..edd36f3c92 100644 --- a/config/akka-reference.conf +++ b/config/akka-reference.conf @@ -1,14 +1,16 @@ -#################### -# Akka Config File # -#################### +############################## +# Akka Reference Config File # +############################## -# This file has all the default settings, so all these could be removed with no visible effect. +# This the reference config file has all the default settings. +# All these could be removed with no visible effect. # Modify as needed. +# This file is imported in the 'akka.conf' file. Make your edits/overrides there. akka { version = "2.0-SNAPSHOT" # Akka version, checked against the runtime version of Akka. - enabled-modules = [] # Comma separated list of the enabled modules. Options: ["remote", "camel", "http"] + enabled-modules = [] # Comma separated list of the enabled modules. Options: ["cluster", "camel", "http"] time-unit = "seconds" # Time unit for all timeout properties throughout the config @@ -25,63 +27,76 @@ akka { boot = [] actor { - timeout = 5 # Default timeout for Future based invocations - # - Actor: !! && !!! - # - UntypedActor: sendRequestReply && sendRequestReplyFuture - # - TypedActor: methods with non-void return type - serialize-messages = off # Does a deep clone of (non-primitive) messages to ensure immutability - throughput = 5 # Default throughput for all Dispatcher, set to 1 for complete fairness - throughput-deadline-time = -1 # Default throughput deadline for all Dispatcher, set to 0 or negative for no deadline - dispatcher-shutdown-timeout = 1 # Using the akka.time-unit, how long dispatchers by default will wait for new actors until they shut down + timeout = 5 # Default timeout for Future based invocations + # - Actor: !! && ? + # - UntypedActor: sendRequestReply && ask + # - TypedActor: methods with non-void return type + serialize-messages = off # Does a deep clone of (non-primitive) messages to ensure immutability + throughput = 5 # Default throughput for all Dispatcher, set to 1 for complete fairness + throughput-deadline-time = -1 # Default throughput deadline for all Dispatcher, set to 0 or negative for no deadline + dispatcher-shutdown-timeout = 1 # Using the akka.time-unit, how long dispatchers by default will wait for new actors until they shut down deployment { - # ------------------------------- - # -- all configuration options -- - # ------------------------------- + service-ping { # stateless actor with replication factor 3 and round-robin load-balancer - service-ping { # stateless actor with replication factor 3 and round-robin load-balancer - router = "least-cpu" # routing (load-balance) scheme to use - # available: "direct", "round-robin", "random", "least-cpu", "least-ram", "least-messages" - # or: fully qualified class name of the router class - # default is "direct"; - format = "akka.serialization.Format$Default$" - clustered { # makes the actor available in the cluster registry - # default (if omitted) is local non-clustered actor - home = "node:node1" # defines the hostname, IP-address or node name of the "home" node for clustered actor - # available: "host:", "ip:" and "node:" - # default is "host:localhost" - replicas = 3 # number of actor replicas in the cluster - # available: positivoe integer (0-N) or the string "auto" for auto-scaling - # if "auto" is used then 'home' has no meaning - # default is '0', meaning no replicas; - stateless = on # is the actor stateless or stateful - # if turned 'on': actor is defined as stateless and can be load-balanced accordingly - # if turned 'off' (or omitted): actor is defined as stateful which means replicatable through transaction log - # default is 'off' + format = "akka.serialization.Format$Default$" # serializer for messages and actor instance + + router = "least-cpu" # routing (load-balance) scheme to use + # available: "direct", "round-robin", "random", + # "least-cpu", "least-ram", "least-messages" + # or: fully qualified class name of the router class + # default is "direct"; + + clustered { # makes the actor available in the cluster registry + # default (if omitted) is local non-clustered actor + + home = "node:node1" # hostname, IP-address or node name of the "home" node for clustered actor + # available: "host:", "ip:" and "node:" + # default is "host:localhost" + + replicas = 3 # number of actor replicas in the cluster + # available: positivoe integer (0-N) or the string "auto" for auto-scaling + # if "auto" is used then 'home' has no meaning + # default is '0', meaning no replicas; + + replication { # use replication or not? + + # FIXME should we have this config option here? If so, implement it all through. + serialize-mailbox = on # should the actor mailbox be part of the serialized snapshot? + + storage = "transaction-log" # storage model for replication + # available: "transaction-log" and "data-grid" + # default is "transaction-log" + + strategy = "write-through" # guaranteees for replication + # available: "write-through" and "write-behind" + # default is "write-through" + + } } } } default-dispatcher { - type = "GlobalDispatcher" # Must be one of the following, all "Global*" are non-configurable - # - Dispatcher - # - BalancingDispatcher - # - GlobalDispatcher - keep-alive-time = 60 # Keep alive time for threads - core-pool-size-factor = 1.0 # No of core threads ... ceil(available processors * factor) - max-pool-size-factor = 4.0 # Max no of threads ... ceil(available processors * factor) - executor-bounds = -1 # Makes the Executor bounded, -1 is unbounded - allow-core-timeout = on # Allow core threads to time out - rejection-policy = "caller-runs" # abort, caller-runs, discard-oldest, discard - throughput = 5 # Throughput for Dispatcher, set to 1 for complete fairness - throughput-deadline-time = -1 # Throughput deadline for Dispatcher, set to 0 or negative for no deadline - mailbox-capacity = -1 # If negative (or zero) then an unbounded mailbox is used (default) - # If positive then a bounded mailbox is used and the capacity is set using the property - # NOTE: setting a mailbox to 'blocking' can be a bit dangerous, could lead to deadlock, use with care - # The following are only used for Dispatcher and only if mailbox-capacity > 0 - mailbox-push-timeout-time = 10 # Specifies the timeout to add a new message to a mailbox that is full - negative number means infinite timeout - # (in unit defined by the time-unit property) + type = "GlobalDispatcher" # Must be one of the following, all "Global*" are non-configurable + # - Dispatcher + # - BalancingDispatcher + # - GlobalDispatcher + keep-alive-time = 60 # Keep alive time for threads + core-pool-size-factor = 1.0 # No of core threads ... ceil(available processors * factor) + max-pool-size-factor = 4.0 # Max no of threads ... ceil(available processors * factor) + executor-bounds = -1 # Makes the Executor bounded, -1 is unbounded + allow-core-timeout = on # Allow core threads to time out + rejection-policy = "caller-runs" # abort, caller-runs, discard-oldest, discard + throughput = 5 # Throughput for Dispatcher, set to 1 for complete fairness + throughput-deadline-time = -1 # Throughput deadline for Dispatcher, set to 0 or negative for no deadline + mailbox-capacity = -1 # If negative (or zero) then an unbounded mailbox is used (default) + # If positive then a bounded mailbox is used and the capacity is set using the property + # NOTE: setting a mailbox to 'blocking' can be a bit dangerous, could lead to deadlock, use with care + # The following are only used for Dispatcher and only if mailbox-capacity > 0 + mailbox-push-timeout-time = 10 # Specifies the timeout to add a new message to a mailbox that is full - negative number means infinite timeout + # (in unit defined by the time-unit property) } mailbox { @@ -126,93 +141,36 @@ akka { cluster { name = "test-cluster" - zookeeper-server-addresses = "localhost:2181" + zookeeper-server-addresses = "localhost:2181" # comma-separated list of ':' elements remote-server-port = 2552 max-time-to-wait-until-connected = 30 session-timeout = 60 connection-timeout = 60 use-compression = off - remote-daemon-ack-timeout = 30 - exclude-ref-node-in-replica-set = on # should a replica be instantiated on the same node as the - # cluster reference to the actor - # default: on - - replication { - digest-type = "MAC" # Options: CRC32 (cheap & unsafe), MAC (expensive & secure using password) - password = "secret" - ensemble-size = 3 - quorum-size = 2 - } - } - - stm { - fair = on # Should global transactions be fair or non-fair (non fair yield better performance) - max-retries = 1000 - timeout = 5 # Default timeout for blocking transactions and transaction set (in unit defined by - # the time-unit property) - write-skew = true - blocking-allowed = false - interruptible = false - speculative = true - quick-release = true - propagation = "requires" - trace-level = "none" - } - - http { - hostname = "localhost" - port = 9998 - - #If you are using akka.http.AkkaRestServlet - filters = ["akka.security.AkkaSecurityFilterFactory"] # List with all jersey filters to use - # resource-packages = ["sample.rest.scala", - # "sample.rest.java", - # "sample.security"] # List with all resource packages for your Jersey services - resource-packages = [] - - # The authentication service to use. Need to be overridden (sample now) - # authenticator = "sample.security.BasicAuthenticationService" - authenticator = "N/A" - - # Uncomment if you are using the KerberosAuthenticationActor - # kerberos { - # servicePrincipal = "HTTP/localhost@EXAMPLE.COM" - # keyTabLocation = "URL to keytab" - # kerberosDebug = "true" - # realm = "EXAMPLE.COM" - # } - kerberos { - servicePrincipal = "N/A" - keyTabLocation = "N/A" - kerberosDebug = "N/A" - realm = "" - } - - # If you are using akka.http.AkkaMistServlet - mist-dispatcher { - #type = "GlobalDispatcher" # Uncomment if you want to use a different dispatcher than the default one for Comet - } - connection-close = true # toggles the addition of the "Connection" response header with a "close" value - root-actor-id = "_httproot" # the id of the actor to use as the root endpoint - root-actor-builtin = true # toggles the use of the built-in root endpoint base class - timeout = 1000 # the default timeout for all async requests (in ms) - expired-header-name = "Async-Timeout" # the name of the response header to use when an async request expires - expired-header-value = "expired" # the value of the response header to use when an async request expires - } - - remote { - - # secure-cookie = "050E0A0D0D06010A00000900040D060F0C09060B" # generate your own with '$AKKA_HOME/scripts/generate_config_with_secure_cookie.sh' or using 'Crypt.generateSecureCookie' - secure-cookie = "" - - compression-scheme = "zlib" # Options: "zlib" (lzf to come), leave out for no compression - zlib-compression-level = 6 # Options: 0-9 (1 being fastest and 9 being the most compressed), default is 6 + remote-daemon-ack-timeout = 30 # Timeout for ACK of cluster operations, lik checking actor out etc. + exclude-ref-node-in-replica-set = on # Should a replica be instantiated on the same node as the + # cluster reference to the actor + # Default: on + compression-scheme = "zlib" # Options: "zlib" (lzf to come), leave out for no compression + zlib-compression-level = 6 # Options: 0-9 (1 being fastest and 9 being the most compressed), default is 6 + # FIXME rename to transport layer = "akka.remote.netty.NettyRemoteSupport" + secure-cookie = "" # Generate your own with '$AKKA_HOME/scripts/generate_config_with_secure_cookie.sh' + # or using 'akka.util.Crypt.generateSecureCookie' + + replication { + digest-type = "MAC" # Options: CRC32 (cheap & unsafe), MAC (expensive & secure using password) + password = "secret" # FIXME: store open in file? + ensemble-size = 3 + quorum-size = 2 + snapshot-frequency = 1000 # The number of messages that should be logged between every actor snapshot + timeout = 30 # Timeout for asyncronous (write-behind) operations + } + server { - hostname = "localhost" # The hostname or IP that clients should connect to - port = 2552 # The port clients should connect to. Default is 2552 (AKKA) + port = 2552 # The default remote server port clients should connect to. Default is 2552 (AKKA) message-frame-size = 1048576 # Increase this if you want to be able to send messages with large payloads connection-timeout = 1 require-cookie = off # Should the remote server require that it peers share the same secure-cookie (defined in the 'remote' section)? @@ -234,7 +192,36 @@ akka { read-timeout = 10 message-frame-size = 1048576 reap-futures-delay = 5 - reconnection-time-window = 600 # Maximum time window that a client should try to reconnect for + reconnection-time-window = 600 # Maximum time window that a client should try to reconnect for } } + + stm { + fair = on # Should global transactions be fair or non-fair (non fair yield better performance) + max-retries = 1000 + timeout = 5 # Default timeout for blocking transactions and transaction set (in unit defined by + # the time-unit property) + write-skew = true + blocking-allowed = false + interruptible = false + speculative = true + quick-release = true + propagation = "requires" + trace-level = "none" + } + + http { + hostname = "localhost" + port = 9998 + + mist-dispatcher { # If you are using akka.http.AkkaMistServlet + #type = "GlobalDispatcher" # Uncomment if you want to use a different dispatcher than the default one for Comet + } + connection-close = true # toggles the addition of the "Connection" response header with a "close" value + root-actor-id = "_httproot" # the id of the actor to use as the root endpoint + root-actor-builtin = true # toggles the use of the built-in root endpoint base class + timeout = 1000 # the default timeout for all async requests (in ms) + expired-header-name = "Async-Timeout" # the name of the response header to use when an async request expires + expired-header-value = "expired" # the value of the response header to use when an async request expires + } } diff --git a/config/microkernel-server.xml b/config/microkernel-server.xml new file mode 100644 index 0000000000..be7382405d --- /dev/null +++ b/config/microkernel-server.xml @@ -0,0 +1,106 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 300000 + 2 + false + 8443 + 20000 + 5000 + + + + + + + + + + + + + + + + + / + + akka.http.AkkaMistServlet + /* + + + + + + + + + + + + + + + true + true + true + 1000 + + diff --git a/project/build/AkkaProject.scala b/project/build/AkkaProject.scala index ec0a765aa1..a0462e2543 100644 --- a/project/build/AkkaProject.scala +++ b/project/build/AkkaProject.scala @@ -67,19 +67,21 @@ class AkkaParentProject(info: ProjectInfo) extends ParentProject(info) with Exec lazy val beanstalkModuleConfig = ModuleConfiguration("beanstalk", AkkaRepo) lazy val lzfModuleConfig = ModuleConfiguration("voldemort.store.compress", "h2-lzf", AkkaRepo) lazy val vscaladocModuleConfig = ModuleConfiguration("org.scala-tools", "vscaladoc", "1.1-md-3", AkkaRepo) - lazy val aspectWerkzModuleConfig = ModuleConfiguration("org.codehaus.aspectwerkz", "aspectwerkz", "2.2.3", AkkaRepo) lazy val objenesisModuleConfig = ModuleConfiguration("org.objenesis", sbt.DefaultMavenRepository) lazy val jdmkModuleConfig = ModuleConfiguration("com.sun.jdmk", SunJDMKRepo) lazy val jmxModuleConfig = ModuleConfiguration("com.sun.jmx", SunJDMKRepo) lazy val jmsModuleConfig = ModuleConfiguration("javax.jms", JBossRepo) lazy val jsr311ModuleConfig = ModuleConfiguration("javax.ws.rs", "jsr311-api", sbt.DefaultMavenRepository) lazy val zookeeperModuleConfig = ModuleConfiguration("org.apache.hadoop.zookeeper", AkkaRepo) + lazy val protobufModuleConfig = ModuleConfiguration("com.google.protobuf", AkkaRepo) lazy val zkclientModuleConfig = ModuleConfiguration("zkclient", AkkaRepo) + lazy val camelModuleConfig = ModuleConfiguration("org.apache.camel", "camel-core", AkkaRepo) // ------------------------------------------------------------------------------------------------------------------- // Versions // ------------------------------------------------------------------------------------------------------------------- lazy val CAMEL_VERSION = "2.7.1" + lazy val CAMEL_PATCH_VERSION = "2.7.1.1" lazy val SPRING_VERSION = "3.0.5.RELEASE" lazy val JACKSON_VERSION = "1.8.0" lazy val JERSEY_VERSION = "1.3" @@ -99,11 +101,9 @@ class AkkaParentProject(info: ProjectInfo) extends ParentProject(info) with Exec // Compile - lazy val aopalliance = "aopalliance" % "aopalliance" % "1.0" % "compile" //Public domain - lazy val aspectwerkz = "org.codehaus.aspectwerkz" % "aspectwerkz" % "2.2.3" % "compile" //ApacheV2 lazy val beanstalk = "beanstalk" % "beanstalk_client" % "1.4.5" //New BSD lazy val bookkeeper = "org.apache.hadoop.zookeeper" % "bookkeeper" % ZOOKEEPER_VERSION //ApacheV2 - lazy val camel_core = "org.apache.camel" % "camel-core" % CAMEL_VERSION % "compile" //ApacheV2 + lazy val camel_core = "org.apache.camel" % "camel-core" % CAMEL_PATCH_VERSION % "compile" //ApacheV2 lazy val commons_codec = "commons-codec" % "commons-codec" % "1.4" % "compile" //ApacheV2 lazy val commons_io = "commons-io" % "commons-io" % "2.0.1" % "compile" //ApacheV2 @@ -127,7 +127,7 @@ class AkkaParentProject(info: ProjectInfo) extends ParentProject(info) with Exec lazy val multiverse = "org.multiverse" % "multiverse-alpha" % MULTIVERSE_VERSION % "compile" //ApacheV2 lazy val netty = "org.jboss.netty" % "netty" % "3.2.4.Final" % "compile" //ApacheV2 lazy val osgi_core = "org.osgi" % "org.osgi.core" % "4.2.0" //ApacheV2 - lazy val protobuf = "com.google.protobuf" % "protobuf-java" % "2.3.0" % "compile" //New BSD + lazy val protobuf = "com.google.protobuf" % "protobuf-java" % "2.4.1" % "compile" //New BSD lazy val redis = "net.debasishg" % "redisclient_2.9.0" % "2.3.1" //ApacheV2 lazy val sjson = "net.debasishg" %% "sjson" % "0.11" % "compile" //ApacheV2 lazy val sjson_test = "net.debasishg" %% "sjson" % "0.11" % "test" //ApacheV2 @@ -136,7 +136,7 @@ class AkkaParentProject(info: ProjectInfo) extends ParentProject(info) with Exec lazy val spring_context = "org.springframework" % "spring-context" % SPRING_VERSION % "compile" //ApacheV2 lazy val stax_api = "javax.xml.stream" % "stax-api" % "1.0-2" % "compile" //ApacheV2 - lazy val logback = "ch.qos.logback" % "logback-classic" % "0.9.28" % "runtime" //MIT + lazy val logback = "ch.qos.logback" % "logback-classic" % "0.9.28" % "runtime" //MIT lazy val log4j = "log4j" % "log4j" % "1.2.15" //ApacheV2 lazy val zookeeper = "org.apache.hadoop.zookeeper" % "zookeeper" % ZOOKEEPER_VERSION //ApacheV2 lazy val zookeeper_lock = "org.apache.hadoop.zookeeper" % "zookeeper-recipes-lock" % ZOOKEEPER_VERSION //ApacheV2 @@ -144,14 +144,14 @@ class AkkaParentProject(info: ProjectInfo) extends ParentProject(info) with Exec // Test lazy val multiverse_test = "org.multiverse" % "multiverse-alpha" % MULTIVERSE_VERSION % "test" //ApacheV2 - lazy val commons_coll = "commons-collections" % "commons-collections" % "3.2.1" % "test" //ApacheV2 - lazy val testJetty = "org.eclipse.jetty" % "jetty-server" % JETTY_VERSION % "test" //Eclipse license - lazy val testJettyWebApp = "org.eclipse.jetty" % "jetty-webapp" % JETTY_VERSION % "test" //Eclipse license - lazy val junit = "junit" % "junit" % "4.5" % "test" //Common Public License 1.0 - lazy val mockito = "org.mockito" % "mockito-all" % "1.8.1" % "test" //MIT - lazy val scalatest = "org.scalatest" %% "scalatest" % SCALATEST_VERSION % "test" //ApacheV2 - lazy val testLogback = "ch.qos.logback" % "logback-classic" % LOGBACK_VERSION % "test" // EPL 1.0 / LGPL 2.1 - lazy val camel_spring = "org.apache.camel" % "camel-spring" % CAMEL_VERSION % "test" //ApacheV2 + lazy val commons_coll = "commons-collections" % "commons-collections" % "3.2.1" % "test" //ApacheV2 + lazy val testJetty = "org.eclipse.jetty" % "jetty-server" % JETTY_VERSION % "test" //Eclipse license + lazy val testJettyWebApp = "org.eclipse.jetty" % "jetty-webapp" % JETTY_VERSION % "test" //Eclipse license + lazy val junit = "junit" % "junit" % "4.5" % "test" //Common Public License 1.0 + lazy val mockito = "org.mockito" % "mockito-all" % "1.8.1" % "test" //MIT + lazy val scalatest = "org.scalatest" %% "scalatest" % SCALATEST_VERSION % "test" //ApacheV2 + lazy val testLogback = "ch.qos.logback" % "logback-classic" % LOGBACK_VERSION % "test" // EPL 1.0 / LGPL 2.1 + lazy val camel_spring = "org.apache.camel" % "camel-spring" % CAMEL_VERSION % "test" //ApacheV2 } @@ -169,10 +169,10 @@ class AkkaParentProject(info: ProjectInfo) extends ParentProject(info) with Exec lazy val akka_cluster = project("akka-cluster", "akka-cluster", new AkkaClusterProject(_), akka_remote) lazy val akka_durable_mailboxes = project("akka-durable-mailboxes", "akka-durable-mailboxes", new AkkaDurableMailboxesParentProject(_), akka_remote) - lazy val akka_camel = project("akka-camel", "akka-camel", new AkkaCamelProject(_), akka_actor, akka_slf4j) + //lazy val akka_camel = project("akka-camel", "akka-camel", new AkkaCamelProject(_), akka_actor, akka_slf4j) //lazy val akka_camel_typed = project("akka-camel-typed", "akka-camel-typed", new AkkaCamelTypedProject(_), akka_actor, akka_slf4j, akka_camel) //lazy val akka_spring = project("akka-spring", "akka-spring", new AkkaSpringProject(_), akka_remote, akka_actor, akka_camel) - lazy val akka_kernel = project("akka-kernel", "akka-kernel", new AkkaKernelProject(_), akka_stm, akka_remote, akka_http, akka_slf4j, akka_camel) + //lazy val akka_kernel = project("akka-kernel", "akka-kernel", new AkkaKernelProject(_), akka_stm, akka_remote, akka_http, akka_slf4j, akka_camel) lazy val akka_sbt_plugin = project("akka-sbt-plugin", "akka-sbt-plugin", new AkkaSbtPluginProject(_)) lazy val akka_tutorials = project("akka-tutorials", "akka-tutorials", new AkkaTutorialsParentProject(_), akka_actor) @@ -598,31 +598,35 @@ class AkkaParentProject(info: ProjectInfo) extends ParentProject(info) with Exec } } - class AkkaSampleRemoteProject(info: ProjectInfo) extends AkkaDefaultProject(info) - class AkkaSampleChatProject(info: ProjectInfo) extends AkkaDefaultProject(info) class AkkaSampleFSMProject(info: ProjectInfo) extends AkkaDefaultProject(info) + class AkkaSampleHelloProject(info: ProjectInfo) extends AkkaDefaultProject(info) + class AkkaSampleOsgiProject(info: ProjectInfo) extends AkkaDefaultProject(info) with BNDPlugin { val osgiCore = Dependencies.osgi_core override protected def bndPrivatePackage = List("sample.osgi.*") override protected def bndBundleActivator = Some("sample.osgi.Activator") } + class AkkaSampleRemoteProject(info: ProjectInfo) extends AkkaDefaultProject(info) + class AkkaSamplesParentProject(info: ProjectInfo) extends ParentProject(info) { override def disableCrossPaths = true lazy val akka_sample_ants = project("akka-sample-ants", "akka-sample-ants", new AkkaSampleAntsProject(_), akka_stm) + // lazy val akka_sample_chat = project("akka-sample-chat", "akka-sample-chat", + // new AkkaSampleChatProject(_), akka_remote) lazy val akka_sample_fsm = project("akka-sample-fsm", "akka-sample-fsm", new AkkaSampleFSMProject(_), akka_actor) -// lazy val akka_sample_remote = project("akka-sample-remote", "akka-sample-remote", -// new AkkaSampleRemoteProject(_), akka_remote) -// lazy val akka_sample_chat = project("akka-sample-chat", "akka-sample-chat", -// new AkkaSampleChatProject(_), akka_remote) + // lazy val akka_sample_hello = project("akka-sample-hello", "akka-sample-hello", + // new AkkaSampleHelloProject(_), akka_kernel) lazy val akka_sample_osgi = project("akka-sample-osgi", "akka-sample-osgi", new AkkaSampleOsgiProject(_), akka_actor) + // lazy val akka_sample_remote = project("akka-sample-remote", "akka-sample-remote", + // new AkkaSampleRemoteProject(_), akka_remote) lazy val publishRelease = { val releaseConfiguration = new DefaultPublishConfiguration(localReleaseRepository, "release", false) @@ -681,6 +685,9 @@ class AkkaParentProject(info: ProjectInfo) extends ParentProject(info) with Exec val junit = Dependencies.junit val scalatest = Dependencies.scalatest val multiverse_test = Dependencies.multiverse_test // StandardLatch + val protobuf = Dependencies.protobuf + val jackson = Dependencies.jackson + val sjson = Dependencies.sjson override def compileOptions = super.compileOptions ++ compileOptions("-P:continuations:enable") } @@ -784,6 +791,9 @@ class AkkaParentProject(info: ProjectInfo) extends ParentProject(info) with Exec lazy val akkaCoreDist = project("core", "akka-dist-core", new AkkaCoreDistProject(_), akkaActorsDist, akka_remote, akka_http, akka_slf4j, akka_testkit, akka_actor_tests) +// lazy val akkaMicrokernelDist = project("microkernel", "akka-dist-microkernel", new AkkaMicrokernelDistProject(_), +// akkaCoreDist, akka_kernel, akka_samples) + def doNothing = task { None } override def publishLocalAction = doNothing override def deliverLocalAction = doNothing @@ -792,6 +802,7 @@ class AkkaParentProject(info: ProjectInfo) extends ParentProject(info) with Exec class AkkaActorsDistProject(info: ProjectInfo) extends DefaultProject(info) with DistDocProject { def distName = "akka-actors" + override def distDocName = "akka" override def distConfigSources = (akkaParent.info.projectPath / "config" ##) * "*" @@ -817,6 +828,51 @@ class AkkaParentProject(info: ProjectInfo) extends ParentProject(info) with Exec class AkkaCoreDistProject(info: ProjectInfo)extends DefaultProject(info) with DistProject { def distName = "akka-core" } + + class AkkaMicrokernelDistProject(info: ProjectInfo) extends DefaultProject(info) with DistProject { + def distName = "akka-microkernel" + + override def distScriptSources = akkaParent.info.projectPath / "scripts" / "microkernel" * "*" + +// override def distClasspath = akka_kernel.runClasspath + +// override def projectDependencies = akka_kernel.topologicalSort + +// override def distAction = super.distAction dependsOn (distSamples) + +// val distSamplesPath = distDocPath / "samples" + + // lazy val distSamples = task { + // val demo = akka_samples.akka_sample_hello.jarPath + // val samples = Set(//akka_samples.akka_sample_camel + // akka_samples.akka_sample_hello) + // //akka_samples.akka_sample_security) + + // def copySamples[P <: DefaultProject](samples: Set[P]) = { + // samples.map { sample => + // val sampleOutputPath = distSamplesPath / sample.name + // val binPath = sampleOutputPath / "bin" + // val configPath = sampleOutputPath / "config" + // val deployPath = sampleOutputPath / "deploy" + // val libPath = sampleOutputPath / "lib" + // val srcPath = sampleOutputPath / "src" + // val confs = sample.info.projectPath / "config" ** "*.*" + // val scripts = akkaParent.info.projectPath / "scripts" / "samples" * "*" + // val libs = sample.managedClasspath(Configurations.Runtime) + // val deployed = sample.jarPath + // val sources = sample.packageSourcePaths + // copyFiles(confs, configPath) orElse + // copyScripts(scripts, binPath) orElse + // copyFiles(libs, libPath) orElse + // copyFiles(deployed, deployPath) orElse + // copyPaths(sources, srcPath) + // }.foldLeft(None: Option[String])(_ orElse _) + // } + + // copyFiles(demo, distDeployPath) orElse + // copySamples(samples) + // } dependsOn (distBase) + } } } diff --git a/project/build/DistProject.scala b/project/build/DistProject.scala index de1cb0cdf9..f930adbf37 100644 --- a/project/build/DistProject.scala +++ b/project/build/DistProject.scala @@ -4,27 +4,7 @@ import sbt._ -trait DistBaseProject extends DefaultProject { - def distOutputPath: Path - def distLibPath: Path - def distSrcPath: Path - def distDocPath: Path - def dist: Task - - override def disableCrossPaths = true - - def doNothing = task { None } - override def compileAction = doNothing - override def testCompileAction = doNothing - override def testAction = doNothing - override def packageAction = doNothing - override def publishLocalAction = doNothing - override def deliverLocalAction = doNothing - override def publishAction = doNothing - override def deliverAction = doNothing -} - -trait DistProject extends DistBaseProject { +trait DistProject extends DefaultProject { def distName: String val distFullName = distName + "-" + version @@ -38,7 +18,6 @@ trait DistProject extends DistBaseProject { val distSrcPath = distOutputPath / "src" / "akka" val distDocPath = distOutputPath / "doc" / "akka" val distDocJarsPath = distDocPath / "api" / "jars" - val distSharePath = Path.userHome / ".ivy2" / "dist" / distFullName val distArchiveName = distFullName + ".zip" val distArchive = (distOutputBasePath ##) / distArchiveName @@ -58,7 +37,7 @@ trait DistProject extends DistBaseProject { def distDependencies = { allProjectDependencies.flatMap( p => p match { - case adp: DistBaseProject => Some(adp) + case dp: DistProject => Some(dp) case _ => None }) } @@ -92,8 +71,6 @@ trait DistProject extends DistBaseProject { def distDocJars = dependencyJars(isDocJar) +++ projectDependencyJars(_.packageDocsJar) - def distShareSources = ((distOutputPath ##) ***) - lazy val dist = (distAction dependsOn (distBase, `package`, packageSrc, packageDocs) describedAs("Create a distribution.")) @@ -116,7 +93,6 @@ trait DistProject extends DistBaseProject { copyFiles(distDocJars, distDocJarsPath) orElse copyPaths(distConfigSources, distConfigPath) orElse copyScripts(distScriptSources, distBinPath) orElse - copyPaths(distShareSources, distSharePath) orElse FileUtilities.zip(List(distOutputPath), distArchive, true, log) orElse exclusiveDist } @@ -136,8 +112,7 @@ trait DistProject extends DistBaseProject { describedAs "Clean the dist target dir.") def distCleanAction = task { - FileUtilities.clean(distOutputPath, log) orElse - FileUtilities.clean(distSharePath, log) + FileUtilities.clean(distOutputPath, log) } def copyFiles(from: PathFinder, to: Path): Option[String] = { @@ -162,6 +137,18 @@ trait DistProject extends DistBaseProject { val success = target.asFile.setExecutable(executable, false) if (success) None else Some("Couldn't set permissions of " + target) } + + override def disableCrossPaths = true + + def doNothing = task { None } + override def compileAction = doNothing + override def testCompileAction = doNothing + override def testAction = doNothing + override def packageAction = doNothing + override def publishLocalAction = doNothing + override def deliverLocalAction = doNothing + override def publishAction = doNothing + override def deliverAction = doNothing } trait DistDocProject extends DistProject { @@ -197,19 +184,3 @@ trait DistDocProject extends DistProject { copyPaths(docsPdfSources, docsPdfPath) } dependsOn (distBase, docParent.docs) } - -/* - * For wiring together akka and akka-modules. - */ -trait DistSharedProject extends DistBaseProject { - def distName: String - - val distFullName = distName + "-" + version - val distOutputPath = Path.userHome / ".ivy2" / "dist" / distFullName - - val distLibPath = distOutputPath / "lib" / "akka" - val distSrcPath = distOutputPath / "src" / "akka" - val distDocPath = distOutputPath / "doc" / "akka" - - lazy val dist = task { None } -} diff --git a/project/scripts/copy-xsd.sh b/project/scripts/copy-xsd.sh new file mode 100644 index 0000000000..214d3332b2 --- /dev/null +++ b/project/scripts/copy-xsd.sh @@ -0,0 +1,40 @@ +#!/bin/bash + +# Copy the akka-version.xsd file to akka.io, renaming it for a release. +# +# Example usage: +# +# sh project/scripts/copy-xsd.sh 1.1-RC1 + +RELEASE=$1 + +if [ -z "$RELEASE" ]; then + echo "Usage: copy-xsd.sh RELEASE" + exit 1 +fi + +version=`grep 'project.version' project/build.properties | cut -d '=' -f2` + +if [ -z "$version" ]; then + echo "Couldn't find the current version in project/build.properties" + exit 1 +fi + +source ~/.akka-release + +if [ -z "$AKKA_RELEASE_SERVER" ]; then + echo "Need AKKA_RELEASE_SERVER to be specified" + exit 1 +fi + +if [ -z "$AKKA_RELEASE_PATH" ]; then + echo "Need AKKA_RELEASE_PATH to be specified" + exit 1 +fi + +echo "Verify sudo on $AKKA_RELEASE_SERVER" +ssh -t ${AKKA_RELEASE_SERVER} sudo -v + +scp akka-spring/src/main/resources/akka/spring/akka-${version}.xsd ${AKKA_RELEASE_SERVER}:/tmp/akka-${RELEASE}.xsd +ssh -t ${AKKA_RELEASE_SERVER} sudo cp /tmp/akka-${RELEASE}.xsd ${AKKA_RELEASE_PATH}/akka-${RELEASE}.xsd +ssh -t ${AKKA_RELEASE_SERVER} rm -f /tmp/akka-${RELEASE}.xsd diff --git a/project/scripts/find-replace.sh b/project/scripts/find-replace.sh index 884ff53a2a..fc21a8aa9f 100644 --- a/project/scripts/find-replace.sh +++ b/project/scripts/find-replace.sh @@ -22,7 +22,7 @@ echo "Find and replace: $FIND --> $REPLACE" # Exclude directories from search -excludedirs=".git dist deploy embedded-repo lib_managed project/boot project/scripts src_managed target akka-docs" +excludedirs=".git dist deploy embedded-repo lib_managed project/boot project/scripts src_managed target" echo "Excluding directories: $excludedirs" diff --git a/project/scripts/release b/project/scripts/release index 2fd97d8693..847e8c350a 100644 --- a/project/scripts/release +++ b/project/scripts/release @@ -1,8 +1,10 @@ sh git checkout -b releasing-{{release.arg1}} +set akka.release true clean script find-replace.sh {{project.version}} {{release.arg1}} script find-replace.sh //[[:space:]]*release:[[:space:]]* reload build-release +sh git add . sh git commit -am 'Update version for release {{project.version}}' sh git tag -m 'Version {{project.version}}' v{{project.version}} diff --git a/project/scripts/test-release b/project/scripts/test-release index 4e821f15f5..17ae402b9f 100644 --- a/project/scripts/test-release +++ b/project/scripts/test-release @@ -1,3 +1,4 @@ +set akka.release true clean clean-lib script find-replace.sh {{project.version}} {{test-release.arg1}} @@ -8,4 +9,5 @@ test-compile test build-release sh git reset --hard +sh git clean -f reload diff --git a/scripts/microkernel/akka b/scripts/microkernel/akka new file mode 100755 index 0000000000..4241d2693d --- /dev/null +++ b/scripts/microkernel/akka @@ -0,0 +1,9 @@ +#!/bin/bash + +AKKA_HOME="$(cd "$(cd "$(dirname "$0")"; pwd -P)"/..; pwd)" + +[ -n "$JAVA_OPTS" ] || JAVA_OPTS="-Xms1536M -Xmx1536M -Xss1M -XX:MaxPermSize=256M -XX:+UseParallelGC" + +[ -n "$AKKA_CLASSPATH" ] || AKKA_CLASSPATH="$AKKA_HOME/lib/scala-library.jar:$AKKA_HOME/lib/akka/*:$AKKA_HOME/config" + +java $JAVA_OPTS -cp "$AKKA_CLASSPATH" -Dakka.home="$AKKA_HOME" akka.kernel.Main diff --git a/scripts/microkernel/akka.bat b/scripts/microkernel/akka.bat new file mode 100644 index 0000000000..59d1a91a48 --- /dev/null +++ b/scripts/microkernel/akka.bat @@ -0,0 +1,6 @@ +@echo off +set AKKA_HOME=%~dp0.. +set JAVA_OPTS=-Xms1024M -Xmx1024M -Xss1M -XX:MaxPermSize=256M -XX:+UseParallelGC +set AKKA_CLASSPATH=%AKKA_HOME%\lib\scala-library.jar;%AKKA_HOME%\config;%AKKA_HOME%\lib\akka\* + +java %JAVA_OPTS% -cp "%AKKA_CLASSPATH%" -Dakka.home="%AKKA_HOME%" akka.kernel.Main diff --git a/scripts/samples/start b/scripts/samples/start new file mode 100755 index 0000000000..491c617db2 --- /dev/null +++ b/scripts/samples/start @@ -0,0 +1,13 @@ +#!/bin/bash + +SAMPLE="$(cd "$(cd "$(dirname "$0")"; pwd -P)"/..; pwd)" + +AKKA_HOME="$(cd "$SAMPLE"/../../../..; pwd)" + +[ -n "$JAVA_OPTS" ] || JAVA_OPTS="-Xms1536M -Xmx1536M -Xss1M -XX:MaxPermSize=256M -XX:+UseParallelGC" + +[ -n "$AKKA_CLASSPATH" ] || AKKA_CLASSPATH="$AKKA_HOME/lib/scala-library.jar:$AKKA_HOME/lib/akka/*" + +SAMPLE_CLASSPATH="$AKKA_CLASSPATH:$SAMPLE/lib/*:$SAMPLE/config" + +java $JAVA_OPTS -cp "$SAMPLE_CLASSPATH" -Dakka.home="$SAMPLE" akka.kernel.Main diff --git a/scripts/samples/start.bat b/scripts/samples/start.bat new file mode 100644 index 0000000000..1bffae4e5b --- /dev/null +++ b/scripts/samples/start.bat @@ -0,0 +1,8 @@ +@echo off +set SAMPLE=%~dp0.. +set AKKA_HOME=%SAMPLE%\..\..\..\.. +set JAVA_OPTS=-Xms1024M -Xmx1024M -Xss1M -XX:MaxPermSize=256M -XX:+UseParallelGC +set AKKA_CLASSPATH=%AKKA_HOME%\lib\scala-library.jar;%AKKA_HOME%\lib\akka\* +set SAMPLE_CLASSPATH=%AKKA_CLASSPATH%;%SAMPLE%\lib\*;%SAMPLE%\config + +java %JAVA_OPTS% -cp "%SAMPLE_CLASSPATH%" -Dakka.home="%SAMPLE%" akka.kernel.Main