Merged with origin/master

This commit is contained in:
Viktor Klang 2010-05-22 16:19:39 +02:00
commit 124bfd8dc5
161 changed files with 1689 additions and 1075 deletions

View file

@ -80,7 +80,7 @@ object AMQP {
class AMQPSupervisor extends Actor with Logging {
import scala.collection.JavaConversions._
import self._
private val connections = new ConcurrentHashMap[ActorRef, ActorRef]
self.faultHandler = Some(OneForOneStrategy(5, 5000))
@ -364,7 +364,7 @@ object AMQP {
import scala.collection.JavaConversions._
import self._
faultHandler = Some(OneForOneStrategy(5, 5000))
trapExit = List(classOf[Throwable])

View file

@ -22,7 +22,7 @@ object ExampleSession {
direct
Thread.sleep(1000)
println("==== FANOUT ===")
fanout
}
@ -47,4 +47,4 @@ object ExampleSession {
val producer = AMQP.newProducer(CONFIG, HOSTNAME, PORT, CHAT, None, None, 100)
producer ! Message("@jonas_boner: I'm going surfing".getBytes, "")
}
}
}

View file

@ -11,7 +11,7 @@ import se.scalablesolutions.akka.util.Logging
/**
* Defines the lifecycle of a CamelContext. Allowed state transitions are
* init -> start -> stop -> init -> ... etc.
* init -> start -> stop -> init -> ... etc.
*
* @author Martin Krasser
*/
@ -95,4 +95,4 @@ trait CamelContextLifecycle extends Logging {
object CamelContextManager extends CamelContextLifecycle {
override def context: CamelContext = super.context
override def template: ProducerTemplate = super.template
}
}

View file

@ -17,4 +17,4 @@ trait Consumer { self: Actor =>
* Returns the Camel endpoint URI to consume messages from.
*/
def endpointUri: String
}
}

View file

@ -23,7 +23,7 @@ case class Message(val body: Any, val headers: Map[String, Any] = Map.empty) {
*
* @see CamelContextManager.
*/
@deprecated("use bodyAs[T](implicit m: Manifest[T]): T instead")
@deprecated("use bodyAs[T](implicit m: Manifest[T]): T instead")
def bodyAs[T](clazz: Class[T]): T =
CamelContextManager.context.getTypeConverter.mandatoryConvertTo[T](clazz, body)
@ -53,7 +53,7 @@ case class Message(val body: Any, val headers: Map[String, Any] = Map.empty) {
*
* @see Message#bodyAs(Class)
*/
@deprecated("use setBodyAs[T](implicit m: Manifest[T]): Message instead")
@deprecated("use setBodyAs[T](implicit m: Manifest[T]): Message instead")
def setBodyAs[T](clazz: Class[T]): Message = setBody(bodyAs(clazz))
/**
@ -200,7 +200,7 @@ class CamelExchangeAdapter(exchange: Exchange) {
*
* @see Failure
*/
def toFailureMessage(headers: Map[String, Any]): Failure =
def toFailureMessage(headers: Map[String, Any]): Failure =
Failure(exchange.getException, headers ++ responseMessage.toMessage.headers)
private def requestMessage = exchange.getIn
@ -246,19 +246,19 @@ class CamelMessageAdapter(val cm: CamelMessage) {
/**
* Defines conversion methods to CamelExchangeAdapter and CamelMessageAdapter.
* Imported by applications
* that implicitly want to use conversion methods of CamelExchangeAdapter and CamelMessageAdapter.
* that implicitly want to use conversion methods of CamelExchangeAdapter and CamelMessageAdapter.
*/
object CamelMessageConversion {
/**
* Creates an CamelExchangeAdapter for the given Camel exchange.
*/
implicit def toExchangeAdapter(ce: Exchange): CamelExchangeAdapter =
implicit def toExchangeAdapter(ce: Exchange): CamelExchangeAdapter =
new CamelExchangeAdapter(ce)
/**
* Creates an CamelMessageAdapter for the given Camel message.
*/
implicit def toMessageAdapter(cm: CamelMessage): CamelMessageAdapter =
implicit def toMessageAdapter(cm: CamelMessage): CamelMessageAdapter =
new CamelMessageAdapter(cm)
}
}

View file

@ -20,7 +20,7 @@ import se.scalablesolutions.akka.util.Logging
* @author Martin Krasser
*/
trait Producer { this: Actor =>
private val headersToCopyDefault = Set(Message.MessageExchangeId)
/**
@ -162,7 +162,7 @@ trait Producer { this: Actor =>
*/
class ProducerResponseSender(
headers: Map[String, Any],
sender: Option[ActorRef],
sender: Option[ActorRef],
senderFuture: Option[CompletableFuture[Any]],
producer: Actor) extends Synchronization with Logging {

View file

@ -27,7 +27,7 @@ class ActorComponent extends DefaultComponent {
val idAndUuid = idAndUuidPair(remaining)
new ActorEndpoint(uri, this, idAndUuid._1, idAndUuid._2)
}
private def idAndUuidPair(remaining: String): Tuple2[Option[String], Option[String]] = {
remaining split ":" toList match {
case id :: Nil => (Some(id), None)
@ -52,13 +52,13 @@ class ActorComponent extends DefaultComponent {
* @author Martin Krasser
*/
class ActorEndpoint(uri: String,
comp: ActorComponent,
val id: Option[String],
class ActorEndpoint(uri: String,
comp: ActorComponent,
val id: Option[String],
val uuid: Option[String]) extends DefaultEndpoint(uri, comp) {
/**
* @throws UnsupportedOperationException
* @throws UnsupportedOperationException
*/
def createConsumer(processor: Processor): Consumer =
throw new UnsupportedOperationException("actor consumer not supported yet")
@ -106,7 +106,7 @@ class ActorProducer(val ep: ActorEndpoint) extends DefaultProducer(ep) {
* Send the exchange in-message to the given actor using the ! operator. The message
* send to the actor is of type se.scalablesolutions.akka.camel.Message.
*/
protected def processInOnly(exchange: Exchange, actor: ActorRef): Unit =
protected def processInOnly(exchange: Exchange, actor: ActorRef): Unit =
actor ! exchange.toRequestMessage(Map(Message.MessageExchangeId -> exchange.getExchangeId))
/**
@ -149,4 +149,4 @@ class ActorProducer(val ep: ActorEndpoint) extends DefaultProducer(ep) {
*/
class ActorNotRegisteredException(uri: String) extends RuntimeException {
override def getMessage = "%s not registered" format uri
}
}

View file

@ -23,4 +23,4 @@ class CamelContextLifecycleTest extends JUnitSuite with CamelContextLifecycle {
}
class TestCamelContext extends DefaultCamelContext
}
}

View file

@ -106,4 +106,4 @@ class CamelExchangeAdapterTest extends JUnitSuite {
exchange.setPattern(pattern)
exchange
}
}
}

View file

@ -35,4 +35,4 @@ class CamelMessageAdapterTest extends JUnitSuite {
}
}
}

View file

@ -70,4 +70,4 @@ class MessageTest extends JUnitSuite with BeforeAndAfterAll {
Message("test1" , Map("A" -> "1")),
Message("test1" , Map("A" -> "1", "B" -> "2")).removeHeader("B"))
}
}
}

View file

@ -17,7 +17,7 @@ object ProducerFeatureTest {
class ProducerFeatureTest extends FeatureSpec with BeforeAndAfterAll with BeforeAndAfterEach with GivenWhenThen {
import ProducerFeatureTest._
override protected def beforeAll = {
ActorRegistry.shutdownAll
CamelContextManager.init
@ -122,7 +122,7 @@ class ProducerFeatureTest extends FeatureSpec with BeforeAndAfterAll with Before
}
private def mockEndpoint = CamelContextManager.context.getEndpoint("mock:mock", classOf[MockEndpoint])
class TestRoute extends RouteBuilder {
def configure {
// for one-way messaging tests
@ -138,4 +138,4 @@ class ProducerFeatureTest extends FeatureSpec with BeforeAndAfterAll with Before
})
}
}
}
}

View file

@ -11,17 +11,17 @@ class ActorComponentFeatureTest extends FeatureSpec with BeforeAndAfterAll with
override protected def beforeAll = {
ActorRegistry.shutdownAll
CamelContextManager.init
CamelContextManager.start
CamelContextManager.start
}
override protected def afterAll = CamelContextManager.stop
override protected def afterEach = ActorRegistry.shutdownAll
feature("Communicate with an actor from a Camel application using actor endpoint URIs") {
import CamelContextManager.template
import Actor._
scenario("one-way communication using actor id") {
val actor = actorOf(new Tester with Retain with Countdown[Message])
actor.start
@ -60,4 +60,4 @@ class ActorComponentFeatureTest extends FeatureSpec with BeforeAndAfterAll with
}
}
}
}
}

View file

@ -8,7 +8,7 @@ import se.scalablesolutions.akka.camel.{CamelContextManager, Message, Consumer}
import Actor._
object CamelServiceFeatureTest {
class TestConsumer(uri: String) extends Actor with Consumer {
def endpointUri = uri
protected def receive = {
@ -32,7 +32,7 @@ object CamelServiceFeatureTest {
class CamelServiceFeatureTest extends FeatureSpec with BeforeAndAfterAll with GivenWhenThen {
import CamelServiceFeatureTest._
var service: CamelService = CamelService.newInstance
override protected def beforeAll = {
@ -46,7 +46,7 @@ class CamelServiceFeatureTest extends FeatureSpec with BeforeAndAfterAll with Gi
service.consumerPublisher.actor.asInstanceOf[ConsumerPublisher].expectPublishCount(1)
// start the CamelService
service.load
// await publication of first test consumer
// await publication of first test consumer
service.consumerPublisher.actor.asInstanceOf[ConsumerPublisher].awaitPublish
}
@ -114,4 +114,4 @@ class CamelServiceFeatureTest extends FeatureSpec with BeforeAndAfterAll with Gi
assert(response === "received msg3")
}
}
}
}

View file

@ -27,7 +27,7 @@ object ConsumerRegisteredTest {
class ConsumerRegisteredTest extends JUnitSuite {
import ConsumerRegisteredTest._
@Test def shouldCreatePublishRequestList = {
val as = List(actorOf[ConsumeAnnotatedActor])
val events = for (a <- as; e <- ConsumerRegistered.forConsumer(a)) yield e

View file

@ -15,4 +15,4 @@ public @interface consume {
public abstract String value();
}
}

View file

@ -15,7 +15,7 @@ import com.google.inject.Singleton;
*/
public class ActiveObjectGuiceModule extends AbstractModule {
private final List<DependencyBinding> bindings;
public ActiveObjectGuiceModule(final List<DependencyBinding> bindings) {
this.bindings = bindings;
}
@ -25,7 +25,7 @@ public class ActiveObjectGuiceModule extends AbstractModule {
for (int i = 0; i < bindings.size(); i++) {
final DependencyBinding db = bindings.get(i);
//if (db.getInterface() ne null) bind((Class) db.getInterface()).to((Class) db.getTarget()).in(Singleton.class);
//else
//else
this.bind(db.getInterface()).toInstance(db.getTarget());
}
}

View file

@ -10,7 +10,7 @@ package se.scalablesolutions.akka.config;
public class DependencyBinding {
private final Class intf;
private final Object target;
public DependencyBinding(final Class intf, final Object target) {
this.intf = intf;
this.target = target;

View file

@ -11,61 +11,61 @@ public final class RemoteProtocol {
com.google.protobuf.GeneratedMessage {
// Use ActorRefProtocol.newBuilder() to construct.
private ActorRefProtocol() {}
private static final ActorRefProtocol defaultInstance = new ActorRefProtocol();
public static ActorRefProtocol getDefaultInstance() {
return defaultInstance;
}
public ActorRefProtocol getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.internal_static_se_scalablesolutions_akka_remote_protobuf_ActorRefProtocol_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.internal_static_se_scalablesolutions_akka_remote_protobuf_ActorRefProtocol_fieldAccessorTable;
}
// required string uuid = 1;
public static final int UUID_FIELD_NUMBER = 1;
private boolean hasUuid;
private java.lang.String uuid_ = "";
public boolean hasUuid() { return hasUuid; }
public java.lang.String getUuid() { return uuid_; }
// required string actorClassName = 2;
public static final int ACTORCLASSNAME_FIELD_NUMBER = 2;
private boolean hasActorClassName;
private java.lang.String actorClassName_ = "";
public boolean hasActorClassName() { return hasActorClassName; }
public java.lang.String getActorClassName() { return actorClassName_; }
// required string sourceHostname = 3;
public static final int SOURCEHOSTNAME_FIELD_NUMBER = 3;
private boolean hasSourceHostname;
private java.lang.String sourceHostname_ = "";
public boolean hasSourceHostname() { return hasSourceHostname; }
public java.lang.String getSourceHostname() { return sourceHostname_; }
// required uint32 sourcePort = 4;
public static final int SOURCEPORT_FIELD_NUMBER = 4;
private boolean hasSourcePort;
private int sourcePort_ = 0;
public boolean hasSourcePort() { return hasSourcePort; }
public int getSourcePort() { return sourcePort_; }
// required uint64 timeout = 5;
public static final int TIMEOUT_FIELD_NUMBER = 5;
private boolean hasTimeout;
private long timeout_ = 0L;
public boolean hasTimeout() { return hasTimeout; }
public long getTimeout() { return timeout_; }
public final boolean isInitialized() {
if (!hasUuid) return false;
if (!hasActorClassName) return false;
@ -74,7 +74,7 @@ public final class RemoteProtocol {
if (!hasTimeout) return false;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (hasUuid()) {
@ -94,12 +94,12 @@ public final class RemoteProtocol {
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasUuid()) {
size += com.google.protobuf.CodedOutputStream
@ -125,7 +125,7 @@ public final class RemoteProtocol {
memoizedSerializedSize = size;
return size;
}
public static se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
@ -183,31 +183,31 @@ public final class RemoteProtocol {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> {
private se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol result;
// Construct using se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol.newBuilder()
private Builder() {}
private static Builder create() {
Builder builder = new Builder();
builder.result = new se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol();
return builder;
}
protected se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol internalGetResult() {
return result;
}
public Builder clear() {
if (result == null) {
throw new IllegalStateException(
@ -216,20 +216,20 @@ public final class RemoteProtocol {
result = new se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol();
return this;
}
public Builder clone() {
return create().mergeFrom(result);
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol.getDescriptor();
}
public se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol getDefaultInstanceForType() {
return se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol.getDefaultInstance();
}
public boolean isInitialized() {
return result.isInitialized();
}
@ -239,7 +239,7 @@ public final class RemoteProtocol {
}
return buildPartial();
}
private se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
if (!isInitialized()) {
@ -248,7 +248,7 @@ public final class RemoteProtocol {
}
return buildPartial();
}
public se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol buildPartial() {
if (result == null) {
throw new IllegalStateException(
@ -258,7 +258,7 @@ public final class RemoteProtocol {
result = null;
return returnMe;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol) {
return mergeFrom((se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol)other);
@ -267,7 +267,7 @@ public final class RemoteProtocol {
return this;
}
}
public Builder mergeFrom(se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol other) {
if (other == se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol.getDefaultInstance()) return this;
if (other.hasUuid()) {
@ -288,7 +288,7 @@ public final class RemoteProtocol {
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
@ -333,8 +333,8 @@ public final class RemoteProtocol {
}
}
}
// required string uuid = 1;
public boolean hasUuid() {
return result.hasUuid();
@ -355,7 +355,7 @@ public final class RemoteProtocol {
result.uuid_ = getDefaultInstance().getUuid();
return this;
}
// required string actorClassName = 2;
public boolean hasActorClassName() {
return result.hasActorClassName();
@ -376,7 +376,7 @@ public final class RemoteProtocol {
result.actorClassName_ = getDefaultInstance().getActorClassName();
return this;
}
// required string sourceHostname = 3;
public boolean hasSourceHostname() {
return result.hasSourceHostname();
@ -397,7 +397,7 @@ public final class RemoteProtocol {
result.sourceHostname_ = getDefaultInstance().getSourceHostname();
return this;
}
// required uint32 sourcePort = 4;
public boolean hasSourcePort() {
return result.hasSourcePort();
@ -415,7 +415,7 @@ public final class RemoteProtocol {
result.sourcePort_ = 0;
return this;
}
// required uint64 timeout = 5;
public boolean hasTimeout() {
return result.hasTimeout();
@ -434,131 +434,131 @@ public final class RemoteProtocol {
return this;
}
}
static {
se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.getDescriptor();
}
static {
se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.internalForceInit();
}
}
public static final class RemoteRequestProtocol extends
com.google.protobuf.GeneratedMessage {
// Use RemoteRequestProtocol.newBuilder() to construct.
private RemoteRequestProtocol() {}
private static final RemoteRequestProtocol defaultInstance = new RemoteRequestProtocol();
public static RemoteRequestProtocol getDefaultInstance() {
return defaultInstance;
}
public RemoteRequestProtocol getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.internal_static_se_scalablesolutions_akka_remote_protobuf_RemoteRequestProtocol_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.internal_static_se_scalablesolutions_akka_remote_protobuf_RemoteRequestProtocol_fieldAccessorTable;
}
// required uint64 id = 1;
public static final int ID_FIELD_NUMBER = 1;
private boolean hasId;
private long id_ = 0L;
public boolean hasId() { return hasId; }
public long getId() { return id_; }
// required uint32 protocol = 2;
public static final int PROTOCOL_FIELD_NUMBER = 2;
private boolean hasProtocol;
private int protocol_ = 0;
public boolean hasProtocol() { return hasProtocol; }
public int getProtocol() { return protocol_; }
// required bytes message = 3;
public static final int MESSAGE_FIELD_NUMBER = 3;
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 = 4;
public static final int MESSAGEMANIFEST_FIELD_NUMBER = 4;
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 string method = 5;
public static final int METHOD_FIELD_NUMBER = 5;
private boolean hasMethod;
private java.lang.String method_ = "";
public boolean hasMethod() { return hasMethod; }
public java.lang.String getMethod() { return method_; }
// required string target = 6;
public static final int TARGET_FIELD_NUMBER = 6;
private boolean hasTarget;
private java.lang.String target_ = "";
public boolean hasTarget() { return hasTarget; }
public java.lang.String getTarget() { return target_; }
// required string uuid = 7;
public static final int UUID_FIELD_NUMBER = 7;
private boolean hasUuid;
private java.lang.String uuid_ = "";
public boolean hasUuid() { return hasUuid; }
public java.lang.String getUuid() { return uuid_; }
// required uint64 timeout = 8;
public static final int TIMEOUT_FIELD_NUMBER = 8;
private boolean hasTimeout;
private long timeout_ = 0L;
public boolean hasTimeout() { return hasTimeout; }
public long getTimeout() { return timeout_; }
// optional string supervisorUuid = 9;
public static final int SUPERVISORUUID_FIELD_NUMBER = 9;
private boolean hasSupervisorUuid;
private java.lang.String supervisorUuid_ = "";
public boolean hasSupervisorUuid() { return hasSupervisorUuid; }
public java.lang.String getSupervisorUuid() { return supervisorUuid_; }
// required bool isActor = 10;
public static final int ISACTOR_FIELD_NUMBER = 10;
private boolean hasIsActor;
private boolean isActor_ = false;
public boolean hasIsActor() { return hasIsActor; }
public boolean getIsActor() { return isActor_; }
// required bool isOneWay = 11;
public static final int ISONEWAY_FIELD_NUMBER = 11;
private boolean hasIsOneWay;
private boolean isOneWay_ = false;
public boolean hasIsOneWay() { return hasIsOneWay; }
public boolean getIsOneWay() { return isOneWay_; }
// required bool isEscaped = 12;
public static final int ISESCAPED_FIELD_NUMBER = 12;
private boolean hasIsEscaped;
private boolean isEscaped_ = false;
public boolean hasIsEscaped() { return hasIsEscaped; }
public boolean getIsEscaped() { return isEscaped_; }
// optional .se.scalablesolutions.akka.remote.protobuf.ActorRefProtocol sender = 13;
public static final int SENDER_FIELD_NUMBER = 13;
private boolean hasSender;
private se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol sender_ = se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol.getDefaultInstance();
public boolean hasSender() { return hasSender; }
public se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.ActorRefProtocol getSender() { return sender_; }
public final boolean isInitialized() {
if (!hasId) return false;
if (!hasProtocol) return false;
@ -574,7 +574,7 @@ public final class RemoteProtocol {
}
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (hasId()) {
@ -618,12 +618,12 @@ public final class RemoteProtocol {
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasId()) {
size += com.google.protobuf.CodedOutputStream
@ -681,7 +681,7 @@ public final class RemoteProtocol {
memoizedSerializedSize = size;
return size;
}
public static se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
@ -739,31 +739,31 @@ public final class RemoteProtocol {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> {
private se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol result;
// Construct using se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol.newBuilder()
private Builder() {}
private static Builder create() {
Builder builder = new Builder();
builder.result = new se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol();
return builder;
}
protected se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol internalGetResult() {
return result;
}
public Builder clear() {
if (result == null) {
throw new IllegalStateException(
@ -772,20 +772,20 @@ public final class RemoteProtocol {
result = new se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol();
return this;
}
public Builder clone() {
return create().mergeFrom(result);
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol.getDescriptor();
}
public se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol getDefaultInstanceForType() {
return se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol.getDefaultInstance();
}
public boolean isInitialized() {
return result.isInitialized();
}
@ -795,7 +795,7 @@ public final class RemoteProtocol {
}
return buildPartial();
}
private se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
if (!isInitialized()) {
@ -804,7 +804,7 @@ public final class RemoteProtocol {
}
return buildPartial();
}
public se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol buildPartial() {
if (result == null) {
throw new IllegalStateException(
@ -814,7 +814,7 @@ public final class RemoteProtocol {
result = null;
return returnMe;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol) {
return mergeFrom((se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol)other);
@ -823,7 +823,7 @@ public final class RemoteProtocol {
return this;
}
}
public Builder mergeFrom(se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol other) {
if (other == se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteRequestProtocol.getDefaultInstance()) return this;
if (other.hasId()) {
@ -868,7 +868,7 @@ public final class RemoteProtocol {
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
@ -950,8 +950,8 @@ public final class RemoteProtocol {
}
}
}
// required uint64 id = 1;
public boolean hasId() {
return result.hasId();
@ -969,7 +969,7 @@ public final class RemoteProtocol {
result.id_ = 0L;
return this;
}
// required uint32 protocol = 2;
public boolean hasProtocol() {
return result.hasProtocol();
@ -987,7 +987,7 @@ public final class RemoteProtocol {
result.protocol_ = 0;
return this;
}
// required bytes message = 3;
public boolean hasMessage() {
return result.hasMessage();
@ -1008,7 +1008,7 @@ public final class RemoteProtocol {
result.message_ = getDefaultInstance().getMessage();
return this;
}
// optional bytes messageManifest = 4;
public boolean hasMessageManifest() {
return result.hasMessageManifest();
@ -1029,7 +1029,7 @@ public final class RemoteProtocol {
result.messageManifest_ = getDefaultInstance().getMessageManifest();
return this;
}
// optional string method = 5;
public boolean hasMethod() {
return result.hasMethod();
@ -1050,7 +1050,7 @@ public final class RemoteProtocol {
result.method_ = getDefaultInstance().getMethod();
return this;
}
// required string target = 6;
public boolean hasTarget() {
return result.hasTarget();
@ -1071,7 +1071,7 @@ public final class RemoteProtocol {
result.target_ = getDefaultInstance().getTarget();
return this;
}
// required string uuid = 7;
public boolean hasUuid() {
return result.hasUuid();
@ -1092,7 +1092,7 @@ public final class RemoteProtocol {
result.uuid_ = getDefaultInstance().getUuid();
return this;
}
// required uint64 timeout = 8;
public boolean hasTimeout() {
return result.hasTimeout();
@ -1110,7 +1110,7 @@ public final class RemoteProtocol {
result.timeout_ = 0L;
return this;
}
// optional string supervisorUuid = 9;
public boolean hasSupervisorUuid() {
return result.hasSupervisorUuid();
@ -1131,7 +1131,7 @@ public final class RemoteProtocol {
result.supervisorUuid_ = getDefaultInstance().getSupervisorUuid();
return this;
}
// required bool isActor = 10;
public boolean hasIsActor() {
return result.hasIsActor();
@ -1149,7 +1149,7 @@ public final class RemoteProtocol {
result.isActor_ = false;
return this;
}
// required bool isOneWay = 11;
public boolean hasIsOneWay() {
return result.hasIsOneWay();
@ -1167,7 +1167,7 @@ public final class RemoteProtocol {
result.isOneWay_ = false;
return this;
}
// required bool isEscaped = 12;
public boolean hasIsEscaped() {
return result.hasIsEscaped();
@ -1185,7 +1185,7 @@ public final class RemoteProtocol {
result.isEscaped_ = false;
return this;
}
// optional .se.scalablesolutions.akka.remote.protobuf.ActorRefProtocol sender = 13;
public boolean hasSender() {
return result.hasSender();
@ -1223,103 +1223,103 @@ public final class RemoteProtocol {
return this;
}
}
static {
se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.getDescriptor();
}
static {
se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.internalForceInit();
}
}
public static final class RemoteReplyProtocol extends
com.google.protobuf.GeneratedMessage {
// Use RemoteReplyProtocol.newBuilder() to construct.
private RemoteReplyProtocol() {}
private static final RemoteReplyProtocol defaultInstance = new RemoteReplyProtocol();
public static RemoteReplyProtocol getDefaultInstance() {
return defaultInstance;
}
public RemoteReplyProtocol getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.internal_static_se_scalablesolutions_akka_remote_protobuf_RemoteReplyProtocol_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.internal_static_se_scalablesolutions_akka_remote_protobuf_RemoteReplyProtocol_fieldAccessorTable;
}
// required uint64 id = 1;
public static final int ID_FIELD_NUMBER = 1;
private boolean hasId;
private long id_ = 0L;
public boolean hasId() { return hasId; }
public long getId() { return id_; }
// optional uint32 protocol = 2;
public static final int PROTOCOL_FIELD_NUMBER = 2;
private boolean hasProtocol;
private int protocol_ = 0;
public boolean hasProtocol() { return hasProtocol; }
public int getProtocol() { return protocol_; }
// optional bytes message = 3;
public static final int MESSAGE_FIELD_NUMBER = 3;
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 = 4;
public static final int MESSAGEMANIFEST_FIELD_NUMBER = 4;
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 string exception = 5;
public static final int EXCEPTION_FIELD_NUMBER = 5;
private boolean hasException;
private java.lang.String exception_ = "";
public boolean hasException() { return hasException; }
public java.lang.String getException() { return exception_; }
// optional string supervisorUuid = 6;
public static final int SUPERVISORUUID_FIELD_NUMBER = 6;
private boolean hasSupervisorUuid;
private java.lang.String supervisorUuid_ = "";
public boolean hasSupervisorUuid() { return hasSupervisorUuid; }
public java.lang.String getSupervisorUuid() { return supervisorUuid_; }
// required bool isActor = 7;
public static final int ISACTOR_FIELD_NUMBER = 7;
private boolean hasIsActor;
private boolean isActor_ = false;
public boolean hasIsActor() { return hasIsActor; }
public boolean getIsActor() { return isActor_; }
// required bool isSuccessful = 8;
public static final int ISSUCCESSFUL_FIELD_NUMBER = 8;
private boolean hasIsSuccessful;
private boolean isSuccessful_ = false;
public boolean hasIsSuccessful() { return hasIsSuccessful; }
public boolean getIsSuccessful() { return isSuccessful_; }
public final boolean isInitialized() {
if (!hasId) return false;
if (!hasIsActor) return false;
if (!hasIsSuccessful) return false;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (hasId()) {
@ -1348,12 +1348,12 @@ public final class RemoteProtocol {
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasId()) {
size += com.google.protobuf.CodedOutputStream
@ -1391,7 +1391,7 @@ public final class RemoteProtocol {
memoizedSerializedSize = size;
return size;
}
public static se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
@ -1449,31 +1449,31 @@ public final class RemoteProtocol {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> {
private se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol result;
// Construct using se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol.newBuilder()
private Builder() {}
private static Builder create() {
Builder builder = new Builder();
builder.result = new se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol();
return builder;
}
protected se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol internalGetResult() {
return result;
}
public Builder clear() {
if (result == null) {
throw new IllegalStateException(
@ -1482,20 +1482,20 @@ public final class RemoteProtocol {
result = new se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol();
return this;
}
public Builder clone() {
return create().mergeFrom(result);
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol.getDescriptor();
}
public se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol getDefaultInstanceForType() {
return se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol.getDefaultInstance();
}
public boolean isInitialized() {
return result.isInitialized();
}
@ -1505,7 +1505,7 @@ public final class RemoteProtocol {
}
return buildPartial();
}
private se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
if (!isInitialized()) {
@ -1514,7 +1514,7 @@ public final class RemoteProtocol {
}
return buildPartial();
}
public se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol buildPartial() {
if (result == null) {
throw new IllegalStateException(
@ -1524,7 +1524,7 @@ public final class RemoteProtocol {
result = null;
return returnMe;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol) {
return mergeFrom((se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol)other);
@ -1533,7 +1533,7 @@ public final class RemoteProtocol {
return this;
}
}
public Builder mergeFrom(se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol other) {
if (other == se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.RemoteReplyProtocol.getDefaultInstance()) return this;
if (other.hasId()) {
@ -1563,7 +1563,7 @@ public final class RemoteProtocol {
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
@ -1620,8 +1620,8 @@ public final class RemoteProtocol {
}
}
}
// required uint64 id = 1;
public boolean hasId() {
return result.hasId();
@ -1639,7 +1639,7 @@ public final class RemoteProtocol {
result.id_ = 0L;
return this;
}
// optional uint32 protocol = 2;
public boolean hasProtocol() {
return result.hasProtocol();
@ -1657,7 +1657,7 @@ public final class RemoteProtocol {
result.protocol_ = 0;
return this;
}
// optional bytes message = 3;
public boolean hasMessage() {
return result.hasMessage();
@ -1678,7 +1678,7 @@ public final class RemoteProtocol {
result.message_ = getDefaultInstance().getMessage();
return this;
}
// optional bytes messageManifest = 4;
public boolean hasMessageManifest() {
return result.hasMessageManifest();
@ -1699,7 +1699,7 @@ public final class RemoteProtocol {
result.messageManifest_ = getDefaultInstance().getMessageManifest();
return this;
}
// optional string exception = 5;
public boolean hasException() {
return result.hasException();
@ -1720,7 +1720,7 @@ public final class RemoteProtocol {
result.exception_ = getDefaultInstance().getException();
return this;
}
// optional string supervisorUuid = 6;
public boolean hasSupervisorUuid() {
return result.hasSupervisorUuid();
@ -1741,7 +1741,7 @@ public final class RemoteProtocol {
result.supervisorUuid_ = getDefaultInstance().getSupervisorUuid();
return this;
}
// required bool isActor = 7;
public boolean hasIsActor() {
return result.hasIsActor();
@ -1759,7 +1759,7 @@ public final class RemoteProtocol {
result.isActor_ = false;
return this;
}
// required bool isSuccessful = 8;
public boolean hasIsSuccessful() {
return result.hasIsSuccessful();
@ -1778,16 +1778,16 @@ public final class RemoteProtocol {
return this;
}
}
static {
se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.getDescriptor();
}
static {
se.scalablesolutions.akka.remote.protobuf.RemoteProtocol.internalForceInit();
}
}
private static com.google.protobuf.Descriptors.Descriptor
internal_static_se_scalablesolutions_akka_remote_protobuf_ActorRefProtocol_descriptor;
private static
@ -1803,7 +1803,7 @@ public final class RemoteProtocol {
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_se_scalablesolutions_akka_remote_protobuf_RemoteReplyProtocol_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
@ -1868,6 +1868,6 @@ public final class RemoteProtocol {
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
}
public static void internalForceInit() {}
}

View file

@ -43,4 +43,4 @@ message RemoteReplyProtocol {
optional string supervisorUuid = 6;
required bool isActor = 7;
required bool isSuccessful = 8;
}
}

View file

@ -30,8 +30,8 @@ object Annotations {
}
/**
* Configuration factory for Active Objects.
*
* Configuration factory for Active Objects.
*
* FIXDOC: document ActiveObjectConfiguration
*/
final class ActiveObjectConfiguration {
@ -74,7 +74,7 @@ final class ActiveObjectConfiguration {
*/
object ActiveObject {
import Actor.actorOf
val AKKA_CAMEL_ROUTING_SCHEME = "akka"
private[actor] val AW_PROXY_PREFIX = "$$ProxiedByAW".intern
@ -182,7 +182,7 @@ object ActiveObject {
}
@deprecated("use newInstance(intf: Class[T], target: AnyRef, config: ActiveObjectConfiguration) instead")
def newInstance[T](intf: Class[T], target: AnyRef, timeout: Long,
def newInstance[T](intf: Class[T], target: AnyRef, timeout: Long,
dispatcher: MessageDispatcher, restartCallbacks: Option[RestartCallbacks]): T = {
val actor = actorOf(new Dispatcher(false, restartCallbacks))
actor.dispatcher = dispatcher
@ -197,7 +197,7 @@ object ActiveObject {
}
@deprecated("use newInstance(target: Class[T], config: ActiveObjectConfiguration) instead")
def newInstance[T](target: Class[T], timeout: Long, transactionRequired: Boolean,
def newInstance[T](target: Class[T], timeout: Long, transactionRequired: Boolean,
dispatcher: MessageDispatcher, restartCallbacks: Option[RestartCallbacks]): T = {
val actor = actorOf(new Dispatcher(transactionRequired, restartCallbacks))
actor.dispatcher = dispatcher
@ -212,7 +212,7 @@ object ActiveObject {
}
@deprecated("use newInstance(intf: Class[T], target: AnyRef, config: ActiveObjectConfiguration) instead")
def newInstance[T](intf: Class[T], target: AnyRef, timeout: Long, transactionRequired: Boolean,
def newInstance[T](intf: Class[T], target: AnyRef, timeout: Long, transactionRequired: Boolean,
dispatcher: MessageDispatcher, restartCallbacks: Option[RestartCallbacks]): T = {
val actor = actorOf(new Dispatcher(transactionRequired, restartCallbacks))
actor.dispatcher = dispatcher
@ -227,7 +227,7 @@ object ActiveObject {
}
@deprecated("use newInstance(target: Class[T], config: ActiveObjectConfiguration) instead")
def newRemoteInstance[T](target: Class[T], timeout: Long, dispatcher: MessageDispatcher,
def newRemoteInstance[T](target: Class[T], timeout: Long, dispatcher: MessageDispatcher,
hostname: String, port: Int, restartCallbacks: Option[RestartCallbacks]): T = {
val actor = actorOf(new Dispatcher(false, restartCallbacks))
actor.dispatcher = dispatcher
@ -242,7 +242,7 @@ object ActiveObject {
}
@deprecated("use newInstance(intf: Class[T], target: AnyRef, config: ActiveObjectConfiguration) instead")
def newRemoteInstance[T](intf: Class[T], target: AnyRef, timeout: Long, dispatcher: MessageDispatcher,
def newRemoteInstance[T](intf: Class[T], target: AnyRef, timeout: Long, dispatcher: MessageDispatcher,
hostname: String, port: Int, restartCallbacks: Option[RestartCallbacks]): T = {
val actor = actorOf(new Dispatcher(false, restartCallbacks))
actor.dispatcher = dispatcher
@ -250,7 +250,7 @@ object ActiveObject {
}
@deprecated("use newInstance(target: Class[T], config: ActiveObjectConfiguration) instead")
def newRemoteInstance[T](target: Class[T], timeout: Long, transactionRequired: Boolean,
def newRemoteInstance[T](target: Class[T], timeout: Long, transactionRequired: Boolean,
dispatcher: MessageDispatcher, hostname: String, port: Int): T = {
val actor = actorOf(new Dispatcher(transactionRequired, None))
actor.dispatcher = dispatcher
@ -258,7 +258,7 @@ object ActiveObject {
}
@deprecated("use newInstance(target: Class[T], config: ActiveObjectConfiguration) instead")
def newRemoteInstance[T](target: Class[T], timeout: Long, transactionRequired: Boolean, dispatcher: MessageDispatcher,
def newRemoteInstance[T](target: Class[T], timeout: Long, transactionRequired: Boolean, dispatcher: MessageDispatcher,
hostname: String, port: Int, restartCallbacks: Option[RestartCallbacks]): T = {
val actor = actorOf(new Dispatcher(transactionRequired, restartCallbacks))
actor.dispatcher = dispatcher
@ -266,7 +266,7 @@ object ActiveObject {
}
@deprecated("use newInstance(intf: Class[T], target: AnyRef, config: ActiveObjectConfiguration) instead")
def newRemoteInstance[T](intf: Class[T], target: AnyRef, timeout: Long, transactionRequired: Boolean,
def newRemoteInstance[T](intf: Class[T], target: AnyRef, timeout: Long, transactionRequired: Boolean,
dispatcher: MessageDispatcher, hostname: String, port: Int): T = {
val actor = actorOf(new Dispatcher(transactionRequired, None))
actor.dispatcher = dispatcher
@ -274,7 +274,7 @@ object ActiveObject {
}
@deprecated("use newInstance(intf: Class[T], target: AnyRef, config: ActiveObjectConfiguration) instead")
def newRemoteInstance[T](intf: Class[T], target: AnyRef, timeout: Long, transactionRequired: Boolean,
def newRemoteInstance[T](intf: Class[T], target: AnyRef, timeout: Long, transactionRequired: Boolean,
dispatcher: MessageDispatcher, hostname: String, port: Int, restartCallbacks: Option[RestartCallbacks]): T = {
val actor = actorOf(new Dispatcher(transactionRequired, restartCallbacks))
actor.dispatcher = dispatcher
@ -374,7 +374,7 @@ object ActiveObject {
this
}
private[akka] def supervise(restartStrategy: RestartStrategy, components: List[Supervise]): Supervisor =
private[akka] def supervise(restartStrategy: RestartStrategy, components: List[Supervise]): Supervisor =
Supervisor(SupervisorConfig(restartStrategy, components))
}
@ -556,12 +556,12 @@ private[akka] class Dispatcher(transactionalRequired: Boolean, val callbacks: Op
preRestart = Some(try {
targetInstance.getClass.getDeclaredMethod(pre, ZERO_ITEM_CLASS_ARRAY: _*)
} catch { case e => throw new IllegalStateException(
"Could not find pre restart method [" + pre + "] \nin [" +
"Could not find pre restart method [" + pre + "] \nin [" +
targetClass.getName + "]. \nIt must have a zero argument definition.") })
postRestart = Some(try {
targetInstance.getClass.getDeclaredMethod(post, ZERO_ITEM_CLASS_ARRAY: _*)
} catch { case e => throw new IllegalStateException(
"Could not find post restart method [" + post + "] \nin [" +
"Could not find post restart method [" + post + "] \nin [" +
targetClass.getName + "]. \nIt must have a zero argument definition.") })
}
@ -571,11 +571,11 @@ private[akka] class Dispatcher(transactionalRequired: Boolean, val callbacks: Op
if (preRestart.isDefined && preRestart.get.getParameterTypes.length != 0)
throw new IllegalStateException(
"Method annotated with @prerestart or defined as a restart callback in \n[" +
"Method annotated with @prerestart or defined as a restart callback in \n[" +
targetClass.getName + "] must have a zero argument definition")
if (postRestart.isDefined && postRestart.get.getParameterTypes.length != 0)
throw new IllegalStateException(
"Method annotated with @postrestart or defined as a restart callback in \n[" +
"Method annotated with @postrestart or defined as a restart callback in \n[" +
targetClass.getName + "] must have a zero argument definition")
if (preRestart.isDefined) preRestart.get.setAccessible(true)
@ -583,7 +583,7 @@ private[akka] class Dispatcher(transactionalRequired: Boolean, val callbacks: Op
// see if we have a method annotated with @inittransactionalstate, if so invoke it
initTxState = methods.find(m => m.isAnnotationPresent(Annotations.inittransactionalstate))
if (initTxState.isDefined && initTxState.get.getParameterTypes.length != 0)
if (initTxState.isDefined && initTxState.get.getParameterTypes.length != 0)
throw new IllegalStateException("Method annotated with @inittransactionalstate must have a zero argument definition")
if (initTxState.isDefined) initTxState.get.setAccessible(true)
}

View file

@ -20,7 +20,7 @@ trait ActorWithNestedReceive extends Actor {
processors.head forward message
nestedReactsProcessors = processors.tail.reverse
}
protected def react: Receive
protected def reactAgain(pf: Receive) = nestedReactsProcessors ::= actor(pf)
protected def receive = processNestedReacts orElse react
@ -98,8 +98,8 @@ object Actor extends Logging {
def actorOf[T <: Actor: Manifest]: ActorRef = new LocalActorRef(manifest[T].erasure.asInstanceOf[Class[_ <: Actor]])
/**
* Creates a Actor.actorOf out of the Actor. Allows you to pass in a factory function
* that creates the Actor. Please note that this function can be invoked multiple
* Creates a Actor.actorOf out of the Actor. Allows you to pass in a factory function
* that creates the Actor. Please note that this function can be invoked multiple
* times if for example the Actor is supervised and needs to be restarted.
* <p/>
* This function should <b>NOT</b> be used for remote actors.
@ -251,7 +251,7 @@ object Actor extends Logging {
*
* <p/>
* The Actor's API is available in the 'self' member variable.
*
*
* <p/>
* Here you find functions like:
* - !, !!, !!! and forward
@ -268,12 +268,12 @@ object Actor extends Logging {
* - faultHandler = ...
* - trapExit = ...
* - etc.
*
*
* <p/>
* This means that to use them you have to prefix them with 'self', like this: <tt>self ! Message</tt>
*
* However, for convenience you can import these functions and fields like below, which will allow you do
* drop the 'self' prefix:
* drop the 'self' prefix:
* <pre>
* class MyActor extends Actor {
* import self._
@ -283,7 +283,7 @@ object Actor extends Logging {
* ...
* }
* </pre>
*
*
* <p/>
* The Actor trait also has a 'log' member field that can be used for logging within the Actor.
*
@ -295,20 +295,20 @@ trait Actor extends Logging {
*/
type Receive = Actor.Receive
/*
* For internal use only, functions as the implicit sender references when invoking
/*
* For internal use only, functions as the implicit sender references when invoking
* one of the message send functions (!, !! and !!!).
*/
implicit val optionSelf: Option[ActorRef] = {
val ref = Actor.actorRefInCreation.value
Actor.actorRefInCreation.value = None
if (ref.isEmpty) throw new ActorInitializationException(
"ActorRef for instance of actor [" + getClass.getName + "] is not in scope." +
"\n\tYou can not create an instance of an actor explicitly using 'new MyActor'." +
"\n\tYou have to use one of the factory methods in the 'Actor' object to create a new actor." +
"\n\tEither use:" +
"\n\t\t'val actor = Actor.actorOf[MyActor]', or" +
"\n\t\t'val actor = Actor.actorOf(new MyActor(..))'" +
"ActorRef for instance of actor [" + getClass.getName + "] is not in scope." +
"\n\tYou can not create an instance of an actor explicitly using 'new MyActor'." +
"\n\tYou have to use one of the factory methods in the 'Actor' object to create a new actor." +
"\n\tEither use:" +
"\n\t\t'val actor = Actor.actorOf[MyActor]', or" +
"\n\t\t'val actor = Actor.actorOf(new MyActor(..))'" +
"\n\t\t'val actor = Actor.actor { case msg => .. } }'")
else ref
}
@ -329,7 +329,7 @@ trait Actor extends Logging {
*/
val self: ActorRef = optionSelf.get
self.id = getClass.getName
/**
* User overridable callback/setting.
* <p/>
@ -408,7 +408,7 @@ trait Actor extends Logging {
case UnlinkAndStop(child) => self.unlink(child); child.stop
case Kill => throw new ActorKilledException("Actor [" + toString + "] was killed by a Kill message")
}
override def hashCode: Int = self.hashCode
override def equals(that: Any): Boolean = self.equals(that)
@ -418,14 +418,14 @@ trait Actor extends Logging {
/**
* Base class for the different dispatcher types.
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
sealed abstract class DispatcherType
/**
* Module that holds the different dispatcher types.
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
object DispatcherType {

View file

@ -50,7 +50,7 @@ object ActorRef {
/**
* Deserializes the ActorRef instance from a byte array (Array[Byte]) into an ActorRef instance.
*/
def fromBinary(bytes: Array[Byte]): ActorRef =
def fromBinary(bytes: Array[Byte]): ActorRef =
fromProtocol(ActorRefProtocol.newBuilder.mergeFrom(bytes).build)
/**
@ -73,32 +73,32 @@ object ActorRef {
* Here is an example on how to create an actor with a default constructor.
* <pre>
* import Actor._
*
*
* val actor = actorOf[MyActor]
* actor.start
* actor ! message
* actor.stop
* </pre>
*
* You can also create and start actors like this:
*
* You can also create and start actors like this:
* <pre>
* val actor = actorOf[MyActor].start
* </pre>
*
*
* Here is an example on how to create an actor with a non-default constructor.
* <pre>
* import Actor._
*
*
* val actor = actorOf(new MyActor(...))
* actor.start
* actor ! message
* actor.stop
* </pre>
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
trait ActorRef extends TransactionManagement {
// Only mutable for RemoteServer in order to maintain identity across nodes
@volatile protected[akka] var _uuid = UUID.newUuid.toString
@volatile protected[this] var _isRunning = false
@ -211,14 +211,14 @@ trait ActorRef extends TransactionManagement {
// protected[this] var _replyTo: Option[Either[ActorRef, CompletableFuture[Any]]] = None
// protected[akka] def replyTo: Option[Either[ActorRef, CompletableFuture[Any]]] = guard.withGuard { _replyTo }
// protected[akka] def replyTo_=(rt: Option[Either[ActorRef, CompletableFuture[Any]]]) = guard.withGuard { _replyTo = rt }
protected[akka] var _sender: Option[ActorRef] = None
protected[akka] var _senderFuture: Option[CompletableFuture[Any]] = None
protected[akka] def sender: Option[ActorRef] = guard.withGuard { _sender }
protected[akka] def senderFuture: Option[CompletableFuture[Any]] = guard.withGuard { _senderFuture }
protected[akka] def sender_=(s: Option[ActorRef]) = guard.withGuard { _sender = s}
protected[akka] def senderFuture_=(sf: Option[CompletableFuture[Any]]) = guard.withGuard { _senderFuture = sf}
/**
* Is the actor being restarted?
*/
@ -240,7 +240,7 @@ trait ActorRef extends TransactionManagement {
def uuid = _uuid
/**
* Only for internal use. UUID is effectively final.
* Only for internal use. UUID is effectively final.
*/
protected[akka] def uuid_=(uid: String) = _uuid = uid
@ -340,7 +340,7 @@ trait ActorRef extends TransactionManagement {
else throw new IllegalStateException("Can't forward message when initial sender is not an actor")
} else throw new ActorInitializationException("Actor has not been started, you need to invoke 'actor.start' before using it")
}
/**
* Use <code>self.reply(..)</code> to reply with a message to the original sender of the message currently
* being processed.
@ -377,12 +377,12 @@ trait ActorRef extends TransactionManagement {
* Serializes the ActorRef instance into a byte array (Array[Byte]).
*/
def toBinary: Array[Byte]
/**
* Returns the class for the Actor instance that is managed by the ActorRef.
*/
def actorClass: Class[_ <: Actor]
/**
* Sets the dispatcher for this actor. Needs to be invoked before the actor is started.
*/
@ -397,12 +397,12 @@ trait ActorRef extends TransactionManagement {
* Invoking 'makeRemote' means that an actor will be moved to and invoked on a remote host.
*/
def makeRemote(hostname: String, port: Int): Unit
/**
* Invoking 'makeRemote' means that an actor will be moved to and invoked on a remote host.
*/
def makeRemote(address: InetSocketAddress): Unit
/**
* Invoking 'makeTransactionRequired' means that the actor will **start** a new transaction if non exists.
* However, it will always participate in an existing transaction.
@ -412,7 +412,7 @@ trait ActorRef extends TransactionManagement {
* </pre>
*/
def makeTransactionRequired: Unit
/**
* Returns the home address and port for this actor.
*/
@ -421,7 +421,7 @@ trait ActorRef extends TransactionManagement {
/**
* Set the home address and port for this actor.
*/
def homeAddress_=(hostnameAndPort: Tuple2[String, Int]): Unit =
def homeAddress_=(hostnameAndPort: Tuple2[String, Int]): Unit =
homeAddress_=(new InetSocketAddress(hostnameAndPort._1, hostnameAndPort._2))
/**
@ -469,7 +469,7 @@ trait ActorRef extends TransactionManagement {
* To be invoked from within the actor itself.
*/
def unlink(actorRef: ActorRef): Unit
/**
* Atomically start and link an actor.
* <p/>
@ -511,12 +511,12 @@ trait ActorRef extends TransactionManagement {
* To be invoked from within the actor itself.
*/
def spawnLinkRemote[T <: Actor : Manifest](hostname: String, port: Int): ActorRef
/**
* Returns the mailbox size.
*/
def mailboxSize: Int
/**
* Returns the supervisor, if there is one.
*/
@ -540,7 +540,7 @@ trait ActorRef extends TransactionManagement {
senderFuture: Option[CompletableFuture[T]]): CompletableFuture[T]
protected[this] def actorInstance: AtomicReference[Actor]
protected[akka] def actor: Actor = actorInstance.get
protected[akka] def supervisor_=(sup: Option[ActorRef]): Unit
@ -557,7 +557,7 @@ trait ActorRef extends TransactionManagement {
protected[akka] def linkedActors: JMap[String, ActorRef]
protected[akka] def linkedActorsAsList: List[ActorRef]
protected[akka] def linkedActorsAsList: List[ActorRef]
override def hashCode: Int = HashCode.hash(HashCode.SEED, uuid)
@ -571,12 +571,7 @@ trait ActorRef extends TransactionManagement {
protected def processSender(senderOption: Option[ActorRef], requestBuilder: RemoteRequestProtocol.Builder) = {
senderOption.foreach { sender =>
val address = sender.homeAddress
val server = RemoteServer.serverFor(address) match {
case Some(server) => server
case None => (new RemoteServer).start(address)
}
server.register(sender.uuid, sender)
RemoteServer.getOrCreateServer(sender.homeAddress).register(sender.uuid, sender)
requestBuilder.setSender(sender.toProtocol)
}
}
@ -584,21 +579,21 @@ trait ActorRef extends TransactionManagement {
/**
* Local ActorRef that is used when referencing the Actor on its "home" node.
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
sealed class LocalActorRef private[akka](
private[this] var actorFactory: Either[Option[Class[_ <: Actor]], Option[() => Actor]] = Left(None))
extends ActorRef {
private[akka] def this(clazz: Class[_ <: Actor]) = this(Left(Some(clazz)))
private[akka] def this(clazz: Class[_ <: Actor]) = this(Left(Some(clazz)))
private[akka] def this(factory: () => Actor) = this(Right(Some(factory)))
// Only mutable for RemoteServer in order to maintain identity across nodes
@volatile private[akka] var _remoteAddress: Option[InetSocketAddress] = None
@volatile private[akka] var _linkedActors: Option[ConcurrentHashMap[String, ActorRef]] = None
@volatile private[akka] var _supervisor: Option[ActorRef] = None
protected[akka] val _mailbox: Deque[MessageInvocation] = new ConcurrentLinkedDeque[MessageInvocation]
protected[this] val actorInstance = new AtomicReference[Actor](newActor)
@ -610,7 +605,7 @@ sealed class LocalActorRef private[akka](
private val actorSelfFields = findActorSelfField(actor.getClass)
if (runActorInitialization) initializeActorInstance
/**
* Serializes the ActorRef instance into a Protocol Buffers (protobuf) Message.
*/
@ -618,13 +613,13 @@ sealed class LocalActorRef private[akka](
val host = homeAddress.getHostName
val port = homeAddress.getPort
if (!registeredInRemoteNodeDuringSerialization) {
if (!registeredInRemoteNodeDuringSerialization) {
Actor.log.debug("Register serialized Actor [%s] as remote @ [%s:%s]", actorClass.getName, host, port)
if (RemoteServer.serverFor(host, port).isEmpty) (new RemoteServer).start(host, port)
RemoteServer.actorsFor(RemoteServer.Address(host, port)).actors.put(uuid, this)
RemoteServer.getOrCreateServer(homeAddress)
RemoteServer.registerActor(homeAddress, uuid, this)
registeredInRemoteNodeDuringSerialization = true
}
ActorRefProtocol.newBuilder
.setUuid(uuid)
.setActorClassName(actorClass.getName)
@ -636,19 +631,19 @@ sealed class LocalActorRef private[akka](
/**
* Returns the mailbox.
*/
*/
protected[akka] def mailbox: Deque[MessageInvocation] = _mailbox
/**
* Serializes the ActorRef instance into a byte array (Array[Byte]).
*/
def toBinary: Array[Byte] = toProtocol.toByteArray
/**
* Returns the class for the Actor instance that is managed by the ActorRef.
*/
def actorClass: Class[_ <: Actor] = actor.getClass.asInstanceOf[Class[_ <: Actor]]
/**
* Sets the dispatcher for this actor. Needs to be invoked before the actor is started.
*/
@ -698,7 +693,7 @@ sealed class LocalActorRef private[akka](
}
/**
* Set the contact address for this actor. This is used for replying to messages
* Set the contact address for this actor. This is used for replying to messages
* sent asynchronously when no reply channel exists.
*/
def homeAddress_=(address: InetSocketAddress): Unit = guard.withGuard { _homeAddress = address }
@ -857,7 +852,7 @@ sealed class LocalActorRef private[akka](
* Returns the mailbox size.
*/
def mailboxSize: Int = _mailbox.size
/**
* Shuts down and removes all linked actors.
*/
@ -870,7 +865,7 @@ sealed class LocalActorRef private[akka](
* Returns the supervisor, if there is one.
*/
def supervisor: Option[ActorRef] = guard.withGuard { _supervisor }
protected[akka] def supervisor_=(sup: Option[ActorRef]): Unit = guard.withGuard { _supervisor = sup }
private def spawnButDoNotStart[T <: Actor: Manifest]: ActorRef = guard.withGuard {
@ -883,19 +878,19 @@ sealed class LocalActorRef private[akka](
isInInitialization = true
Actor.actorRefInCreation.value = Some(this)
val actor = actorFactory match {
case Left(Some(clazz)) =>
try {
clazz.newInstance
} catch {
case Left(Some(clazz)) =>
try {
clazz.newInstance
} catch {
case e: InstantiationException => throw new ActorInitializationException(
"Could not instantiate Actor due to:\n" + e +
"\nMake sure Actor is NOT defined inside a class/trait," +
"Could not instantiate Actor due to:\n" + e +
"\nMake sure Actor is NOT defined inside a class/trait," +
"\nif so put it outside the class/trait, f.e. in a companion object," +
"\nOR try to change: 'actorOf[MyActor]' to 'actorOf(new MyActor)'.")
"\nOR try to change: 'actorOf[MyActor]' to 'actorOf(new MyActor)'.")
}
case Right(Some(factory)) =>
case Right(Some(factory)) =>
factory()
case _ =>
case _ =>
throw new ActorInitializationException(
"Can't create Actor, no Actor class or factory function in scope")
}
@ -904,7 +899,7 @@ sealed class LocalActorRef private[akka](
isInInitialization = false
actor
}
protected[akka] def postMessageToMailbox(message: Any, senderOption: Option[ActorRef]): Unit = {
sender = senderOption
joinTransaction(message)
@ -951,13 +946,13 @@ sealed class LocalActorRef private[akka](
.setIsActor(true)
.setIsOneWay(false)
.setIsEscaped(false)
//senderOption.foreach(sender => requestBuilder.setSender(sender.toProtocol))
RemoteProtocolBuilder.setMessage(message, requestBuilder)
val id = registerSupervisorAsRemoteActor
if (id.isDefined) requestBuilder.setSupervisorUuid(id.get)
val future = RemoteClient.clientFor(remoteAddress.get).send(requestBuilder.build, senderFuture)
if (future.isDefined) future.get
else throw new IllegalStateException("Expected a future from remote call to actor " + toString)
@ -1078,7 +1073,7 @@ sealed class LocalActorRef private[akka](
// FIXME: implement support for maxNrOfRetries and withinTimeRange in RestartStrategy
case AllForOneStrategy(maxNrOfRetries, withinTimeRange) =>
restartLinkedActors(reason)
case OneForOneStrategy(maxNrOfRetries, withinTimeRange) =>
dead.restart(reason)
}
@ -1128,7 +1123,7 @@ sealed class LocalActorRef private[akka](
if (linkedActors.isEmpty) {
Actor.log.info(
"All linked actors have died permanently (they were all configured as TEMPORARY)" +
"\n\tshutting down and unlinking supervisor actor as well [%s].",
"\n\tshutting down and unlinking supervisor actor as well [%s].",
actorRef.id)
_supervisor.foreach(_ ! UnlinkAndStop(this))
}
@ -1153,7 +1148,7 @@ sealed class LocalActorRef private[akka](
} else _linkedActors.get
}
protected[akka] def linkedActorsAsList: List[ActorRef] =
protected[akka] def linkedActorsAsList: List[ActorRef] =
linkedActors.values.toArray.toList.asInstanceOf[List[ActorRef]]
private def nullOutActorRefReferencesFor(actor: Actor) = {
@ -1215,17 +1210,17 @@ sealed class LocalActorRef private[akka](
/**
* Remote ActorRef that is used when referencing the Actor on a different node than its "home" node.
* This reference is network-aware (remembers its origin) and immutable.
* This reference is network-aware (remembers its origin) and immutable.
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
private[akka] case class RemoteActorRef private[akka] (
// uuid: String, className: String, hostname: String, port: Int, timeOut: Long, isOnRemoteHost: Boolean) extends ActorRef {
uuuid: String, val className: String, val hostname: String, val port: Int, _timeout: Long)
uuuid: String, val className: String, val hostname: String, val port: Int, _timeout: Long)
extends ActorRef {
_uuid = uuuid
_uuid = uuuid
timeout = _timeout
start
lazy val remoteClient = RemoteClient.clientFor(hostname, port)
@ -1271,7 +1266,7 @@ private[akka] case class RemoteActorRef private[akka] (
_isRunning = false
_isShutDown = true
}
// ==== NOT SUPPORTED ====
def toBinary: Array[Byte] = unsupported
def actorClass: Class[_ <: Actor] = unsupported

View file

@ -160,4 +160,4 @@ object ActorRegistry extends Logging {
else log.warning("Can't send ActorRegistryEvent to [%s] since it is not running.", listener)
}
}
}
}

View file

@ -3,47 +3,47 @@
*/
package se.scalablesolutions.akka.actor
import se.scalablesolutions.akka.stm.Ref
import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.CountDownLatch
class AgentException private[akka](message: String) extends RuntimeException(message)
/**
* The Agent class was strongly inspired by the agent principle in Clojure.
* <p/>
* <p/>
*
* Agents provide independent, asynchronous change of individual locations.
* Agents are bound to a single storage location for their lifetime, and
* only allow mutation of that location (to a new state) to occur as a
* result of an action. Actions are functions (with, optionally, additional
* arguments) that are asynchronously applied to an Agent's state and whose
* return value becomes the Agent's new state. Because the set of functions
* is open, the set of actions supported by an Agent is also open, a sharp
* Agents provide independent, asynchronous change of individual locations.
* Agents are bound to a single storage location for their lifetime, and
* only allow mutation of that location (to a new state) to occur as a
* result of an action. Actions are functions (with, optionally, additional
* arguments) that are asynchronously applied to an Agent's state and whose
* return value becomes the Agent's new state. Because the set of functions
* is open, the set of actions supported by an Agent is also open, a sharp
* contrast to pattern matching message handling loops provided by Actors.
* <p/>
*
* Agents are reactive, not autonomous - there is no imperative message loop
* and no blocking receive. The state of an Agent should be itself immutable
* (preferably an instance of one of Akka's persistent collections), and the
* state of an Agent is always immediately available for reading by any
* thread (using the '()' function) without any messages, i.e. observation
* <p/>
*
* Agents are reactive, not autonomous - there is no imperative message loop
* and no blocking receive. The state of an Agent should be itself immutable
* (preferably an instance of one of Akka's persistent collections), and the
* state of an Agent is always immediately available for reading by any
* thread (using the '()' function) without any messages, i.e. observation
* does not require cooperation or coordination.
* <p/>
* <p/>
*
* The actions of all Agents get interleaved amongst threads in a thread pool.
* At any point in time, at most one action for each Agent is being executed.
* Actions dispatched to an agent from another single agent or thread will
* occur in the order they were sent, potentially interleaved with actions
* The actions of all Agents get interleaved amongst threads in a thread pool.
* At any point in time, at most one action for each Agent is being executed.
* Actions dispatched to an agent from another single agent or thread will
* occur in the order they were sent, potentially interleaved with actions
* dispatched to the same agent from other sources.
* <p/>
* <p/>
*
* If an Agent is used within an enclosing transaction, then it will
* participate in that transaction.
* <p/>
*
* If an Agent is used within an enclosing transaction, then it will
* participate in that transaction.
* <p/>
*
* Example of usage:
* <pre>
* val agent = Agent(5)
@ -56,65 +56,65 @@ class AgentException private[akka](message: String) extends RuntimeException(mes
*
* agent.close
* </pre>
* <p/>
*
* Agent is also monadic, which means that you can compose operations using
* <p/>
*
* Agent is also monadic, which means that you can compose operations using
* for-comprehensions. In monadic usage the original agents are not touched
* but new agents are created. So the old values (agents) are still available
* as-is. They are so-called 'persistent'.
* <p/>
*
* <p/>
*
* Example of monadic usage:
* <pre>
* val agent1 = Agent(3)
* val agent2 = Agent(5)
*
* for (value <- agent1) {
* result = value + 1
* result = value + 1
* }
*
* val agent3 =
* for (value <- agent1) yield value + 1
*
*
* val agent3 =
* for (value <- agent1) yield value + 1
*
* val agent4 = for {
* value1 <- agent1
* value2 <- agent2
* } yield value1 + value2
* } yield value1 + value2
*
* agent1.close
* agent2.close
* agent3.close
* agent4.close
* </pre>
* <p/>
*
* IMPORTANT:
* You can *not* call 'agent.get', 'agent()' or use the monadic 'foreach',
* 'map' and 'flatMap' within an enclosing transaction since that would block
* the transaction indefinitely. But all other operations are fine. The system
* will raise an error (e.g. *not* deadlock) if you try to do so, so as long as
* <p/>
*
* IMPORTANT:
* You can *not* call 'agent.get', 'agent()' or use the monadic 'foreach',
* 'map' and 'flatMap' within an enclosing transaction since that would block
* the transaction indefinitely. But all other operations are fine. The system
* will raise an error (e.g. *not* deadlock) if you try to do so, so as long as
* you test your application thoroughly you should be fine.
*
*
* @author Viktor Klang
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
sealed class Agent[T] private (initialValue: T) {
import Agent._
import Actor._
private val dispatcher = actorOf(new AgentDispatcher[T](initialValue)).start
dispatcher ! Value(initialValue)
/**
* Submits a request to read the internal state.
*
* A copy of the internal state will be returned, depending on the underlying
* effective copyStrategy. Internally leverages the asynchronous getValue()
*
* A copy of the internal state will be returned, depending on the underlying
* effective copyStrategy. Internally leverages the asynchronous getValue()
* method and then waits for its result on a CountDownLatch.
*/
final def get: T = {
if (dispatcher.isTransactionInScope) throw new AgentException(
"Can't call Agent.get within an enclosing transaction."+
"Can't call Agent.get within an enclosing transaction."+
"\n\tWould block indefinitely.\n\tPlease refactor your code.")
val ref = new AtomicReference[T]
val latch = new CountDownLatch(1)
@ -122,10 +122,10 @@ sealed class Agent[T] private (initialValue: T) {
latch.await
ref.get
}
/**
* Submits a request to read the internal state. A copy of the internal state will be
* returned, depending on the underlying effective copyStrategy. Internally leverages
* Submits a request to read the internal state. A copy of the internal state will be
* returned, depending on the underlying effective copyStrategy. Internally leverages
* the asynchronous getValue() method and then waits for its result on a CountDownLatch.
*/
final def apply(): T = get
@ -134,25 +134,25 @@ sealed class Agent[T] private (initialValue: T) {
* Submits the provided function for execution against the internal agent's state.
*/
final def apply(message: (T => T)): Unit = dispatcher ! Function(message)
/**
* Submits a new value to be set as the new agent's internal state.
*/
final def apply(message: T): Unit = dispatcher ! Value(message)
/**
* Submits the provided function of type 'T => T' for execution against the internal agent's state.
*/
final def send(message: (T) => T): Unit = dispatcher ! Function(message)
/**
* Submits a new value to be set as the new agent's internal state.
*/
final def send(message: T): Unit = dispatcher ! Value(message)
/**
* Asynchronously submits a procedure of type 'T => Unit' to read the internal state.
* The supplied procedure will be executed on the returned internal state value. A copy
* Asynchronously submits a procedure of type 'T => Unit' to read the internal state.
* The supplied procedure will be executed on the returned internal state value. A copy
* of the internal state will be used, depending on the underlying effective copyStrategy.
* Does not change the value of the agent (this).
*/
@ -174,23 +174,23 @@ sealed class Agent[T] private (initialValue: T) {
* Applies function with type 'T => B' to the agent's internal state.
* Does not change the value of the agent (this).
*/
final def foreach(f: (T) => Unit): Unit = f(get)
final def foreach(f: (T) => Unit): Unit = f(get)
/**
* Closes the agents and makes it eligable for garbage collection.
*
*
* A closed agent can never be used again.
*/
def close = dispatcher.stop
}
/**
* Provides factory methods to create Agents.
*
* @author Viktor Klang
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
object Agent {
object Agent {
/*
* The internal messages for passing around requests.
@ -198,7 +198,7 @@ object Agent {
private[akka] case class Value[T](value: T)
private[akka] case class Function[T](fun: ((T) => T))
private[akka] case class Procedure[T](fun: ((T) => Unit))
/**
* Creates a new Agent of type T with the initial value of value.
*/
@ -214,9 +214,9 @@ final class AgentDispatcher[T] private[akka] (initialValue: T) extends Transacto
import Agent._
import Actor._
log.debug("Starting up Agent [%s]", self.uuid)
private lazy val value = Ref[T]()
/**
* Periodically handles incoming messages.
*/
@ -228,11 +228,11 @@ final class AgentDispatcher[T] private[akka] (initialValue: T) extends Transacto
case Procedure(proc: (T => Unit)) =>
proc(value.getOrElse(throw new AgentException("Could not read Agent's value; value is null")))
}
/**
* Performs a CAS operation, atomically swapping the internal state with the value
* Performs a CAS operation, atomically swapping the internal state with the value
* provided as a by-name parameter.
*/
private final def swap(newData: => T): Unit = value.swap(newData)
}

View file

@ -29,21 +29,28 @@ trait BootableActorLoaderService extends Bootable with Logging {
log.error("Could not find a deploy directory at [%s]", DEPLOY)
System.exit(-1)
}
val filesToDeploy = DEPLOY_DIR.listFiles.toArray.toList.asInstanceOf[List[File]].filter(_.getName.endsWith(".jar"))
val filesToDeploy = DEPLOY_DIR.listFiles.toArray.toList
.asInstanceOf[List[File]].filter(_.getName.endsWith(".jar"))
var dependencyJars: List[URL] = Nil
filesToDeploy.map { file =>
val jarFile = new JarFile(file)
val en = jarFile.entries
while (en.hasMoreElements) {
val name = en.nextElement.getName
if (name.endsWith(".jar")) dependencyJars ::= new File(String.format("jar:file:%s!/%s", jarFile.getName, name)).toURI.toURL
if (name.endsWith(".jar")) dependencyJars ::= new File(
String.format("jar:file:%s!/%s", jarFile.getName, name)).toURI.toURL
}
}
val toDeploy = filesToDeploy.map(_.toURI.toURL)
log.info("Deploying applications from [%s]: [%s]", DEPLOY, toDeploy)
log.debug("Loading dependencies [%s]", dependencyJars)
val allJars = toDeploy ::: dependencyJars
new URLClassLoader(allJars.toArray.asInstanceOf[Array[URL]] , getClass.getClassLoader)
val parentClassLoader = classOf[Seq[_]].getClassLoader
URLClassLoader.newInstance(
allJars.toArray.asInstanceOf[Array[URL]],
ClassLoader.getSystemClassLoader)
//parentClassLoader)
} else getClass.getClassLoader)
}

View file

@ -9,8 +9,10 @@
* 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.
*
* Rework of David Pollak's ActorPing class in the Lift Project
* which is licensed under the Apache 2 License.
*/
package se.scalablesolutions.akka.actor
import java.util.concurrent._
@ -19,59 +21,50 @@ import se.scalablesolutions.akka.config.ScalaConfig._
import se.scalablesolutions.akka.config.{AllForOneStrategy, OneForOneStrategy, FaultHandlingStrategy}
import se.scalablesolutions.akka.util.Logging
case object UnSchedule
case class SchedulerException(msg: String, e: Throwable) extends RuntimeException(msg, e)
/**
* Rework of David Pollak's ActorPing class in the Lift Project
* which is licensed under the Apache 2 License.
*/
class ScheduleActor(val receiver: ActorRef, val future: ScheduledFuture[AnyRef]) extends Actor with Logging {
self.lifeCycle = Some(LifeCycle(Permanent))
def receive = {
case UnSchedule =>
Scheduler.stopSupervising(self)
future.cancel(true)
exit
}
}
object Scheduler extends Actor {
object Scheduler {
import Actor._
case object UnSchedule
case class SchedulerException(msg: String, e: Throwable) extends RuntimeException(msg, e)
private var service = Executors.newSingleThreadScheduledExecutor(SchedulerThreadFactory)
private val schedulers = new ConcurrentHashMap[ActorRef, ActorRef]
self.faultHandler = Some(OneForOneStrategy(5, 5000))
self.trapExit = List(classOf[Throwable])
def schedule(receiver: ActorRef, message: AnyRef, initialDelay: Long, delay: Long, timeUnit: TimeUnit) = {
try {
self.startLink(actorOf(new ScheduleActor(
receiver,
service.scheduleAtFixedRate(new java.lang.Runnable {
def run = receiver ! message;
}, initialDelay, delay, timeUnit).asInstanceOf[ScheduledFuture[AnyRef]])))
val future = service.scheduleAtFixedRate(
new Runnable { def run = receiver ! message },
initialDelay, delay, timeUnit).asInstanceOf[ScheduledFuture[AnyRef]]
val scheduler = actorOf(new ScheduleActor(future)).start
schedulers.put(scheduler, scheduler)
} catch {
case e => throw SchedulerException(message + " could not be scheduled on " + receiver, e)
}
}
def restart = service = Executors.newSingleThreadScheduledExecutor(SchedulerThreadFactory)
def stopSupervising(actorRef: ActorRef) = {
self.unlink(actorRef)
def unschedule(actorRef: ActorRef) = {
actorRef ! UnSchedule
schedulers.remove(actorRef)
}
override def shutdown = {
def shutdown = {
import scala.collection.JavaConversions._
schedulers.values.foreach(_ ! UnSchedule)
schedulers.clear
service.shutdown
}
def restart = {
shutdown
service = Executors.newSingleThreadScheduledExecutor(SchedulerThreadFactory)
}
}
private class ScheduleActor(future: ScheduledFuture[AnyRef]) extends Actor with Logging {
def receive = {
case _ => {} // ignore all messages
case Scheduler.UnSchedule =>
future.cancel(true)
exit
}
}

View file

@ -11,6 +11,7 @@ import se.scalablesolutions.akka.remote.RemoteServer
import Actor._
import java.util.concurrent.{CopyOnWriteArrayList, ConcurrentHashMap}
import java.net.InetSocketAddress
class SupervisorException private[akka](message: String) extends RuntimeException(message)
@ -19,7 +20,7 @@ class SupervisorException private[akka](message: String) extends RuntimeExceptio
* These are not actors, if you need a supervisor that is an Actor then you have to use the 'SupervisorActor'
* factory object.
* <p/>
*
*
* Here is a sample on how to use it:
* <pre>
* val supervisor = Supervisor(
@ -49,7 +50,7 @@ object Supervisor {
/**
* Factory object for creating supervisors as Actors, it has both a declarative and programatic API.
* <p/>
*
*
* Here is a sample on how to use the programmatic API (note that the supervisor is automatically started):
* <pre>
* val supervisor = SupervisorActor(AllForOneStrategy(maxNrOfRetries, timeRange), Array(classOf[Throwable]))
@ -67,22 +68,22 @@ object Supervisor {
* LifeCycle(Permanent)) ::
* Nil))
* </pre>
*
*
* You dynamically link and unlink child children using the 'link' and 'unlink' methods.
* <pre>
* supervisor.link(child)
* supervisor.unlink(child)
* </pre>
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
object SupervisorActor {
def apply(config: SupervisorConfig): ActorRef = {
def apply(config: SupervisorConfig): ActorRef = {
val (handler, trapExits) = SupervisorFactory.retrieveFaultHandlerAndTrapExitsFrom(config)
actorOf(new SupervisorActor(handler, trapExits)).start
}
def apply(handler: FaultHandlingStrategy, trapExceptions: List[Class[_ <: Throwable]]): ActorRef =
def apply(handler: FaultHandlingStrategy, trapExceptions: List[Class[_ <: Throwable]]): ActorRef =
actorOf(new SupervisorActor(handler, trapExceptions)).start
}
@ -116,9 +117,9 @@ object SupervisorActor {
*/
object SupervisorFactory {
def apply(config: SupervisorConfig) = new SupervisorFactory(config)
private[akka] def retrieveFaultHandlerAndTrapExitsFrom(config: SupervisorConfig):
Tuple2[FaultHandlingStrategy, List[Class[_ <: Throwable]]] = config match {
private[akka] def retrieveFaultHandlerAndTrapExitsFrom(config: SupervisorConfig):
Tuple2[FaultHandlingStrategy, List[Class[_ <: Throwable]]] = config match {
case SupervisorConfig(RestartStrategy(scheme, maxNrOfRetries, timeRange, trapExceptions), _) =>
scheme match {
case AllForOne => (AllForOneStrategy(maxNrOfRetries, timeRange), trapExceptions)
@ -128,8 +129,8 @@ object SupervisorFactory {
}
/**
* For internal use only.
*
* For internal use only.
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
class SupervisorFactory private[akka] (val config: SupervisorConfig) extends Logging {
@ -148,32 +149,32 @@ class SupervisorFactory private[akka] (val config: SupervisorConfig) extends Log
/**
* <b>NOTE:</b>
* <p/>
* <p/>
* The supervisor class is only used for the configuration system when configuring supervisor
* hierarchies declaratively. Should not be used as part of the regular programming API. Instead
* wire the children together using 'link', 'spawnLink' etc. and set the 'trapExit' flag in the
* children that should trap error signals and trigger restart.
* <p/>
* <p/>
* See the ScalaDoc for the SupervisorFactory for an example on how to declaratively wire up children.
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
*/
sealed class Supervisor private[akka] (
handler: FaultHandlingStrategy, trapExceptions: List[Class[_ <: Throwable]])
extends Configurator {
import Supervisor._
private val childActors = new ConcurrentHashMap[String, List[ActorRef]]
private val childSupervisors = new CopyOnWriteArrayList[Supervisor]
private val childSupervisors = new CopyOnWriteArrayList[Supervisor]
private[akka] val supervisor = SupervisorActor(handler, trapExceptions)
def uuid = supervisor.uuid
def start: Supervisor = {
def start: Supervisor = {
ConfiguratorRepository.registerConfigurator(this)
this
}
def shutdown: Unit = supervisor.stop
def link(child: ActorRef) = supervisor.link(child)
@ -186,7 +187,7 @@ sealed class Supervisor private[akka] (
// FIXME recursive search + do not fix if we remove feature that Actors can be RESTful usin Jersey annotations
def getComponentInterfaces: List[Class[_]] =
childActors.values.toArray.toList.asInstanceOf[List[List[AnyRef]]].flatten.map(_.getClass)
// FIXME recursive search + do not fix if we remove feature that Actors can be RESTful usin Jersey annotations
def isDefined(clazz: Class[_]): Boolean = childActors.containsKey(clazz.getName)
@ -196,7 +197,7 @@ sealed class Supervisor private[akka] (
server match {
case Supervise(actorRef, lifeCycle, remoteAddress) =>
val className = actorRef.actor.getClass.getName
val currentActors = {
val currentActors = {
val list = childActors.get(className)
if (list eq null) List[ActorRef]()
else list
@ -204,11 +205,8 @@ sealed class Supervisor private[akka] (
childActors.put(className, actorRef :: currentActors)
actorRef.lifeCycle = Some(lifeCycle)
supervisor.link(actorRef)
remoteAddress.foreach { address => RemoteServer
.actorsFor(RemoteServer.Address(address.hostname, address.port))
.actors.put(actorRef.id, actorRef)
}
remoteAddress.foreach(address =>
RemoteServer.registerActor(new InetSocketAddress(address.hostname, address.port), actorRef.uuid, actorRef))
case supervisorConfig @ SupervisorConfig(_, _) => // recursive supervisor configuration
val childSupervisor = Supervisor(supervisorConfig)
supervisor.link(childSupervisor.supervisor)
@ -231,11 +229,11 @@ sealed class Supervisor private[akka] (
* supervisor.link(child)
* supervisor.unlink(child)
* </pre>
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
final class SupervisorActor private[akka] (
handler: FaultHandlingStrategy,
handler: FaultHandlingStrategy,
trapExceptions: List[Class[_ <: Throwable]]) extends Actor {
import self._
trapExit = trapExceptions

View file

@ -18,7 +18,7 @@ import com.google.inject._
* <p/>
* If you don't want declarative configuration then you should use the <code>ActiveObject</code>
* factory methods.
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
class ActiveObjectConfigurator {

View file

@ -17,9 +17,9 @@ import java.net.InetSocketAddress
import java.lang.reflect.Method
/**
* This is an class for internal usage. Instead use the <code>se.scalablesolutions.akka.config.ActiveObjectConfigurator</code>
* This is an class for internal usage. Instead use the <code>se.scalablesolutions.akka.config.ActiveObjectConfigurator</code>
* class for creating ActiveObjects.
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
private[akka] class ActiveObjectGuiceConfigurator extends ActiveObjectConfiguratorBase with Logging {
@ -85,15 +85,11 @@ private[akka] class ActiveObjectGuiceConfigurator extends ActiveObjectConfigurat
val actorRef = Actor.actorOf(new Dispatcher(component.transactionRequired, component.lifeCycle.callbacks))
if (component.dispatcher.isDefined) actorRef.dispatcher = component.dispatcher.get
val remoteAddress =
if (component.remoteAddress.isDefined)
if (component.remoteAddress.isDefined)
Some(new InetSocketAddress(component.remoteAddress.get.hostname, component.remoteAddress.get.port))
else None
val proxy = ActiveObject.newInstance(targetClass, actorRef, remoteAddress, component.timeout).asInstanceOf[AnyRef]
if (remoteAddress.isDefined) {
RemoteServer
.actorsFor(RemoteServer.Address(component.remoteAddress.get.hostname, component.remoteAddress.get.port))
.activeObjects.put(targetClass.getName, proxy)
}
remoteAddress.foreach(address => RemoteServer.registerActiveObject(address, targetClass.getName, proxy))
supervised ::= Supervise(actorRef, component.lifeCycle)
activeObjectRegistry.put(targetClass, (proxy, proxy, component))
new DependencyBinding(targetClass, proxy)
@ -106,16 +102,12 @@ private[akka] class ActiveObjectGuiceConfigurator extends ActiveObjectConfigurat
val actorRef = Actor.actorOf(new Dispatcher(component.transactionRequired, component.lifeCycle.callbacks))
if (component.dispatcher.isDefined) actorRef.dispatcher = component.dispatcher.get
val remoteAddress =
if (component.remoteAddress.isDefined)
if (component.remoteAddress.isDefined)
Some(new InetSocketAddress(component.remoteAddress.get.hostname, component.remoteAddress.get.port))
else None
val proxy = ActiveObject.newInstance(
targetClass, targetInstance, actorRef, remoteAddress, component.timeout).asInstanceOf[AnyRef]
if (remoteAddress.isDefined) {
RemoteServer
.actorsFor(RemoteServer.Address(component.remoteAddress.get.hostname, component.remoteAddress.get.port))
.activeObjects.put(targetClass.getName, proxy)
}
remoteAddress.foreach(address => RemoteServer.registerActiveObject(address, targetClass.getName, proxy))
supervised ::= Supervise(actorRef, component.lifeCycle)
activeObjectRegistry.put(targetClass, (proxy, targetInstance, component))
new DependencyBinding(targetClass, proxy)
@ -166,4 +158,4 @@ private[akka] class ActiveObjectGuiceConfigurator extends ActiveObjectConfigurat
if (supervisor.isDefined) supervisor.get.shutdown
}
}

View file

@ -6,11 +6,13 @@ package se.scalablesolutions.akka.config
import se.scalablesolutions.akka.util.Logging
import net.lag.configgy.{Configgy, ParseException}
import net.lag.configgy.{Config => CConfig, Configgy, ParseException}
class ConfigurationException(message: String) extends RuntimeException(message)
/**
* Loads up the configuration (from the akka.conf file).
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
object Config extends Logging {
@ -37,9 +39,10 @@ object Config extends Logging {
log.info("Config loaded from -Dakka.config=%s", configFile)
} catch {
case e: ParseException => throw new ConfigurationException(
"Config could not be loaded from -Dakka.config=" + configFile +
"Config could not be loaded from -Dakka.config=" + configFile +
"\n\tdue to: " + e.toString)
}
Configgy.config
} else if (getClass.getClassLoader.getResource("akka.conf") != null) {
try {
Configgy.configureFromResource("akka.conf", getClass.getClassLoader)
@ -49,6 +52,7 @@ object Config extends Logging {
"Can't load 'akka.conf' config file from application classpath," +
"\n\tdue to: " + e.toString)
}
Configgy.config
} else if (HOME.isDefined) {
try {
val configFile = HOME.get + "/config/akka.conf"
@ -60,23 +64,24 @@ object Config extends Logging {
"\n\tbut the 'akka.conf' config file can not be found at [" + HOME.get + "/config/akka.conf]," +
"\n\tdue to: " + e.toString)
}
Configgy.config
} else {
throw new ConfigurationException(
log.warning(
"\nCan't load 'akka.conf'." +
"\nOne of the three ways of locating the 'akka.conf' file needs to be defined:" +
"\n\t1. Define the '-Dakka.config=...' system property option." +
"\n\t2. Put the 'akka.conf' file on the classpath." +
"\n\t3. Define 'AKKA_HOME' environment variable pointing to the root of the Akka distribution." +
"\nI have no way of finding the 'akka.conf' configuration file." +
"\nAborting.")
"\nUsing default values everywhere.")
CConfig.fromString("<akka></akka>")
}
Configgy.config
}
val CONFIG_VERSION = config.getString("akka.version", "0")
val CONFIG_VERSION = config.getString("akka.version", VERSION)
if (VERSION != CONFIG_VERSION) throw new ConfigurationException(
"Akka JAR version [" + VERSION + "] is different than the provided config ('akka.conf') version [" + CONFIG_VERSION + "]")
val startTime = System.currentTimeMillis
val startTime = System.currentTimeMillis
def uptime = (System.currentTimeMillis - startTime) / 1000
}

View file

@ -57,4 +57,4 @@ class Component(@BeanProperty val intf: Class[_],
@BeanProperty val timeout: Int) extends Server {
def newWorker(proxy: ActiveObjectProxy) = se.scalablesolutions.akka.kernel.Supervise(proxy.server, lifeCycle.transform)
}
*/
*/

View file

@ -16,7 +16,7 @@ private[akka] trait Configurator {
* @param clazz the class for the active object
* @return the active object for the class
*/
def getInstance[T](clazz: Class[T]): List[T]
def getInstance[T](clazz: Class[T]): List[T]
def getComponentInterfaces: List[Class[_]]

View file

@ -4,7 +4,7 @@
package se.scalablesolutions.akka.config
import se.scalablesolutions.akka.actor.{Actor, ActorRef}
import se.scalablesolutions.akka.actor.{Actor, ActorRef}
import se.scalablesolutions.akka.dispatch.MessageDispatcher
sealed abstract class FaultHandlingStrategy
@ -24,7 +24,7 @@ object ScalaConfig {
abstract class Scope extends ConfigElement
case class SupervisorConfig(restartStrategy: RestartStrategy, worker: List[Server]) extends Server
class Supervise(val actorRef: ActorRef, val lifeCycle: LifeCycle, _remoteAddress: RemoteAddress) extends Server {
val remoteAddress: Option[RemoteAddress] = if (_remoteAddress eq null) None else Some(_remoteAddress)
}
@ -135,7 +135,7 @@ object JavaConfig {
def transform = se.scalablesolutions.akka.config.ScalaConfig.RestartStrategy(
scheme.transform, maxNrOfRetries, withinTimeRange, trapExceptions.toList)
}
class LifeCycle(@BeanProperty val scope: Scope, @BeanProperty val callbacks: RestartCallbacks) extends ConfigElement {
def this(scope: Scope) = this(scope, null)
def transform = {
@ -230,5 +230,5 @@ object JavaConfig {
def newSupervised(actorRef: ActorRef) =
se.scalablesolutions.akka.config.ScalaConfig.Supervise(actorRef, lifeCycle.transform)
}
}
}

View file

@ -15,8 +15,8 @@ abstract class AbstractReactorBasedEventDrivenDispatcher(val name: String) exten
protected val messageInvokers = new HashMap[AnyRef, MessageInvoker]
protected var selectorThread: Thread = _
protected val guard = new Object
def dispatch(invocation: MessageInvocation) = queue.append(invocation)
def dispatch(invocation: MessageInvocation) = queue.append(invocation)
override def register(actorRef: ActorRef) = synchronized {
messageInvokers.put(actorRef, new ActorMessageInvoker(actorRef))

View file

@ -45,7 +45,7 @@ object Dispatchers {
super.register(actor)
}
}
object globalReactorBasedSingleThreadEventDrivenDispatcher extends ReactorBasedSingleThreadEventDrivenDispatcher("global")
object globalReactorBasedThreadPoolEventDrivenDispatcher extends ReactorBasedThreadPoolEventDrivenDispatcher("global")

View file

@ -96,7 +96,7 @@ class ExecutorBasedEventDrivenDispatcher(_name: String) extends MessageDispatche
active = false
references.clear
}
def usesActorMailbox = true
def ensureNotActive: Unit = if (active) throw new IllegalStateException(

View file

@ -32,7 +32,7 @@ class ExecutorBasedEventDrivenWorkStealingDispatcher(_name: String) extends Mess
@volatile private var active: Boolean = false
implicit def actorRef2actor(actorRef: ActorRef): Actor = actorRef.actor
/** Type of the actors registered in this dispatcher. */
private var actorType:Option[Class[_]] = None
@ -51,7 +51,7 @@ class ExecutorBasedEventDrivenWorkStealingDispatcher(_name: String) extends Mess
if (!tryProcessMailbox(invocation.receiver)) {
// we are not able to process our mailbox (another thread is busy with it), so lets donate some of our mailbox
// to another actor and then process his mailbox in stead.
findThief(invocation.receiver).foreach( tryDonateAndProcessMessages(invocation.receiver,_) )
findThief(invocation.receiver).foreach( tryDonateAndProcessMessages(invocation.receiver,_) )
}
}
})
@ -97,7 +97,7 @@ class ExecutorBasedEventDrivenWorkStealingDispatcher(_name: String) extends Mess
// copy to prevent concurrent modifications having any impact
val actors = pooledActors.toArray(new Array[ActorRef](pooledActors.size))
val i = if ( lastThiefIndex > actors.size ) 0 else lastThiefIndex
// we risk to pick a thief which is unregistered from the dispatcher in the meantime, but that typically means
// the dispatcher is being shut down...
val (thief: Option[ActorRef], index: Int) = doFindThief(receiver, actors, i)

View file

@ -44,7 +44,7 @@ object Futures {
def awaitEither[T](f1: Future[T], f2: Future[T]): Option[T] = {
import Actor.Sender.Self
import Actor.{spawn, actor}
case class Result(res: Option[T])
val handOff = new SynchronousQueue[Option[T]]
spawn {

View file

@ -37,7 +37,7 @@ class ReactorBasedSingleThreadEventDrivenDispatcher(name: String) extends Abstra
}
def isShutdown = !active
def usesActorMailbox = false
class Demultiplexer(private val messageQueue: ReactiveMessageQueue) extends MessageDemultiplexer {

View file

@ -125,16 +125,16 @@ class ReactorBasedThreadPoolEventDrivenDispatcher(_name: String)
private def resume(actor: AnyRef) = synchronized {
busyActors.add(actor)
}
private def suspend(actor: AnyRef) = synchronized {
busyActors.remove(actor)
busyActors.remove(actor)
}
private def passFairnessCheck(nrOfBusyMessages: Int) = {
if (fair) true
else nrOfBusyMessages < 100
}
def usesActorMailbox = false
def ensureNotActive: Unit = if (active) throw new IllegalStateException(

View file

@ -11,18 +11,18 @@ import se.scalablesolutions.akka.actor.{Actor, ActorRef, ActorMessageInvoker}
/**
* Dedicates a unique thread for each actor passed in as reference. Served through its messageQueue.
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
class ThreadBasedDispatcher(actor: ActorRef) extends MessageDispatcher {
private val name = actor.getClass.getName + ":" + actor.uuid
private val threadName = "thread-based:dispatcher:" + name
private val threadName = "thread-based:dispatcher:" + name
private val messageHandler = new ActorMessageInvoker(actor)
private val queue = new BlockingMessageQueue(name)
private var selectorThread: Thread = _
@volatile private var active: Boolean = false
def dispatch(invocation: MessageInvocation) = queue.append(invocation)
def dispatch(invocation: MessageInvocation) = queue.append(invocation)
def start = if (!active) {
active = true
@ -37,7 +37,7 @@ class ThreadBasedDispatcher(actor: ActorRef) extends MessageDispatcher {
}
selectorThread.start
}
def isShutdown = !active
def usesActorMailbox = false

View file

@ -18,7 +18,7 @@ trait ThreadPoolBuilder {
private val NR_MAX_THREADS = 128
private val KEEP_ALIVE_TIME = 60000L // default is one minute
private val MILLISECONDS = TimeUnit.MILLISECONDS
private var threadPoolBuilder: ThreadPoolExecutor = _
private var boundedExecutorBound = -1
private var inProcessOfBuilding = false
@ -30,7 +30,7 @@ trait ThreadPoolBuilder {
def isShutdown = executor.isShutdown
def buildThreadPool = synchronized {
def buildThreadPool: Unit = synchronized {
ensureNotActive
inProcessOfBuilding = false
if (boundedExecutorBound > 0) {
@ -152,7 +152,7 @@ trait ThreadPoolBuilder {
}
def ensureNotActive: Unit
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
@ -248,4 +248,4 @@ trait ThreadPoolBuilder {
}
}
}
}
}

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2010 Scalable Solutions AB <http://scalablesolutions.se>
*/
package se.scalablesolutions.akka.remote
import se.scalablesolutions.akka.actor.BootableActorLoaderService
@ -19,16 +19,16 @@ trait BootableRemoteActorService extends Bootable with Logging {
protected lazy val remoteServerThread = new Thread(new Runnable() {
def run = RemoteNode.start(self.applicationLoader)
}, "Akka Remote Service")
def startRemoteService = remoteServerThread.start
abstract override def onLoad = {
super.onLoad //Initialize BootableActorLoaderService before remote service
if(config.getBool("akka.remote.server.service", true)){
if(config.getBool("akka.remote.cluster.service", true))
Cluster.start(self.applicationLoader)
log.info("Initializing Remote Actors Service...")
startRemoteService
log.info("Remote Actors Service initialized!")

View file

@ -62,7 +62,7 @@ trait Cluster {
* @author Viktor Klang
*/
trait ClusterActor extends Actor with Cluster {
val name = config.getString("akka.remote.cluster.name") getOrElse "default"
val name = config.getString("akka.remote.cluster.name", "default")
@volatile protected var serializer : Serializer = _
@ -233,12 +233,13 @@ abstract class BasicClusterActor extends ClusterActor with Logging {
*/
object Cluster extends Cluster with Logging {
lazy val DEFAULT_SERIALIZER_CLASS_NAME = Serializer.Java.getClass.getName
lazy val DEFAULT_CLUSTER_ACTOR_CLASS_NAME = classOf[JGroupsClusterActor].getName
@volatile private[remote] var clusterActor: Option[ClusterActor] = None
@volatile private[remote] var clusterActorRef: Option[ActorRef] = None
private[remote] def createClusterActor(loader: ClassLoader): Option[ActorRef] = {
val name = config.getString("akka.remote.cluster.actor")
val name = config.getString("akka.remote.cluster.actor", DEFAULT_CLUSTER_ACTOR_CLASS_NAME)
if (name.isEmpty) throw new IllegalArgumentException(
"Can't start cluster since the 'akka.remote.cluster.actor' configuration option is not defined")
@ -246,19 +247,16 @@ object Cluster extends Cluster with Logging {
"akka.remote.cluster.serializer", DEFAULT_SERIALIZER_CLASS_NAME))
.newInstance.asInstanceOf[Serializer]
serializer.classLoader = Some(loader)
try {
name map {
fqn =>
Actor.actorOf({
val a = Class.forName(fqn).newInstance.asInstanceOf[ClusterActor]
a setSerializer serializer
a
})
}
}
catch {
case e =>
log.error(e, "Couldn't load Cluster provider: [%s]", name.getOrElse("Not specified"))
Some(Actor.actorOf {
val a = Class.forName(name).newInstance.asInstanceOf[ClusterActor]
a setSerializer serializer
a
})
} catch {
case e =>
log.error(e, "Couldn't load Cluster provider: [%s]", name)
None
}
}
@ -286,9 +284,9 @@ object Cluster extends Cluster with Logging {
def start(serializerClassLoader: Option[ClassLoader]): Unit = synchronized {
log.info("Starting up Cluster Service...")
if (clusterActor.isEmpty) {
for {
for {
actorRef <- createClusterActor(serializerClassLoader getOrElse getClass.getClassLoader)
sup <- createSupervisor(actorRef)
sup <- createSupervisor(actorRef)
} {
clusterActorRef = Some(actorRef.start)
clusterActor = Some(actorRef.actor.asInstanceOf[ClusterActor])

View file

@ -1,13 +1,12 @@
package se.scalablesolutions.akka.cluster.jgroups
package se.scalablesolutions.akka.remote
import org.jgroups.{JChannel, View => JG_VIEW, Address, Message => JG_MSG, ExtendedMembershipListener, Receiver}
import org.jgroups.util.Util
import se.scalablesolutions.akka.remote.BasicClusterActor
/**
* Clustering support via JGroups.
* @Author Viktor Klang
*
* @author Viktor Klang
*/
class JGroupsClusterActor extends BasicClusterActor {
import scala.collection.JavaConversions._
@ -20,7 +19,7 @@ class JGroupsClusterActor extends BasicClusterActor {
override def init = {
super.init
log debug "Initiating JGroups-based cluster actor"
log info "Initiating JGroups-based cluster actor"
isActive = true
// Set up the JGroups local endpoint
@ -58,9 +57,9 @@ class JGroupsClusterActor extends BasicClusterActor {
override def shutdown = {
super.shutdown
log debug ("Shutting down %s", toString)
log info ("Shutting down %s", toString)
isActive = false
channel.foreach(Util shutdown _)
channel = None
}
}
}

View file

@ -28,7 +28,7 @@ import scala.collection.mutable.{HashSet, HashMap}
/**
* Atomic remote request/reply message id generator.
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
object RemoteRequestProtocolIdFactory {
@ -64,7 +64,7 @@ object RemoteClient extends Logging {
def actorFor(className: String, timeout: Long, hostname: String, port: Int): ActorRef =
actorFor(className, className, timeout, hostname, port)
def actorFor(actorRef: String, className: String, timeout: Long, hostname: String, port: Int): ActorRef =
def actorFor(actorRef: String, className: String, timeout: Long, hostname: String, port: Int): ActorRef =
RemoteActorRef(actorRef, className, hostname, port, timeout)
def clientFor(hostname: String, port: Int): RemoteClient = clientFor(new InetSocketAddress(hostname, port))
@ -139,11 +139,11 @@ class RemoteClient(val hostname: String, val port: Int) extends Logging {
Executors.newCachedThreadPool)
private val bootstrap = new ClientBootstrap(channelFactory)
private val openChannels = new DefaultChannelGroup(classOf[RemoteClient].getName);
private val timer = new HashedWheelTimer
private val remoteAddress = new InetSocketAddress(hostname, port)
private[remote] var connection: ChannelFuture = _
private[remote] val openChannels = new DefaultChannelGroup(classOf[RemoteClient].getName);
bootstrap.setPipelineFactory(new RemoteClientPipelineFactory(name, futures, supervisors, bootstrap, remoteAddress, timer, this))
bootstrap.setOption("tcpNoDelay", true)
@ -296,11 +296,10 @@ class RemoteClientHandler(val name: String,
override def channelClosed(ctx: ChannelHandlerContext, event: ChannelStateEvent) = if (client.isRunning) {
timer.newTimeout(new TimerTask() {
def run(timeout: Timeout) = {
client.openChannels.remove(event.getChannel)
log.debug("Remote client reconnecting to [%s]", remoteAddress)
client.connection = bootstrap.connect(remoteAddress)
// Wait until the connection attempt succeeds or fails.
client.connection.awaitUninterruptibly
client.connection.awaitUninterruptibly // Wait until the connection attempt succeeds or fails.
if (!client.connection.isSuccess) {
client.listeners.toArray.foreach(l => l.asInstanceOf[ActorRef] ! RemoteClientError(client.connection.getCause))
log.error(client.connection.getCause, "Reconnection to [%s] has failed", remoteAddress)

View file

@ -22,7 +22,7 @@ object RemoteProtocolBuilder {
SERIALIZER_JAVA_JSON.classLoader = Some(cl)
SERIALIZER_SCALA_JSON.classLoader = Some(cl)
}
def getMessage(request: RemoteRequestProtocol): Any = {
request.getProtocol match {
case SerializationProtocol.JAVA =>

View file

@ -22,6 +22,8 @@ import org.jboss.netty.handler.codec.frame.{LengthFieldBasedFrameDecoder, Length
import org.jboss.netty.handler.codec.protobuf.{ProtobufDecoder, ProtobufEncoder}
import org.jboss.netty.handler.codec.compression.{ZlibEncoder, ZlibDecoder}
import scala.collection.mutable.Map
/**
* Use this object if you need a single remote server on a specific node.
*
@ -88,38 +90,52 @@ object RemoteServer {
}
}
class RemoteActorSet {
val actors = new ConcurrentHashMap[String, ActorRef]
val activeObjects = new ConcurrentHashMap[String, AnyRef]
private class RemoteActorSet {
private[RemoteServer] val actors = new ConcurrentHashMap[String, ActorRef]
private[RemoteServer] val activeObjects = new ConcurrentHashMap[String, AnyRef]
}
private val remoteActorSets = new ConcurrentHashMap[Address, RemoteActorSet]
private val remoteServers = new ConcurrentHashMap[Address, RemoteServer]
private val guard = new ReadWriteGuard
private val remoteActorSets = Map[Address, RemoteActorSet]()
private val remoteServers = Map[Address, RemoteServer]()
private[akka] def actorsFor(remoteServerAddress: RemoteServer.Address): RemoteActorSet = {
val set = remoteActorSets.get(remoteServerAddress)
if (set ne null) set
else {
val remoteActorSet = new RemoteActorSet
remoteActorSets.put(remoteServerAddress, remoteActorSet)
remoteActorSet
private[akka] def registerActor(address: InetSocketAddress, uuid: String, actor: ActorRef) = guard.withWriteGuard {
actorsFor(RemoteServer.Address(address.getHostName, address.getPort)).actors.put(uuid, actor)
}
private[akka] def registerActiveObject(address: InetSocketAddress, name: String, activeObject: AnyRef) = guard.withWriteGuard {
actorsFor(RemoteServer.Address(address.getHostName, address.getPort)).activeObjects.put(name, activeObject)
}
private[akka] def getOrCreateServer(address: InetSocketAddress): RemoteServer = guard.withWriteGuard {
serverFor(address) match {
case Some(server) => server
case None => (new RemoteServer).start(address)
}
}
private[akka] def serverFor(hostname: String, port: Int): Option[RemoteServer] = {
val server = remoteServers.get(Address(hostname, port))
if (server eq null) None
else Some(server)
}
private[akka] def serverFor(address: InetSocketAddress): Option[RemoteServer] =
serverFor(address.getHostName, address.getPort)
private[remote] def register(hostname: String, port: Int, server: RemoteServer) =
remoteServers.put(Address(hostname, port), server)
private[akka] def serverFor(hostname: String, port: Int): Option[RemoteServer] = guard.withReadGuard {
remoteServers.get(Address(hostname, port))
}
private[remote] def unregister(hostname: String, port: Int) =
private[akka] def register(hostname: String, port: Int, server: RemoteServer) = guard.withWriteGuard {
remoteServers.put(Address(hostname, port), server)
}
private[akka] def unregister(hostname: String, port: Int) = guard.withWriteGuard {
remoteServers.remove(Address(hostname, port))
}
private def actorsFor(remoteServerAddress: RemoteServer.Address): RemoteActorSet = {
remoteActorSets.get(remoteServerAddress).getOrElse {
val remoteActorSet = new RemoteActorSet
remoteActorSets.put(remoteServerAddress, remoteActorSet)
remoteActorSet
}
}
}
/**
@ -223,7 +239,7 @@ class RemoteServer extends Logging {
/**
* Register Remote Actor by a specific 'id' passed as argument.
* <p/>
* NOTE: If you use this method to register your remote actor then you must unregister the actor by this ID yourself.
* NOTE: If you use this method to register your remote actor then you must unregister the actor by this ID yourself.
*/
def register(id: String, actorRef: ActorRef) = synchronized {
if (_isRunning) {
@ -246,9 +262,9 @@ class RemoteServer extends Logging {
}
/**
* Unregister Remote Actor by specific 'id'.
* Unregister Remote Actor by specific 'id'.
* <p/>
* NOTE: You need to call this method if you have registered an actor by a custom ID.
* NOTE: You need to call this method if you have registered an actor by a custom ID.
*/
def unregister(id: String) = synchronized {
if (_isRunning) {

View file

@ -24,7 +24,7 @@ class CyclicIterator[T](items: List[T]) extends InfiniteIterator[T] {
}
}
/**
/**
* This InfiniteIterator always returns the Actor that has the currently smallest mailbox
* useful for work-stealing.
*/
@ -32,4 +32,4 @@ class SmallestMailboxFirstIterator(items : List[ActorRef]) extends InfiniteItera
def hasNext = items != Nil
def next = items.reduceLeft((a1, a2) => if (a1.mailboxSize < a2.mailboxSize) a1 else a2)
}
}

View file

@ -8,7 +8,7 @@ import se.scalablesolutions.akka.actor.{Actor, ActorRef}
sealed trait ListenerMessage
case class Listen(listener: ActorRef) extends ListenerMessage
case class Deafen(listener: ActorRef) extends ListenerMessage
case class Deafen(listener: ActorRef) extends ListenerMessage
case class WithListeners(f: Set[ActorRef] => Unit) extends ListenerMessage
/** Listeners is a generic trait to implement listening capability on an Actor
@ -26,6 +26,6 @@ trait Listeners { self : Actor =>
case Deafen(l) => listeners( _ - l )
case WithListeners(f) => listeners foreach f
}
protected def gossip(msg : Any) = listeners foreach ( _ foreach ( _ ! msg ) )
}
}

View file

@ -21,19 +21,19 @@ object Patterns {
/** Interceptor is a filter(x,y) where x.isDefinedAt is considered to be always true
*/
def intercept[A, B](interceptor: (A) => Unit, interceptee: PF[A, B]): PF[A, B] =
def intercept[A, B](interceptor: (A) => Unit, interceptee: PF[A, B]): PF[A, B] =
filter({case a if a.isInstanceOf[A] => interceptor(a)}, interceptee)
/** Creates a LoadBalancer from the thunk-supplied InfiniteIterator
*/
def loadBalancerActor(actors: => InfiniteIterator[ActorRef]): ActorRef =
def loadBalancerActor(actors: => InfiniteIterator[ActorRef]): ActorRef =
actorOf(new Actor with LoadBalancer {
val seq = actors
}).start
/** Creates a Dispatcher given a routing and a message-transforming function
*/
def dispatcherActor(routing: PF[Any, ActorRef], msgTransformer: (Any) => Any): ActorRef =
def dispatcherActor(routing: PF[Any, ActorRef], msgTransformer: (Any) => Any): ActorRef =
actorOf(new Actor with Dispatcher {
override def transform(msg: Any) = msgTransformer(msg)
def routes = routing
@ -45,9 +45,9 @@ object Patterns {
def routes = routing
}).start
/** Creates an actor that pipes all incoming messages to
/** Creates an actor that pipes all incoming messages to
* both another actor and through the supplied function
*/
def loggerActor(actorToLog: ActorRef, logger: (Any) => Unit): ActorRef =
def loggerActor(actorToLog: ActorRef, logger: (Any) => Unit): ActorRef =
dispatcherActor({case _ => actorToLog}, logger)
}
}

View file

@ -6,7 +6,7 @@ package se.scalablesolutions.akka.patterns
import se.scalablesolutions.akka.actor.{Actor, ActorRef}
/**
/**
* A Dispatcher is a trait whose purpose is to route incoming messages to actors.
*/
trait Dispatcher { this: Actor =>
@ -16,17 +16,17 @@ trait Dispatcher { this: Actor =>
protected def routes: PartialFunction[Any, ActorRef]
protected def dispatch: Receive = {
case a if routes.isDefinedAt(a) =>
case a if routes.isDefinedAt(a) =>
if (isSenderDefined) routes(a).forward(transform(a))(someSelf)
else routes(a).!(transform(a))(None)
else routes(a).!(transform(a))(None)
}
def receive = dispatch
private def isSenderDefined = self.senderFuture.isDefined || self.sender.isDefined
}
/**
/**
* A LoadBalancer is a specialized kind of Dispatcher, that is supplied an InfiniteIterator of targets
* to dispatch incoming messages to.
*/
@ -34,4 +34,4 @@ trait LoadBalancer extends Dispatcher { self: Actor =>
protected def seq: InfiniteIterator[ActorRef]
protected def routes = { case x if seq.hasNext => seq.next }
}
}

View file

@ -317,4 +317,4 @@ case class BinaryStringByteArrayMap(val value: Map[String, Array[Byte]]) extends
def this() = this(null)
def fromBytes(bytes: Array[Byte]) = BinaryStringByteArrayMap(fromByteArray[Map[String, Array[Byte]]](bytes))
def toBytes: Array[Byte] = toByteArray(value)
}
}

View file

@ -8,7 +8,7 @@ package se.scalablesolutions.akka.serialization
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
object Compression {
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/

View file

@ -32,20 +32,20 @@ trait Serializable {
/**
* Serialization protocols.
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
object Serializable {
/**
* Example on how to use the SBinary serialization protocol:
* Example on how to use the SBinary serialization protocol:
* <pre>
* case class User(val usernamePassword: Tuple2[String, String],
* val email: String,
* val age: Int)
* extends Serializable.SBinary[User] {
* def this() = this(null, null, 0)
* import sbinary.DefaultProtocol._
* import sbinary.DefaultProtocol._
* implicit object UserFormat extends Format[User] {
* def reads(in : Input) = User(
* read[Tuple2[String, String]](in),
@ -74,7 +74,7 @@ object Serializable {
trait JSON extends Serializable {
def toJSON: String
}
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/

View file

@ -34,7 +34,7 @@ class SerializerFactory {
def getJavaJSON: JavaJSON.type = JavaJSON
def getScalaJSON: ScalaJSON.type = ScalaJSON
def getSBinary: SBinary.type = SBinary
def getProtobuf: Protobuf.type = Protobuf
def getProtobuf: Protobuf.type = Protobuf
}
/**
@ -67,7 +67,7 @@ object Serializer {
}
def in(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = {
val in =
val in =
if (classLoader.isDefined) new ClassLoaderObjectInputStream(classLoader.get, new ByteArrayInputStream(bytes))
else new ObjectInputStream(new ByteArrayInputStream(bytes))
val obj = in.readObject
@ -88,14 +88,14 @@ object Serializer {
"Can't serialize a non-protobuf message using protobuf [" + obj + "]")
obj.asInstanceOf[Message].toByteArray
}
def in(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")
"Need a protobuf message class to be able to serialize bytes using protobuf")
// TODO: should we cache this method lookup?
val message = clazz.get.getDeclaredMethod(
"getDefaultInstance", EMPTY_CLASS_ARRAY: _*).invoke(null, EMPTY_ANY_REF_ARRAY: _*).asInstanceOf[Message]
message.toBuilder().mergeFrom(bytes).build
message.toBuilder().mergeFrom(bytes).build
}
def in(bytes: Array[Byte], clazz: Class[_]): AnyRef = {
@ -124,7 +124,7 @@ object Serializer {
def in(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 =
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]
@ -137,7 +137,7 @@ object Serializer {
mapper.readValue(json, clazz).asInstanceOf[AnyRef]
}
}
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
@ -149,7 +149,7 @@ object Serializer {
// FIXME set ClassLoader on SJSONSerializer.SJSON
def in(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = SJSONSerializer.SJSON.in(bytes)
import scala.reflect.Manifest
def in[T](json: String)(implicit m: Manifest[T]): AnyRef = {
SJSONSerializer.SJSON.in(json)(m)
@ -168,13 +168,13 @@ object Serializer {
import sbinary._
import sbinary.Operations._
import sbinary.DefaultProtocol._
def deepClone[T <: AnyRef](obj: T)(implicit w : Writes[T], r : Reads[T]): T = in[T](out[T](obj), None)
def out[T](t : T)(implicit bin : Writes[T]): Array[Byte] = toByteArray[T](t)
def in[T](array : Array[Byte], clazz: Option[Class[T]])(implicit bin : Reads[T]): T = fromByteArray[T](array)
def in[T](array : Array[Byte])(implicit bin : Reads[T]): T = fromByteArray[T](array)
}
}

View file

@ -40,34 +40,34 @@ trait PersistentDataStructure
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
*
* @author Daniel Spiewak
* @author Rich Hickey
*/
@serializable
final class HashTrie[K, +V] private (root: Node[K, V]) extends Map[K, V] with PersistentDataStructure {
override lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = update(pair._1, pair._2)
override def update[A >: V](key: K, value: A) = new HashTrie(root(0, key, key.hashCode) = value)
def -(key: K) = new HashTrie(root.remove(key, key.hashCode))
def iterator = root.elements
def empty[A]: HashTrie[K, A] = new HashTrie(new EmptyNode[K])
def diagnose = root.toString
}
object HashTrie {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashTrie[K, V]) { _ + _ }
def unapplySeq[K, V](map: HashTrie[K, V]) = map.toSeq
}
@ -77,29 +77,29 @@ object HashTrie {
@serializable
private[stm] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
@serializable
private[stm] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](shift: Int, key: K, hash: Int, value: V) = new LeafNode(key, hash, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
@ -111,9 +111,9 @@ private[stm] abstract class SingleNode[K, +V] extends Node[K, V] {
private[stm] class LeafNode[K, +V](key: K, val hash: Int, value: V) extends SingleNode[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](shift: Int, key: K, hash: Int, value: A) = {
if (this.key == key) {
if (this.value == value) this else new LeafNode(key, hash, value)
@ -123,53 +123,53 @@ private[stm] class LeafNode[K, +V](key: K, val hash: Int, value: V) extends Sing
BitmappedNode(shift)(this, key, hash, value)
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[stm] class CollisionNode[K, +V](val hash: Int, bucket: List[(K, V)]) extends SingleNode[K, V] {
lazy val size = bucket.length
def this(hash: Int, pairs: (K, V)*) = this(hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
override def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for ((k, v) <- bucket) yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(hash, if (found) newBucket else (key, value) :: bucket)
} else {
BitmappedNode(shift)(this, key, hash, value)
}
}
override def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == bucket.length) this else {
if (newBucket.length == 1) {
val (key, value) = newBucket.head
@ -177,11 +177,11 @@ private[stm] class CollisionNode[K, +V](val hash: Int, bucket: List[(K, V)]) ext
} else new CollisionNode(hash, newBucket)
}
}
def iterator = bucket.iterator
def elements = bucket.iterator
override def toString = "CollisionNode(" + bucket.toString + ")"
}
@ -191,38 +191,38 @@ private[stm] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bi
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
override def update[A >: V](levelShift: Int, key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else {
val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = new LeafNode(key, hash, value)
val newBits = bits | mask
if (newBits == ~0) {
new FullNode(shift)(newTable)
@ -231,54 +231,54 @@ private[stm] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bi
}
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node == table(i)) {
this
} else if (node.isInstanceOf[EmptyNode[_]]) {
if (size == 1) new EmptyNode[K] else {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
table.foldLeft(emptyElements) { (it, e) =>
if (e eq null) it else it ++ e.elements
}
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ ne null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
@ -287,26 +287,26 @@ private[stm] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bi
private[stm] object BitmappedNode {
def apply[K, V](shift: Int)(node: SingleNode[K, V], key: K, hash: Int, value: V) = {
val table = new Array[Node[K, V]](Math.max((hash >>> shift) & 0x01f, (node.hash >>> shift) & 0x01f) + 1)
val preBits = {
val i = (node.hash >>> shift) & 0x01f
table(i) = node
1 << i
}
val bits = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((preBits & mask) == mask) {
table(i) = (table(i)(shift + 5, key, hash) = value)
} else {
table(i) = new LeafNode(key, hash, value)
}
preBits | mask
}
new BitmappedNode(shift)(table, bits)
}
}
@ -314,34 +314,34 @@ private[stm] object BitmappedNode {
private[stm] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val node = table(i).remove(key, hash)
if (node == table(i)) this else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, ~mask)
@ -351,14 +351,14 @@ private[stm] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends
}
}
}
def elements = table.foldLeft(emptyElements) { _ ++ _.elements }
override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}

View file

@ -12,13 +12,13 @@ import se.scalablesolutions.akka.util.Logging
/**
* Detects if there is a UserTransaction or TransactionManager available in the JNDI.
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
object TransactionContainer extends Logging {
val AKKA_JTA_TRANSACTION_SERVICE_CLASS = "se.scalablesolutions.akka.jta.AtomikosTransactionService"
val DEFAULT_USER_TRANSACTION_NAME = "java:comp/UserTransaction"
val FALLBACK_TRANSACTION_MANAGER_NAMES = "java:comp/TransactionManager" ::
val FALLBACK_TRANSACTION_MANAGER_NAMES = "java:comp/TransactionManager" ::
"java:appserver/TransactionManager" ::
"java:pm/TransactionManager" ::
"java:/TransactionManager" :: Nil
@ -27,12 +27,12 @@ object TransactionContainer extends Logging {
val JTA_PROVIDER = config.getString("akka.jta.provider", "from-jndi")
private var synchronizationRegistry: Option[TransactionSynchronizationRegistry] = None
def apply(tm: Either[Option[UserTransaction], Option[TransactionManager]]) = new TransactionContainer(tm)
def apply(): TransactionContainer =
JTA_PROVIDER match {
case "from-jndi" =>
case "from-jndi" =>
new TransactionContainer(findUserTransaction match {
case None => Right(findTransactionManager)
case tm => Left(tm)
@ -43,19 +43,19 @@ object TransactionContainer extends Logging {
.newInstance.asInstanceOf[TransactionService]
.transactionContainer
} catch {
case e: ClassNotFoundException =>
case e: ClassNotFoundException =>
throw new StmConfigurationException(
"JTA provider defined as 'atomikos', but the AtomikosTransactionService classes can not be found." +
"JTA provider defined as 'atomikos', but the AtomikosTransactionService classes can not be found." +
"\n\tPlease make sure you have 'akka-jta' JAR and its dependencies on your classpath.")
}
case _ =>
case _ =>
throw new StmConfigurationException(
"No UserTransaction on TransactionManager could be found in scope." +
"\n\tEither add 'akka-jta' to the classpath or make sure there is a" +
"\n\tEither add 'akka-jta' to the classpath or make sure there is a" +
"\n\tTransactionManager or UserTransaction defined in the JNDI.")
}
def findUserTransaction: Option[UserTransaction] = {
val located = createInitialContext.lookup(DEFAULT_USER_TRANSACTION_NAME)
if (located eq null) None
@ -74,7 +74,7 @@ object TransactionContainer extends Logging {
log.info("JTA TransactionSynchronizationRegistry detected [%s]", located)
synchronizationRegistry = Some(located.asInstanceOf[TransactionSynchronizationRegistry])
synchronizationRegistry
}
}
}
}
@ -100,49 +100,49 @@ object TransactionContainer extends Logging {
* JTA transaction container holding either a UserTransaction or a TransactionManager.
* <p/>
* The TransactionContainer is created using the factory <tt>val container = TransactionContainer()</tt>
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
class TransactionContainer private (val tm: Either[Option[UserTransaction], Option[TransactionManager]]) {
def registerSynchronization(sync: Synchronization) = {
TransactionContainer.findSynchronizationRegistry match { // try to use SynchronizationRegistry in JNDI
case Some(registry) =>
case Some(registry) =>
registry.asInstanceOf[TransactionSynchronizationRegistry].registerInterposedSynchronization(sync)
case None =>
tm match {
case Right(Some(txMan)) => // try to use TransactionManager
txMan.getTransaction.registerSynchronization(sync)
case _ =>
log.warning("Cannot find TransactionSynchronizationRegistry in JNDI, can't register STM synchronization")
log.warning("Cannot find TransactionSynchronizationRegistry in JNDI, can't register STM synchronization")
}
}
}
def begin = tm match {
case Left(Some(userTx)) => userTx.begin
case Right(Some(txMan)) => txMan.begin
case _ => throw new StmConfigurationException("Does not have a UserTransaction or TransactionManager in scope")
}
def commit = tm match {
case Left(Some(userTx)) => userTx.commit
case Right(Some(txMan)) => txMan.commit
case _ => throw new StmConfigurationException("Does not have a UserTransaction or TransactionManager in scope")
}
def rollback = tm match {
case Left(Some(userTx)) => userTx.rollback
case Right(Some(txMan)) => txMan.rollback
case _ => throw new StmConfigurationException("Does not have a UserTransaction or TransactionManager in scope")
}
def getStatus = tm match {
case Left(Some(userTx)) => userTx.getStatus
case Right(Some(txMan)) => txMan.getStatus
case _ => throw new StmConfigurationException("Does not have a UserTransaction or TransactionManager in scope")
}
def isInExistingTransaction = tm match {
case Left(Some(userTx)) => userTx.getStatus == Status.STATUS_ACTIVE
case Right(Some(txMan)) => txMan.getStatus == Status.STATUS_ACTIVE
@ -154,7 +154,7 @@ class TransactionContainer private (val tm: Either[Option[UserTransaction], Opti
case Right(Some(txMan)) => txMan.getStatus == Status.STATUS_MARKED_ROLLBACK
case _ => throw new StmConfigurationException("Does not have a UserTransaction or TransactionManager in scope")
}
def setRollbackOnly = tm match {
case Left(Some(userTx)) => userTx.setRollbackOnly
case Right(Some(txMan)) => txMan.setRollbackOnly
@ -165,7 +165,7 @@ class TransactionContainer private (val tm: Either[Option[UserTransaction], Opti
case Right(Some(txMan)) => txMan.suspend
case _ => throw new StmConfigurationException("Does not have a TransactionManager in scope")
}
def resume(tx: JtaTransaction) = tm match {
case Right(Some(txMan)) => txMan.resume(tx)
case _ => throw new StmConfigurationException("Does not have a TransactionManager in scope")
@ -197,6 +197,6 @@ class StmSynchronization(tc: TransactionContainer, tx: Transaction) extends Sync
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
trait TransactionService {
def transactionContainer: TransactionContainer
def transactionContainer: TransactionContainer
}

View file

@ -11,7 +11,7 @@ package se.scalablesolutions.akka.stm
* <pre>
* scala> ResultOrFailure(1)
* res0: ResultOrFailure[Int] = ResultOrFailure@a96606
*
*
* scala> res0()
* res1: Int = 1
*
@ -19,13 +19,13 @@ package se.scalablesolutions.akka.stm
*
* scala> res0()
* res3: Int = 3
*
*
* scala> res0() = { println("Hello world"); 3}
* Hello world
*
* scala> res0()
* res5: Int = 3
*
*
* scala> res0() = error("Lets see what happens here...")
*
* scala> res0()

View file

@ -306,22 +306,22 @@ object Transaction {
private[akka] var transaction: Option[MultiverseTransaction] = None
private[this] val persistentStateMap = new HashMap[String, Committable]
private[akka] val depth = new AtomicInteger(0)
val jta: Option[TransactionContainer] =
if (JTA_AWARE) Some(TransactionContainer())
else None
log.trace("Creating %s", toString)
// --- public methods ---------
def begin = synchronized {
jta.foreach { txContainer =>
jta.foreach { txContainer =>
txContainer.begin
txContainer.registerSynchronization(new StmSynchronization(txContainer, this))
}
}
def commit = synchronized {
log.trace("Committing transaction %s", toString)
Transaction.atomic0 {
@ -347,7 +347,7 @@ object Transaction {
// --- internal methods ---------
private def isJtaTxActive(status: Int) = status == Status.STATUS_ACTIVE
private[akka] def status_? = status
private[akka] def increment = depth.incrementAndGet

View file

@ -21,13 +21,13 @@ import org.multiverse.api.GlobalStmInstance.getGlobalStmInstance
* val myVector = TransactionalVector()
* val myRef = TransactionalRef()
* </pre>
*
*
* <p/>
* Example Java usage:
* <pre>
* TransactionalMap myMap = TransactionalState.newMap();
* </pre>
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
object TransactionalState {
@ -58,7 +58,7 @@ trait Committable {
object RefFactory {
private val factory = getGlobalStmInstance.getProgrammaticReferenceFactoryBuilder.build
def createRef[T] = factory.atomicCreateReference[T]()
def createRef[T](value: T) = factory.atomicCreateReference(value)
@ -66,7 +66,7 @@ object RefFactory {
/**
* Alias to TransactionalRef.
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
object Ref {
@ -79,7 +79,7 @@ object Ref {
/**
* Alias to Ref.
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
object TransactionalRef {
@ -146,7 +146,7 @@ class TransactionalRef[T](initialOpt: Option[T] = None) extends Transactional {
ensureIsInTransaction
!ref.isNull
}
def isEmpty: Boolean = {
ensureIsInTransaction
ref.isNull
@ -171,7 +171,7 @@ class TransactionalRef[T](initialOpt: Option[T] = None) extends Transactional {
* Necessary to keep from being implicitly converted to Iterable in for comprehensions.
*/
def withFilter(p: T => Boolean): WithFilter = new WithFilter(p)
class WithFilter(p: T => Boolean) {
def map[B](f: T => B): TransactionalRef[B] = self filter p map f
def flatMap[B](f: T => TransactionalRef[B]): TransactionalRef[B] = self filter p flatMap f
@ -228,14 +228,14 @@ class TransactionalMap[K, V](initialOpt: Option[HashTrie[K, V]] = None) extends
val uuid = UUID.newUuid.toString
protected[this] val ref = new TransactionalRef(initialOpt.orElse(Some(new HashTrie[K, V])))
def -=(key: K) = {
def -=(key: K) = {
remove(key)
this
}
def +=(key: K, value: V) = put(key, value)
def +=(kv: (K, V)) = {
put(kv._1,kv._2)
this
@ -249,7 +249,7 @@ class TransactionalMap[K, V](initialOpt: Option[HashTrie[K, V]] = None) extends
}
def get(key: K): Option[V] = ref.get.get.get(key)
override def put(key: K, value: V): Option[V] = {
val map = ref.get.get
val oldValue = map.get(key)
@ -262,7 +262,7 @@ class TransactionalMap[K, V](initialOpt: Option[HashTrie[K, V]] = None) extends
val oldValue = map.get(key)
ref.swap(map.update(key, value))
}
def iterator = ref.get.get.iterator
override def elements: Iterator[(K, V)] = ref.get.get.iterator
@ -272,15 +272,15 @@ class TransactionalMap[K, V](initialOpt: Option[HashTrie[K, V]] = None) extends
override def clear = ref.swap(new HashTrie[K, V])
override def size: Int = ref.get.get.size
override def hashCode: Int = System.identityHashCode(this);
override def equals(other: Any): Boolean =
other.isInstanceOf[TransactionalMap[_, _]] &&
other.isInstanceOf[TransactionalMap[_, _]] &&
other.hashCode == hashCode
override def toString = if (outsideTransaction) "<TransactionalMap>" else super.toString
def outsideTransaction =
org.multiverse.api.ThreadLocalTransaction.getThreadLocalTransaction eq null
}
@ -302,9 +302,9 @@ class TransactionalVector[T](initialOpt: Option[Vector[T]] = None) extends Trans
val uuid = UUID.newUuid.toString
private[this] val ref = new TransactionalRef(initialOpt.orElse(Some(EmptyVector)))
def clear = ref.swap(EmptyVector)
def +(elem: T) = add(elem)
def add(elem: T) = ref.swap(ref.get.get + elem)
@ -324,12 +324,12 @@ class TransactionalVector[T](initialOpt: Option[Vector[T]] = None) extends Trans
override def hashCode: Int = System.identityHashCode(this);
override def equals(other: Any): Boolean =
other.isInstanceOf[TransactionalVector[_]] &&
override def equals(other: Any): Boolean =
other.isInstanceOf[TransactionalVector[_]] &&
other.hashCode == hashCode
override def toString = if (outsideTransaction) "<TransactionalVector>" else super.toString
def outsideTransaction =
org.multiverse.api.ThreadLocalTransaction.getThreadLocalTransaction eq null
}

View file

@ -43,19 +43,19 @@ import Vector._
* @author Rich Hickey
*/
@serializable
class Vector[+T] private (val length: Int, shift: Int, root: Array[AnyRef], tail: Array[AnyRef])
class Vector[+T] private (val length: Int, shift: Int, root: Array[AnyRef], tail: Array[AnyRef])
extends IndexedSeq[T] with PersistentDataStructure { outer =>
private val tailOff = length - tail.length
/*
* The design of this data structure inherantly requires heterogenous arrays.
* It is *possible* to design around this, but the result is comparatively
* quite inefficient. With respect to this fact, I have left the original
* (somewhat dynamically-typed) implementation in place.
*/
private[stm] def this() = this(0, 5, EmptyArray, EmptyArray)
def apply(i: Int): T = {
if (i >= 0 && i < length) {
if (i >= tailOff) {
@ -63,24 +63,24 @@ class Vector[+T] private (val length: Int, shift: Int, root: Array[AnyRef], tail
} else {
var arr = root
var level = shift
while (level > 0) {
arr = arr((i >>> level) & 0x01f).asInstanceOf[Array[AnyRef]]
level -= 5
}
arr(i & 0x01f).asInstanceOf[T]
}
} else throw new IndexOutOfBoundsException(i.toString)
}
def update[A >: T](i: Int, obj: A): Vector[A] = {
if (i >= 0 && i < length) {
if (i >= tailOff) {
val newTail = new Array[AnyRef](tail.length)
Array.copy(tail, 0, newTail, 0, tail.length)
newTail(i & 0x01f) = obj.asInstanceOf[AnyRef]
new Vector[A](length, shift, root, newTail)
} else {
new Vector[A](length, shift, doAssoc(shift, root, i, obj), tail)
@ -89,69 +89,69 @@ class Vector[+T] private (val length: Int, shift: Int, root: Array[AnyRef], tail
this + obj
} else throw new IndexOutOfBoundsException(i.toString)
}
private def doAssoc[A >: T](level: Int, arr: Array[AnyRef], i: Int, obj: A): Array[AnyRef] = {
val ret = new Array[AnyRef](arr.length)
Array.copy(arr, 0, ret, 0, arr.length)
if (level == 0) {
ret(i & 0x01f) = obj.asInstanceOf[AnyRef]
} else {
val subidx = (i >>> level) & 0x01f
ret(subidx) = doAssoc(level - 5, arr(subidx).asInstanceOf[Array[AnyRef]], i, obj)
}
ret
}
def ++[A >: T](other: Iterable[A]) = other.foldLeft(this:Vector[A]) { _ + _ }
def +[A >: T](obj: A): Vector[A] = {
if (tail.length < 32) {
val newTail = new Array[AnyRef](tail.length + 1)
Array.copy(tail, 0, newTail, 0, tail.length)
newTail(tail.length) = obj.asInstanceOf[AnyRef]
new Vector[A](length + 1, shift, root, newTail)
} else {
var (newRoot, expansion) = pushTail(shift - 5, root, tail, null)
var newShift = shift
if (expansion ne null) {
newRoot = array(newRoot, expansion)
newShift += 5
}
new Vector[A](length + 1, newShift, newRoot, array(obj.asInstanceOf[AnyRef]))
}
}
private def pushTail(level: Int, arr: Array[AnyRef], tailNode: Array[AnyRef], expansion: AnyRef): (Array[AnyRef], AnyRef) = {
val newChild = if (level == 0) tailNode else {
val (newChild, subExpansion) = pushTail(level - 5, arr(arr.length - 1).asInstanceOf[Array[AnyRef]], tailNode, expansion)
if (subExpansion eq null) {
val ret = new Array[AnyRef](arr.length)
Array.copy(arr, 0, ret, 0, arr.length)
ret(arr.length - 1) = newChild
return (ret, null)
} else subExpansion
}
// expansion
if (arr.length == 32) {
(arr, array(newChild))
(arr, array(newChild))
} else {
val ret = new Array[AnyRef](arr.length + 1)
Array.copy(arr, 0, ret, 0, arr.length)
ret(arr.length) = newChild
(ret, null)
}
}
/**
* Removes the <i>tail</i> element of this vector.
*/
@ -163,99 +163,99 @@ class Vector[+T] private (val length: Int, shift: Int, root: Array[AnyRef], tail
} else if (tail.length > 1) {
val newTail = new Array[AnyRef](tail.length - 1)
Array.copy(tail, 0, newTail, 0, newTail.length)
new Vector[T](length - 1, shift, root, newTail)
} else {
var (newRoot, pTail) = popTail(shift - 5, root, null)
var newShift = shift
if (newRoot eq null) {
newRoot = EmptyArray
}
if (shift > 5 && newRoot.length == 1) {
newRoot = newRoot(0).asInstanceOf[Array[AnyRef]]
newShift -= 5
}
new Vector[T](length - 1, newShift, newRoot, pTail.asInstanceOf[Array[AnyRef]])
}
}
private def popTail(shift: Int, arr: Array[AnyRef], pTail: AnyRef): (Array[AnyRef], AnyRef) = {
val newPTail = if (shift > 0) {
val (newChild, subPTail) = popTail(shift - 5, arr(arr.length - 1).asInstanceOf[Array[AnyRef]], pTail)
if (newChild ne null) {
val ret = new Array[AnyRef](arr.length)
Array.copy(arr, 0, ret, 0, arr.length)
ret(arr.length - 1) = newChild
return (ret, subPTail)
}
subPTail
} else if (shift == 0) {
arr(arr.length - 1)
} else pTail
// contraction
if (arr.length == 1) {
(null, newPTail)
} else {
} else {
val ret = new Array[AnyRef](arr.length - 1)
Array.copy(arr, 0, ret, 0, ret.length)
(ret, newPTail)
}
}
override def filter(p: (T)=>Boolean) = {
var back = new Vector[T]
var i = 0
while (i < length) {
val e = apply(i)
if (p(e)) back += e
i += 1
}
back
}
def flatMap[A](f: (T)=>Iterable[A]): Vector[A] = {
var back = new Vector[A]
var i = 0
while (i < length) {
f(apply(i)) foreach { back += _ }
i += 1
}
back
}
def map[A](f: (T)=>A): Vector[A] = {
var back = new Vector[A]
var i = 0
while (i < length) {
back += f(apply(i))
i += 1
}
back
}
override def reverse: Vector[T] = new VectorProjection[T] {
override val length = outer.length
override def apply(i: Int) = outer.apply(length - i - 1)
}
def subseq(from: Int, end: Int) = subVector(from, end)
def subVector(from: Int, end: Int): Vector[T] = {
if (from < 0) {
throw new IndexOutOfBoundsException(from.toString)
@ -266,37 +266,37 @@ class Vector[+T] private (val length: Int, shift: Int, root: Array[AnyRef], tail
} else {
new VectorProjection[T] {
override val length = end - from
override def apply(i: Int) = outer.apply(i + from)
}
}
}
def zip[A](that: Vector[A]) = {
var back = new Vector[(T, A)]
var i = 0
val limit = Math.min(length, that.length)
while (i < limit) {
back += (apply(i), that(i))
i += 1
}
back
}
def zipWithIndex = {
var back = new Vector[(T, Int)]
var i = 0
while (i < length) {
back += (apply(i), i)
i += 1
}
back
}
override def equals(other: Any) = other match {
case vec: Vector[_] => {
var back = length == vec.length
@ -318,11 +318,11 @@ class Vector[+T] private (val length: Int, shift: Int, root: Array[AnyRef], tail
object Vector {
private[stm] val EmptyArray = new Array[AnyRef](0)
def apply[T](elems: T*) = elems.foldLeft(EmptyVector:Vector[T]) { _ + _ }
def unapplySeq[T](vec: Vector[T]): Option[Seq[T]] = Some(vec)
@inline
private[stm] def array(elems: AnyRef*) = {
val back = new Array[AnyRef](elems.length)
@ -337,9 +337,9 @@ object EmptyVector extends Vector[Nothing]
private[stm] abstract class VectorProjection[+T] extends Vector[T] {
override val length: Int
override def apply(i: Int): T
override def +[A >: T](e: A) = innerCopy + e
override def update[A >: T](i: Int, e: A) = {
if (i < 0) {
throw new IndexOutOfBoundsException(i.toString)
@ -347,7 +347,7 @@ private[stm] abstract class VectorProjection[+T] extends Vector[T] {
throw new IndexOutOfBoundsException(i.toString)
} else innerCopy(i) = e
}
private lazy val innerCopy = foldLeft(EmptyVector:Vector[T]) { _ + _ }
}

View file

@ -7,4 +7,4 @@ package se.scalablesolutions.akka.util
trait Bootable {
def onLoad {}
def onUnload {}
}
}

View file

@ -21,7 +21,7 @@ import java.lang.{Float => JFloat, Double => JDouble}
* result
* }
* </pre>
*
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
object HashCode {

View file

@ -11,54 +11,54 @@ public final class ProtobufProtocol {
com.google.protobuf.GeneratedMessage {
// Use ProtobufPOJO.newBuilder() to construct.
private ProtobufPOJO() {}
private static final ProtobufPOJO defaultInstance = new ProtobufPOJO();
public static ProtobufPOJO getDefaultInstance() {
return defaultInstance;
}
public ProtobufPOJO getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return se.scalablesolutions.akka.actor.ProtobufProtocol.internal_static_se_scalablesolutions_akka_actor_ProtobufPOJO_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return se.scalablesolutions.akka.actor.ProtobufProtocol.internal_static_se_scalablesolutions_akka_actor_ProtobufPOJO_fieldAccessorTable;
}
// required uint64 id = 1;
public static final int ID_FIELD_NUMBER = 1;
private boolean hasId;
private long id_ = 0L;
public boolean hasId() { return hasId; }
public long getId() { return id_; }
// required string name = 2;
public static final int NAME_FIELD_NUMBER = 2;
private boolean hasName;
private java.lang.String name_ = "";
public boolean hasName() { return hasName; }
public java.lang.String getName() { return name_; }
// required bool status = 3;
public static final int STATUS_FIELD_NUMBER = 3;
private boolean hasStatus;
private boolean status_ = false;
public boolean hasStatus() { return hasStatus; }
public boolean getStatus() { return status_; }
public final boolean isInitialized() {
if (!hasId) return false;
if (!hasName) return false;
if (!hasStatus) return false;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (hasId()) {
@ -72,12 +72,12 @@ public final class ProtobufProtocol {
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasId()) {
size += com.google.protobuf.CodedOutputStream
@ -95,7 +95,7 @@ public final class ProtobufProtocol {
memoizedSerializedSize = size;
return size;
}
public static se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
@ -153,31 +153,31 @@ public final class ProtobufProtocol {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> {
private se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO result;
// Construct using se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO.newBuilder()
private Builder() {}
private static Builder create() {
Builder builder = new Builder();
builder.result = new se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO();
return builder;
}
protected se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO internalGetResult() {
return result;
}
public Builder clear() {
if (result == null) {
throw new IllegalStateException(
@ -186,20 +186,20 @@ public final class ProtobufProtocol {
result = new se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO();
return this;
}
public Builder clone() {
return create().mergeFrom(result);
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO.getDescriptor();
}
public se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO getDefaultInstanceForType() {
return se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO.getDefaultInstance();
}
public boolean isInitialized() {
return result.isInitialized();
}
@ -209,7 +209,7 @@ public final class ProtobufProtocol {
}
return buildPartial();
}
private se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
if (!isInitialized()) {
@ -218,7 +218,7 @@ public final class ProtobufProtocol {
}
return buildPartial();
}
public se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO buildPartial() {
if (result == null) {
throw new IllegalStateException(
@ -228,7 +228,7 @@ public final class ProtobufProtocol {
result = null;
return returnMe;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO) {
return mergeFrom((se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO)other);
@ -237,7 +237,7 @@ public final class ProtobufProtocol {
return this;
}
}
public Builder mergeFrom(se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO other) {
if (other == se.scalablesolutions.akka.actor.ProtobufProtocol.ProtobufPOJO.getDefaultInstance()) return this;
if (other.hasId()) {
@ -252,7 +252,7 @@ public final class ProtobufProtocol {
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
@ -289,8 +289,8 @@ public final class ProtobufProtocol {
}
}
}
// required uint64 id = 1;
public boolean hasId() {
return result.hasId();
@ -308,7 +308,7 @@ public final class ProtobufProtocol {
result.id_ = 0L;
return this;
}
// required string name = 2;
public boolean hasName() {
return result.hasName();
@ -329,7 +329,7 @@ public final class ProtobufProtocol {
result.name_ = getDefaultInstance().getName();
return this;
}
// required bool status = 3;
public boolean hasStatus() {
return result.hasStatus();
@ -348,22 +348,22 @@ public final class ProtobufProtocol {
return this;
}
}
static {
se.scalablesolutions.akka.actor.ProtobufProtocol.getDescriptor();
}
static {
se.scalablesolutions.akka.actor.ProtobufProtocol.internalForceInit();
}
}
private static com.google.protobuf.Descriptors.Descriptor
internal_static_se_scalablesolutions_akka_actor_ProtobufPOJO_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_se_scalablesolutions_akka_actor_ProtobufPOJO_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
@ -397,6 +397,6 @@ public final class ProtobufProtocol {
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
}
public static void internalForceInit() {}
}

View file

@ -12,9 +12,9 @@ object ActorFireForgetRequestReplySpec {
self.dispatcher = Dispatchers.newThreadBasedDispatcher(self)
def receive = {
case "Send" =>
case "Send" =>
self.reply("Reply")
case "SendImplicit" =>
case "SendImplicit" =>
self.sender.get ! "ReplyImplicit"
}
}
@ -34,7 +34,7 @@ object ActorFireForgetRequestReplySpec {
state.finished.await
}
}
}
}
object state {
var s = "NIL"
@ -51,7 +51,7 @@ class ActorFireForgetRequestReplySpec extends JUnitSuite {
val replyActor = actorOf[ReplyActor].start
val senderActor = actorOf(new SenderActor(replyActor)).start
senderActor ! "Init"
try { state.finished.await(1L, TimeUnit.SECONDS) }
try { state.finished.await(1L, TimeUnit.SECONDS) }
catch { case e: TimeoutException => fail("Never got the message") }
assert("Reply" === state.s)
}
@ -62,7 +62,7 @@ class ActorFireForgetRequestReplySpec extends JUnitSuite {
val replyActor = actorOf[ReplyActor].start
val senderActor = actorOf(new SenderActor(replyActor)).start
senderActor ! "InitImplicit"
try { state.finished.await(1L, TimeUnit.SECONDS) }
try { state.finished.await(1L, TimeUnit.SECONDS) }
catch { case e: TimeoutException => fail("Never got the message") }
assert("ReplyImplicit" === state.s)
}

View file

@ -19,7 +19,6 @@ class ActorPatternsTest extends junit.framework.TestCase with Suite with MustMat
import Patterns._
@Test def testDispatcher = {
val (testMsg1,testMsg2,testMsg3,testMsg4) = ("test1","test2","test3","test4")
val targetOk = new AtomicInteger(0)
val t1 = actorOf( new Actor() {
def receive = {
@ -82,8 +81,8 @@ class ActorPatternsTest extends junit.framework.TestCase with Suite with MustMat
t1ProcessedCount.get must be < (t2ProcessedCount.get) // because t1 is much slower and thus has a bigger mailbox all the time
for(a <- List(t1,t2,d)) a.stop
}
@Test def testListener = {
@Test def testListener = {
val latch = new CountDownLatch(2)
val num = new AtomicInteger(0)
val i = actorOf(new Actor with Listeners {
@ -92,17 +91,17 @@ class ActorPatternsTest extends junit.framework.TestCase with Suite with MustMat
}
})
i.start
def newListener = actor {
case "bar" =>
def newListener = actor {
case "bar" =>
num.incrementAndGet
latch.countDown
}
val a1 = newListener
val a2 = newListener
val a3 = newListener
i ! Listen(a1)
i ! Listen(a2)
i ! Listen(a3)
@ -115,4 +114,4 @@ class ActorPatternsTest extends junit.framework.TestCase with Suite with MustMat
num.get must be (2)
for(a <- List(i,a1,a2,a3)) a.stop
}
}
}

View file

@ -13,12 +13,12 @@ object ActorRegistrySpec {
record = "pong" + record
self.reply("got ping")
}
}
}
}
class ActorRegistrySpec extends JUnitSuite {
import ActorRegistrySpec._
@Test def shouldGetActorByIdFromActorRegistry {
ActorRegistry.shutdownAll
val actor = actorOf[TestActor]

View file

@ -88,7 +88,7 @@ class AgentSpec extends junit.framework.TestCase with Suite with MustMatchers {
result must be(4)
agent1.close
}
@Test def testAgentMap = {
val agent1 = Agent(3)
val result = for (first <- agent1) yield first + 1

View file

@ -20,4 +20,4 @@ class ActorUtilTest extends junit.framework.TestCase with Suite with MustMatcher
val done = latch.await(5,TimeUnit.SECONDS)
done must be (true)
}
}
}

View file

@ -13,7 +13,7 @@ import Actor._
case class Send(actor: Actor)
object RemoteActorSpecActorUnidirectional {
val latch = new CountDownLatch(1)
val latch = new CountDownLatch(1)
}
class RemoteActorSpecActorUnidirectional extends Actor {
self.dispatcher = Dispatchers.newThreadBasedDispatcher(self)

View file

@ -17,19 +17,19 @@ object ExecutorBasedEventDrivenDispatcherActorSpec {
}
}
object OneWayTestActor {
val oneWay = new CountDownLatch(1)
object OneWayTestActor {
val oneWay = new CountDownLatch(1)
}
class OneWayTestActor extends Actor {
self.dispatcher = Dispatchers.newExecutorBasedEventDrivenDispatcher(self.uuid)
def receive = {
case "OneWay" => OneWayTestActor.oneWay.countDown
}
}
}
}
class ExecutorBasedEventDrivenDispatcherActorSpec extends JUnitSuite {
import ExecutorBasedEventDrivenDispatcherActorSpec._
private val unit = TimeUnit.MILLISECONDS
@Test def shouldSendOneWay = {

View file

@ -39,7 +39,7 @@ class ExecutorBasedEventDrivenDispatcherActorsSpec extends JUnitSuite with MustM
val fFinished = new CountDownLatch(10)
val s = actorOf(new SlowActor(sFinished)).start
val f = actorOf(new FastActor(fFinished)).start
// send a lot of stuff to s
for (i <- 1 to 50) {
s ! i

View file

@ -10,7 +10,7 @@ import Actor._
import java.util.concurrent.{TimeUnit, CountDownLatch}
object ExecutorBasedEventDrivenWorkStealingDispatcherSpec {
object ExecutorBasedEventDrivenWorkStealingDispatcherSpec {
val delayableActorDispatcher = Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher("pooled-dispatcher")
val sharedActorDispatcher = Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher("pooled-dispatcher")
val parentActorDispatcher = Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher("pooled-dispatcher")
@ -28,7 +28,7 @@ object ExecutorBasedEventDrivenWorkStealingDispatcherSpec {
}
}
}
class FirstActor extends Actor {
self.dispatcher = sharedActorDispatcher
def receive = {case _ => {}}
@ -53,7 +53,7 @@ object ExecutorBasedEventDrivenWorkStealingDispatcherSpec {
*/
class ExecutorBasedEventDrivenWorkStealingDispatcherSpec extends JUnitSuite with MustMatchers {
import ExecutorBasedEventDrivenWorkStealingDispatcherSpec._
@Test def fastActorShouldStealWorkFromSlowActor {
val finishedCounter = new CountDownLatch(110)
@ -78,12 +78,12 @@ class ExecutorBasedEventDrivenWorkStealingDispatcherSpec extends JUnitSuite with
}
finishedCounter.await(5, TimeUnit.SECONDS)
fast.actor.asInstanceOf[DelayableActor].invocationCount must be >
fast.actor.asInstanceOf[DelayableActor].invocationCount must be >
(slow.actor.asInstanceOf[DelayableActor].invocationCount)
slow.stop
fast.stop
}
@Test def canNotUseActorsOfDifferentTypesInSameDispatcher: Unit = {
val first = actorOf[FirstActor]
val second = actorOf[SecondActor]

View file

@ -52,12 +52,12 @@ object ForwardActorSpec {
def receive = {
case _ => {}
}
}
}
}
class ForwardActorSpec extends JUnitSuite {
import ForwardActorSpec._
@Test
def shouldForwardActorReferenceWhenInvokingForwardOnBang {
val senderActor = actorOf[BangSenderActor]
@ -76,6 +76,6 @@ class ForwardActorSpec extends JUnitSuite {
val senderActor = actorOf[BangBangSenderActor]
senderActor.start
val latch = senderActor.actor.asInstanceOf[BangBangSenderActor].latch
assert(latch.await(1L, TimeUnit.SECONDS))
assert(latch.await(1L, TimeUnit.SECONDS))
}
}

View file

@ -14,12 +14,12 @@ object FutureSpec {
case "Failure" =>
throw new RuntimeException("expected")
}
}
}
}
class FutureSpec extends JUnitSuite {
import FutureSpec._
@Test def shouldActorReplyResultThroughExplicitFuture {
val actor = actorOf[TestActor]
actor.start

View file

@ -32,7 +32,7 @@ import InMemoryActorSpec._
class InMemStatefulActor(expectedInvocationCount: Int) extends Transactor {
def this() = this(0)
self.timeout = 5000
val notifier = new CountDownLatch(expectedInvocationCount)
private lazy val mapState = TransactionalState.newMap[String, String]
@ -102,7 +102,7 @@ class InMemStatefulActor(expectedInvocationCount: Int) extends Transactor {
@serializable
class InMemFailerActor extends Transactor {
def receive = {
case "Failure" =>
throw new RuntimeException("expected")

View file

@ -21,7 +21,7 @@ case class User(val usernamePassword: Tuple2[String, String],
val age: Int)
extends Serializable.SBinary[User] {
def this() = this(null, null, 0)
import sbinary.DefaultProtocol._
import sbinary.DefaultProtocol._
implicit object UserFormat extends Format[User] {
def reads(in : Input) = User(
read[Tuple2[String, String]](in),

View file

@ -68,4 +68,4 @@ class ProtobufActorMessageSerializationSpec extends JUnitSuite {
actor.stop
}
}

View file

@ -19,20 +19,20 @@ object ReactorBasedSingleThreadEventDrivenDispatcherActorSpec {
}
}
object OneWayTestActor {
val oneWay = new CountDownLatch(1)
object OneWayTestActor {
val oneWay = new CountDownLatch(1)
}
class OneWayTestActor extends Actor {
self.dispatcher = Dispatchers.newExecutorBasedEventDrivenDispatcher(self.uuid)
def receive = {
case "OneWay" => OneWayTestActor.oneWay.countDown
}
}
}
}
class ReactorBasedSingleThreadEventDrivenDispatcherActorSpec extends JUnitSuite {
import ReactorBasedSingleThreadEventDrivenDispatcherActorSpec._
private val unit = TimeUnit.MILLISECONDS
@Test def shouldSendOneWay = {

View file

@ -16,7 +16,7 @@ object ReactorBasedThreadPoolEventDrivenDispatcherActorSpec {
case "Failure" =>
throw new RuntimeException("expected")
}
}
}
}
class ReactorBasedThreadPoolEventDrivenDispatcherActorSpec extends JUnitSuite {

View file

@ -353,7 +353,7 @@ class RemoteSupervisorSpec extends JUnitSuite {
}
/*
@Test def shouldOneWayKillSingleActorOneForOne = {
clearMessageLogs
val sup = getSingleActorOneForOneSupervisor

View file

@ -27,4 +27,4 @@ class SchedulerSpec extends JUnitSuite {
*/
assert(true)
}
}
}

View file

@ -25,7 +25,7 @@ object ServerInitiatedRemoteActorServer {
}
object ServerInitiatedRemoteActorClient extends Logging {
def run = {
val actor = RemoteClient.actorFor("hello-service", "localhost", 9999)
val result = actor !! "Hello"

View file

@ -12,7 +12,7 @@ object ServerInitiatedRemoteActorSpec {
val HOSTNAME = "localhost"
val PORT = 9990
var server: RemoteServer = null
case class Send(actor: ActorRef)
object RemoteActorSpecActorUnidirectional {
@ -135,4 +135,4 @@ class ServerInitiatedRemoteActorSpec extends JUnitSuite {
actor.stop
}
}

View file

@ -21,7 +21,7 @@ object SupervisorSpec {
messageLog.clear
oneWayLog.clear
}
class PingPong1Actor extends Actor {
import self._
//dispatcher = Dispatchers.newThreadBasedDispatcher(self)
@ -82,7 +82,7 @@ object SupervisorSpec {
*/
class SupervisorSpec extends JUnitSuite {
import SupervisorSpec._
var pingpong1: ActorRef = _
var pingpong2: ActorRef = _
var pingpong3: ActorRef = _
@ -110,7 +110,7 @@ class SupervisorSpec extends JUnitSuite {
@Test def shouldKillSingleActorOneForOne = {
clearMessageLogs
val sup = getSingleActorOneForOneSupervisor
intercept[RuntimeException] {
pingpong1 !! (Die, 5000)
}
@ -123,7 +123,7 @@ class SupervisorSpec extends JUnitSuite {
@Test def shouldCallKillCallSingleActorOneForOne = {
clearMessageLogs
val sup = getSingleActorOneForOneSupervisor
expect("pong") {
(pingpong1 !! (Ping, 5000)).getOrElse("nil")
}
@ -150,7 +150,7 @@ class SupervisorSpec extends JUnitSuite {
@Test def shouldKillSingleActorAllForOne = {
clearMessageLogs
val sup = getSingleActorAllForOneSupervisor
intercept[RuntimeException] {
pingpong1 !! (Die, 5000)
}
@ -163,7 +163,7 @@ class SupervisorSpec extends JUnitSuite {
@Test def shouldCallKillCallSingleActorAllForOne = {
clearMessageLogs
val sup = getSingleActorAllForOneSupervisor
expect("pong") {
(pingpong1 !! (Ping, 5000)).getOrElse("nil")
}
@ -190,7 +190,7 @@ class SupervisorSpec extends JUnitSuite {
@Test def shouldKillMultipleActorsOneForOne1 = {
clearMessageLogs
val sup = getMultipleActorsOneForOneConf
intercept[RuntimeException] {
pingpong1 !! (Die, 5000)
}
@ -203,7 +203,7 @@ class SupervisorSpec extends JUnitSuite {
@Test def shouldKillMultipleActorsOneForOne2 = {
clearMessageLogs
val sup = getMultipleActorsOneForOneConf
intercept[RuntimeException] {
pingpong3 !! (Die, 5000)
}
@ -216,7 +216,7 @@ class SupervisorSpec extends JUnitSuite {
@Test def shouldKillCallMultipleActorsOneForOne = {
clearMessageLogs
val sup = getMultipleActorsOneForOneConf
expect("pong") {
(pingpong1 !! (Ping, 5000)).getOrElse("nil")
}
@ -271,7 +271,7 @@ class SupervisorSpec extends JUnitSuite {
@Test def shouldKillMultipleActorsAllForOne = {
clearMessageLogs
val sup = getMultipleActorsAllForOneConf
intercept[RuntimeException] {
pingpong2 !! (Die, 5000)
}
@ -290,7 +290,7 @@ class SupervisorSpec extends JUnitSuite {
@Test def shouldCallKillCallMultipleActorsAllForOne = {
clearMessageLogs
val sup = getMultipleActorsAllForOneConf
expect("pong") {
(pingpong1 !! (Ping, 5000)).getOrElse("nil")
}
@ -351,7 +351,7 @@ class SupervisorSpec extends JUnitSuite {
@Test def shouldOneWayKillSingleActorOneForOne = {
clearMessageLogs
val sup = getSingleActorOneForOneSupervisor
pingpong1 ! Die
expect("DIE") {
@ -362,7 +362,7 @@ class SupervisorSpec extends JUnitSuite {
@Test def shouldOneWayCallKillCallSingleActorOneForOne = {
clearMessageLogs
val sup = getSingleActorOneForOneSupervisor
pingpong1 ! OneWay
expect("oneway") {
@ -374,7 +374,7 @@ class SupervisorSpec extends JUnitSuite {
messageLog.poll(5, TimeUnit.SECONDS)
}
pingpong1 ! OneWay
expect("oneway") {
oneWayLog.poll(5, TimeUnit.SECONDS)
}
@ -383,7 +383,7 @@ class SupervisorSpec extends JUnitSuite {
@Test def shouldRestartKilledActorsForNestedSupervisorHierarchy = {
clearMessageLogs
val sup = getNestedSupervisorsAllForOneConf
expect("pong") {
(pingpong1 !! (Ping, 5000)).getOrElse("nil")

View file

@ -10,19 +10,19 @@ import Actor._
object ThreadBasedActorSpec {
class TestActor extends Actor {
self.dispatcher = Dispatchers.newThreadBasedDispatcher(self)
def receive = {
case "Hello" =>
self.reply("World")
case "Failure" =>
throw new RuntimeException("expected")
}
}
}
}
class ThreadBasedActorSpec extends JUnitSuite {
import ThreadBasedActorSpec._
private val unit = TimeUnit.MILLISECONDS
@Test def shouldSendOneWay {

View file

@ -19,7 +19,7 @@ class ThreadBasedDispatcherSpec extends JUnitSuite {
val key1 = actorOf(new Actor { def receive = { case _ => {}} })
val key2 = actorOf(new Actor { def receive = { case _ => {}} })
val key3 = actorOf(new Actor { def receive = { case _ => {}} })
class TestMessageHandle(handleLatch: CountDownLatch) extends MessageInvoker {
val guardLock: Lock = new ReentrantLock
@ -88,4 +88,4 @@ class ThreadBasedDispatcherSpec extends JUnitSuite {
dispatcher.shutdown
}
}
*/
*/

View file

@ -87,15 +87,15 @@ class TransactionalRefSpec extends Spec with ShouldMatchers {
val value1 = atomic { ref1.get.get }
val value2 = atomic { ref2.get.get }
value1 should be(1)
value2 should be(2)
}
it("should be able to be used in a 'foreach' for comprehension") {
val ref = Ref(3)
var result = 0
var result = 0
atomic {
for (value <- ref) {
@ -133,7 +133,7 @@ class TransactionalRefSpec extends Spec with ShouldMatchers {
value3 should be(3)
}
it("should be able to be used in a 'filter' for comprehension") {
val ref1 = Ref(1)
@ -142,7 +142,7 @@ class TransactionalRefSpec extends Spec with ShouldMatchers {
}
val optLess2 = atomic { refLess2.get }
val refGreater2 = atomic {
for (value <- ref1 if value > 2) yield value
}

View file

@ -1 +1 @@
se.scalablesolutions.akka.rest.ListWriter
se.scalablesolutions.akka.rest.ListWriter

View file

@ -13,7 +13,7 @@ import se.scalablesolutions.akka.actor.Actor
class ActorComponentProvider(val clazz: Class[_], val configurators: List[Configurator])
extends IoCFullyManagedComponentProvider with Logging {
override def getScope = ComponentScope.Singleton
override def getInstance: AnyRef = {
@ -26,4 +26,4 @@ class ActorComponentProvider(val clazz: Class[_], val configurators: List[Config
"No Actor or Active Object for class [" + clazz + "] could be found.\nMake sure you have defined and configured the class as an Active Object or Actor in a supervisor hierarchy.")
else instances.head.asInstanceOf[AnyRef]
}
}
}

View file

@ -9,15 +9,15 @@ import se.scalablesolutions.akka.actor.Actor._
class AkkaBroadcaster extends org.atmosphere.jersey.JerseyBroadcaster {
name = classOf[AkkaBroadcaster].getName
val caster = actor { case f : Function0[_] => f() }
override def destroy {
super.destroy
caster.stop
}
protected override def broadcast(r : AtmosphereResource[_,_], e : AtmosphereResourceEvent[_,_]) = {
caster ! (() => super.broadcast(r,e))
}
}
}

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2010 Scalable Solutions AB <http://scalablesolutions.se>
*/
package se.scalablesolutions.akka.comet
import se.scalablesolutions.akka.actor.Actor
@ -24,8 +24,8 @@ class AkkaClusterBroadcastFilter extends Actor with ClusterBroadcastFilter[AnyRe
@BeanProperty var clusterName = ""
@BeanProperty var broadcaster : Broadcaster = null
/**
* Stops the actor
/**
* Stops the actor
*/
def destroy: Unit = self.stop
@ -36,14 +36,14 @@ class AkkaClusterBroadcastFilter extends Actor with ClusterBroadcastFilter[AnyRe
*/
def filter(o : AnyRef) = new BroadcastFilter.BroadcastAction(o match {
case ClusterCometBroadcast(_,m) => m //Do not re-broadcast, just unbox and pass along
case m : AnyRef => { //Relay message to the cluster and pass along
Cluster.relayMessage(classOf[AkkaClusterBroadcastFilter],ClusterCometBroadcast(clusterName,m))
m
}
})
def receive = {
def receive = {
//Only handle messages intended for this particular instance
case b @ ClusterCometBroadcast(c, _) if (c == clusterName) && (broadcaster ne null) => broadcaster broadcast b
case _ =>
@ -51,4 +51,4 @@ class AkkaClusterBroadcastFilter extends Actor with ClusterBroadcastFilter[AnyRe
//Since this class is instantiated by Atmosphere, we need to make sure it's started
self.start
}
}

View file

@ -60,7 +60,7 @@ class AkkaServlet extends org.atmosphere.cpr.AtmosphereServlet with Logging {
*/
override def createCometSupportResolver() : CometSupportResolver = {
import scala.collection.JavaConversions._
new DefaultCometSupportResolver(config) {
type CS = CometSupport[_ <: AtmosphereResource[_,_]]
override def resolveMultipleNativeSupportConflict(available : JList[Class[_ <: CS]]) : CS = {
@ -70,7 +70,7 @@ class AkkaServlet extends org.atmosphere.cpr.AtmosphereServlet with Logging {
case _ => super.resolveMultipleNativeSupportConflict(available)
}
}
override def resolve(useNativeIfPossible : Boolean, useBlockingAsDefault : Boolean) : CS = {
val predef = config.getInitParameter("cometSupport")
if (testClassExists(predef)) newCometSupport(predef)

View file

@ -14,7 +14,7 @@ class AkkaLoader extends Logging {
@volatile private var hasBooted = false
@volatile private var _bundles: Option[Bootable] = None
def bundles = _bundles;
/*
@ -58,4 +58,4 @@ class AkkaLoader extends Logging {
log.info(" Running version %s", Config.VERSION)
log.info("==============================")
}
}
}

View file

@ -30,4 +30,4 @@ class AkkaServlet extends ServletContainer {
webApplication.initiate(resourceConfig, new ActorComponentProviderFactory(configurators))
}
}
}

View file

@ -11,7 +11,7 @@ import se.scalablesolutions.akka.config.Config
import se.scalablesolutions.akka.util.{Logging, Bootable}
import javax.servlet.{ServletContextListener, ServletContextEvent}
/**
* This class can be added to web.xml mappings as a listener to start and shutdown Akka.
*
@ -22,13 +22,13 @@ import javax.servlet.{ServletContextListener, ServletContextEvent}
* </listener>
* ...
*</web-app>
*/
*/
class Initializer extends ServletContextListener {
lazy val loader = new AkkaLoader
def contextDestroyed(e: ServletContextEvent): Unit =
def contextDestroyed(e: ServletContextEvent): Unit =
loader.shutdown
def contextInitialized(e: ServletContextEvent): Unit =
def contextInitialized(e: ServletContextEvent): Unit =
loader.boot(true, new BootableActorLoaderService with BootableRemoteActorService with CamelService)
}
}

View file

@ -103,9 +103,11 @@ class AkkaSecurityFilterFactory extends ResourceFilterFactory with Logging {
}
}
lazy val authenticatorFQN =
Config.config.getString("akka.rest.authenticator")
.getOrElse(throw new IllegalStateException("akka.rest.authenticator"))
lazy val authenticatorFQN = {
val auth = Config.config.getString("akka.rest.authenticator", "N/A")
if (auth == "N/A") throw new IllegalStateException("The config option 'akka.rest.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
@ -399,19 +401,31 @@ trait SpnegoAuthenticationActor extends AuthenticationActor[SpnegoCredentials] w
/**
* principal name for the HTTP kerberos service, i.e HTTP/ { server } @ { realm }
*/
lazy val servicePrincipal = Config.config.getString("akka.rest.kerberos.servicePrincipal").getOrElse(throw new IllegalStateException("akka.rest.kerberos.servicePrincipal"))
lazy val servicePrincipal = {
val p = Config.config.getString("akka.rest.kerberos.servicePrincipal", "N/A")
if (p == "N/A") throw new IllegalStateException("The config option 'akka.rest.kerberos.servicePrincipal' is not defined in 'akka.conf'")
p
}
/**
* keytab location with credentials for the service principal
*/
lazy val keyTabLocation = Config.config.getString("akka.rest.kerberos.keyTabLocation").getOrElse(throw new IllegalStateException("akka.rest.kerberos.keyTabLocation"))
lazy val keyTabLocation = {
val p = Config.config.getString("akka.rest.kerberos.keyTabLocation", "N/A")
if (p == "N/A") throw new IllegalStateException("The config option 'akka.rest.kerberos.keyTabLocation' is not defined in 'akka.conf'")
p
}
lazy val kerberosDebug = Config.config.getString("akka.rest.kerberos.kerberosDebug").getOrElse("false")
lazy val kerberosDebug = {
val p = Config.config.getString("akka.rest.kerberos.kerberosDebug", "N/A")
if (p == "N/A") throw new IllegalStateException("The config option 'akka.rest.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.rest.kerberos.realm").getOrElse("")
lazy val realm = Config.config.getString("akka.rest.kerberos.realm", "")
/**
* verify the kerberos token from a client with the server

View file

@ -12,4 +12,4 @@ object AllTest extends TestCase {
}
def main(args: Array[String]) = junit.textui.TestRunner.run(suite)
}
}

Some files were not shown because too many files have changed in this diff Show more