Merge pull request #1033 from akka/wip-def-if-patriknw

Style change of def starting with if
This commit is contained in:
Patrik Nordwall 2013-01-18 04:30:43 -08:00
commit db5da848c0
25 changed files with 268 additions and 241 deletions

View file

@ -80,21 +80,21 @@ object ActorModelSpec {
} }
def receive = { def receive = {
case AwaitLatch(latch) ack; latch.await(); busy.switchOff() case AwaitLatch(latch) { ack; latch.await(); busy.switchOff() }
case Meet(sign, wait) ack; sign.countDown(); wait.await(); busy.switchOff() case Meet(sign, wait) { ack; sign.countDown(); wait.await(); busy.switchOff() }
case Wait(time) ack; Thread.sleep(time); busy.switchOff() case Wait(time) { ack; Thread.sleep(time); busy.switchOff() }
case WaitAck(time, l) ack; Thread.sleep(time); l.countDown(); busy.switchOff() case WaitAck(time, l) { ack; Thread.sleep(time); l.countDown(); busy.switchOff() }
case Reply(msg) ack; sender ! msg; busy.switchOff() case Reply(msg) { ack; sender ! msg; busy.switchOff() }
case TryReply(msg) ack; sender.tell(msg, null); busy.switchOff() case TryReply(msg) { ack; sender.tell(msg, null); busy.switchOff() }
case Forward(to, msg) ack; to.forward(msg); busy.switchOff() case Forward(to, msg) { ack; to.forward(msg); busy.switchOff() }
case CountDown(latch) ack; latch.countDown(); busy.switchOff() case CountDown(latch) { ack; latch.countDown(); busy.switchOff() }
case Increment(count) ack; count.incrementAndGet(); busy.switchOff() case Increment(count) { ack; count.incrementAndGet(); busy.switchOff() }
case CountDownNStop(l) ack; l.countDown(); context.stop(self); busy.switchOff() case CountDownNStop(l) { ack; l.countDown(); context.stop(self); busy.switchOff() }
case Restart ack; busy.switchOff(); throw new Exception("Restart requested") case Restart { ack; busy.switchOff(); throw new Exception("Restart requested") }
case Interrupt ack; sender ! Status.Failure(new ActorInterruptedException(new InterruptedException("Ping!"))); busy.switchOff(); throw new InterruptedException("Ping!") case Interrupt { ack; sender ! Status.Failure(new ActorInterruptedException(new InterruptedException("Ping!"))); busy.switchOff(); throw new InterruptedException("Ping!") }
case InterruptNicely(msg) ack; sender ! msg; busy.switchOff(); Thread.currentThread().interrupt() case InterruptNicely(msg) { ack; sender ! msg; busy.switchOff(); Thread.currentThread().interrupt() }
case ThrowException(e: Throwable) ack; busy.switchOff(); throw e case ThrowException(e: Throwable) { ack; busy.switchOff(); throw e }
case DoubleStop ack; context.stop(self); context.stop(self); busy.switchOff case DoubleStop { ack; context.stop(self); context.stop(self); busy.switchOff }
} }
} }
@ -229,7 +229,8 @@ object ActorModelSpec {
} }
} }
@tailrec def await(until: Long)(condition: Boolean): Unit = if (System.currentTimeMillis() <= until) { @tailrec def await(until: Long)(condition: Boolean): Unit =
if (System.currentTimeMillis() <= until) {
var done = false var done = false
try { try {
done = condition done = condition

View file

@ -402,7 +402,8 @@ private[akka] class ActorCell(
checkReceiveTimeout // Reschedule receive timeout checkReceiveTimeout // Reschedule receive timeout
} }
def autoReceiveMessage(msg: Envelope): Unit = if (msg.message != NullMessage) { def autoReceiveMessage(msg: Envelope): Unit =
if (msg.message != NullMessage) {
if (system.settings.DebugAutoReceive) if (system.settings.DebugAutoReceive)
publish(Debug(self.path.toString, clazz(actor), "received AutoReceiveMessage " + msg)) publish(Debug(self.path.toString, clazz(actor), "received AutoReceiveMessage " + msg))
@ -507,7 +508,8 @@ private[akka] class ActorCell(
} }
} }
private def supervise(child: ActorRef, async: Boolean, uid: Int): Unit = if (!isTerminating) { private def supervise(child: ActorRef, async: Boolean, uid: Int): Unit =
if (!isTerminating) {
// Supervise is the first thing we get from a new child, so store away the UID for later use in handleFailure() // Supervise is the first thing we get from a new child, so store away the UID for later use in handleFailure()
initChild(child) match { initChild(child) match {
case Some(crs) case Some(crs)

View file

@ -382,7 +382,7 @@ class LocalActorRefProvider(
override def isTerminated: Boolean = stopped.isOn override def isTerminated: Boolean = stopped.isOn
override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = stopped.ifOff(message match { override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = stopped.ifOff(message match {
case Failed(ex, _) if sender ne null causeOfTermination = Some(ex); sender.asInstanceOf[InternalActorRef].stop() case Failed(ex, _) if sender ne null { causeOfTermination = Some(ex); sender.asInstanceOf[InternalActorRef].stop() }
case NullMessage // do nothing case NullMessage // do nothing
case _ log.error(this + " received unexpected message [" + message + "]") case _ log.error(this + " received unexpected message [" + message + "]")
}) })
@ -449,7 +449,8 @@ class LocalActorRefProvider(
stopWhenAllTerminationHooksDone() stopWhenAllTerminationHooksDone()
} }
def stopWhenAllTerminationHooksDone(): Unit = if (terminationHooks.isEmpty) { def stopWhenAllTerminationHooksDone(): Unit =
if (terminationHooks.isEmpty) {
eventStream.stopDefaultLoggers() eventStream.stopDefaultLoggers()
context.stop(self) context.stop(self)
} }

View file

@ -97,7 +97,8 @@ object FSM {
if (repeat) scheduler.schedule(timeout, timeout, actor, this) if (repeat) scheduler.schedule(timeout, timeout, actor, this)
else scheduler.scheduleOnce(timeout, actor, this)) else scheduler.scheduleOnce(timeout, actor, this))
def cancel(): Unit = if (ref.isDefined) { def cancel(): Unit =
if (ref.isDefined) {
ref.get.cancel() ref.get.cancel()
ref = None ref = None
} }

View file

@ -40,7 +40,8 @@ private[akka] trait DeathWatch { this: ActorCell ⇒
* When this actor is watching the subject of [[akka.actor.Terminated]] message * When this actor is watching the subject of [[akka.actor.Terminated]] message
* it will be propagated to user's receive. * it will be propagated to user's receive.
*/ */
protected def watchedActorTerminated(t: Terminated): Unit = if (watching.contains(t.actor)) { protected def watchedActorTerminated(t: Terminated): Unit =
if (watching.contains(t.actor)) {
maintainAddressTerminatedSubscription(t.actor) { maintainAddressTerminatedSubscription(t.actor) {
watching -= t.actor watching -= t.actor
} }

View file

@ -150,7 +150,8 @@ private[akka] object MessageDispatcher {
// since this is a compile-time constant, scalac will elide code behind if (MessageDispatcher.debug) (RK checked with 2.9.1) // since this is a compile-time constant, scalac will elide code behind if (MessageDispatcher.debug) (RK checked with 2.9.1)
final val debug = false // Deliberately without type ascription to make it a compile-time constant final val debug = false // Deliberately without type ascription to make it a compile-time constant
lazy val actors = new Index[MessageDispatcher, ActorRef](16, _ compareTo _) lazy val actors = new Index[MessageDispatcher, ActorRef](16, _ compareTo _)
def printActors: Unit = if (debug) { def printActors: Unit =
if (debug) {
for { for {
d actors.keys d actors.keys
a { println(d + " inhabitants: " + d.inhabitants); actors.valueIterator(d) } a { println(d + " inhabitants: " + d.inhabitants); actors.valueIterator(d) }

View file

@ -85,7 +85,8 @@ class BalancingDispatcher(
if (!registerForExecution(receiver.mailbox, false, false)) teamWork() if (!registerForExecution(receiver.mailbox, false, false)) teamWork()
} }
protected def teamWork(): Unit = if (attemptTeamWork) { protected def teamWork(): Unit =
if (attemptTeamWork) {
@tailrec def scheduleOne(i: Iterator[ActorCell] = team.iterator): Unit = @tailrec def scheduleOne(i: Iterator[ActorCell] = team.iterator): Unit =
if (messageQueue.hasMessages if (messageQueue.hasMessages
&& i.hasNext && i.hasNext

View file

@ -285,7 +285,8 @@ class BoundedBlockingQueue[E <: AnyRef](
last = -1 //To avoid 2 subsequent removes without a next in between last = -1 //To avoid 2 subsequent removes without a next in between
lock.lock() lock.lock()
try { try {
@tailrec def removeTarget(i: Iterator[E] = backing.iterator()): Unit = if (i.hasNext) { @tailrec def removeTarget(i: Iterator[E] = backing.iterator()): Unit =
if (i.hasNext) {
if (i.next eq target) { if (i.next eq target) {
i.remove() i.remove()
notFull.signal() notFull.signal()

View file

@ -252,7 +252,8 @@ object ByteIterator {
normalize() normalize()
} }
@tailrec final override def drop(n: Int): this.type = if ((n > 0) && !isEmpty) { @tailrec final override def drop(n: Int): this.type =
if ((n > 0) && !isEmpty) {
val nCurrent = math.min(n, current.len) val nCurrent = math.min(n, current.len)
current.drop(n) current.drop(n)
val rest = n - nCurrent val rest = n - nCurrent
@ -275,7 +276,8 @@ object ByteIterator {
normalize() normalize()
} }
@tailrec final override def dropWhile(p: Byte Boolean): this.type = if (!isEmpty) { @tailrec final override def dropWhile(p: Byte Boolean): this.type =
if (!isEmpty) {
current.dropWhile(p) current.dropWhile(p)
val dropMore = current.isEmpty val dropMore = current.isEmpty
normalize() normalize()
@ -309,7 +311,8 @@ object ByteIterator {
} }
} }
@tailrec protected final def getToArray[A](xs: Array[A], offset: Int, n: Int, elemSize: Int)(getSingle: A)(getMult: (Array[A], Int, Int) Unit): this.type = if (n <= 0) this else { @tailrec protected final def getToArray[A](xs: Array[A], offset: Int, n: Int, elemSize: Int)(getSingle: A)(getMult: (Array[A], Int, Int) Unit): this.type =
if (n <= 0) this else {
if (isEmpty) Iterator.empty.next if (isEmpty) Iterator.empty.next
val nDone = if (current.len >= elemSize) { val nDone = if (current.len >= elemSize) {
val nCurrent = math.min(n, current.len / elemSize) val nCurrent = math.min(n, current.len / elemSize)
@ -359,7 +362,8 @@ object ByteIterator {
} }
override def skip(n: Long): Long = { override def skip(n: Long): Long = {
@tailrec def skipImpl(n: Long, skipped: Long): Long = if (n > 0) { @tailrec def skipImpl(n: Long, skipped: Long): Long =
if (n > 0) {
if (!isEmpty) { if (!isEmpty) {
val m = current.asInputStream.skip(n) val m = current.asInputStream.skip(n)
normalize() normalize()

View file

@ -38,7 +38,8 @@ private[akka] object Collections {
} else hasNext //Attempt to find the next } else hasNext //Attempt to find the next
} else _hasNext // Return if we found one } else _hasNext // Return if we found one
override final def next(): To = if (hasNext) { override final def next(): To =
if (hasNext) {
val ret = _next val ret = _next
_next = null.asInstanceOf[To] // Mark as consumed (nice to the GC, don't leak the last returned value) _next = null.asInstanceOf[To] // Mark as consumed (nice to the GC, don't leak the last returned value)
_hasNext = false // Mark as consumed (we need to look for the next value) _hasNext = false // Mark as consumed (we need to look for the next value)

View file

@ -803,7 +803,8 @@ private[cluster] final class ClusterCoreDaemon(publisher: ActorRef) extends Acto
def oneWayGossipTo(address: Address): Unit = def oneWayGossipTo(address: Address): Unit =
gossipTo(address, GossipEnvelope(selfAddress, latestGossip, conversation = false)) gossipTo(address, GossipEnvelope(selfAddress, latestGossip, conversation = false))
def gossipTo(address: Address, gossipMsg: GossipEnvelope): Unit = if (address != selfAddress) def gossipTo(address: Address, gossipMsg: GossipEnvelope): Unit =
if (address != selfAddress)
coreSender ! SendClusterMessage(address, gossipMsg) coreSender ! SendClusterMessage(address, gossipMsg)
def publish(newGossip: Gossip): Unit = { def publish(newGossip: Gossip): Unit = {

View file

@ -143,17 +143,14 @@ private[cluster] final class ClusterHeartbeatSender extends Actor with ActorLogg
case ExpectedFirstHeartbeat(from) triggerFirstHeartbeat(from) case ExpectedFirstHeartbeat(from) triggerFirstHeartbeat(from)
} }
def reset(snapshot: InstantClusterState): Unit = def reset(snapshot: InstantClusterState): Unit = state = state.reset(snapshot.members.map(_.address))
state = state.reset(snapshot.members.map(_.address))
def addMember(m: Member): Unit = if (m.address != selfAddress) def addMember(m: Member): Unit = if (m.address != selfAddress) state = state addMember m.address
state = state addMember m.address
def removeMember(m: Member): Unit = if (m.address != selfAddress) def removeMember(m: Member): Unit = if (m.address != selfAddress) state = state removeMember m.address
state = state removeMember m.address
def addHeartbeatRequest(address: Address): Unit = if (address != selfAddress) def addHeartbeatRequest(address: Address): Unit =
state = state.addHeartbeatRequest(address, Deadline.now + HeartbeatRequestTimeToLive) if (address != selfAddress) state = state.addHeartbeatRequest(address, Deadline.now + HeartbeatRequestTimeToLive)
def sendHeartbeatRequest(address: Address): Unit = def sendHeartbeatRequest(address: Address): Unit =
if (!cluster.failureDetector.isMonitoring(address) && state.ring.mySenders.contains(address)) { if (!cluster.failureDetector.isMonitoring(address) && state.ring.mySenders.contains(address)) {

View file

@ -307,7 +307,8 @@ case class Metric private (name: String, value: Number, private val average: Opt
* If defined ( [[akka.cluster.MetricNumericConverter.defined()]] ), updates the new * If defined ( [[akka.cluster.MetricNumericConverter.defined()]] ), updates the new
* data point, and if defined, updates the data stream. Returns the updated metric. * data point, and if defined, updates the data stream. Returns the updated metric.
*/ */
def :+(latest: Metric): Metric = if (this sameAs latest) average match { def :+(latest: Metric): Metric =
if (this sameAs latest) average match {
case Some(avg) copy(value = latest.value, average = Some(avg :+ latest.value.doubleValue)) case Some(avg) copy(value = latest.value, average = Some(avg :+ latest.value.doubleValue))
case None if latest.average.isDefined copy(value = latest.value, average = latest.average) case None if latest.average.isDefined copy(value = latest.value, average = latest.average)
case _ copy(value = latest.value) case _ copy(value = latest.value)

View file

@ -143,8 +143,8 @@ private[akka] class ClusterReadView(cluster: Cluster) extends Closeable {
/** /**
* Unsubscribe to cluster events. * Unsubscribe to cluster events.
*/ */
def close(): Unit = if (!eventBusListener.isTerminated) { def close(): Unit =
if (!eventBusListener.isTerminated)
eventBusListener ! PoisonPill eventBusListener ! PoisonPill
}
} }

View file

@ -81,13 +81,13 @@ trait MultiNodeClusterSpec extends Suite with STMultiNodeSpec { self: MultiNodeS
} }
} }
def muteMarkingAsUnreachable(sys: ActorSystem = system): Unit = if (!sys.log.isDebugEnabled) { def muteMarkingAsUnreachable(sys: ActorSystem = system): Unit =
if (!sys.log.isDebugEnabled)
sys.eventStream.publish(Mute(EventFilter.error(pattern = ".*Marking.* as UNREACHABLE.*"))) sys.eventStream.publish(Mute(EventFilter.error(pattern = ".*Marking.* as UNREACHABLE.*")))
}
def muteDeadLetters(sys: ActorSystem = system): Unit = if (!sys.log.isDebugEnabled) { def muteDeadLetters(sys: ActorSystem = system): Unit =
if (!sys.log.isDebugEnabled)
sys.eventStream.publish(Mute(EventFilter.warning(pattern = ".*received dead letter from.*"))) sys.eventStream.publish(Mute(EventFilter.warning(pattern = ".*received dead letter from.*")))
}
override def afterAll(): Unit = { override def afterAll(): Unit = {
if (!log.isDebugEnabled) { if (!log.isDebugEnabled) {
@ -201,7 +201,8 @@ trait MultiNodeClusterSpec extends Suite with STMultiNodeSpec { self: MultiNodeS
* out of all nodes in the cluster. First * out of all nodes in the cluster. First
* member in the cluster ring is expected leader. * member in the cluster ring is expected leader.
*/ */
def assertLeaderIn(nodesInCluster: immutable.Seq[RoleName]): Unit = if (nodesInCluster.contains(myself)) { def assertLeaderIn(nodesInCluster: immutable.Seq[RoleName]): Unit =
if (nodesInCluster.contains(myself)) {
nodesInCluster.length must not be (0) nodesInCluster.length must not be (0)
val expectedLeader = roleOfLeader(nodesInCluster) val expectedLeader = roleOfLeader(nodesInCluster)
val leader = clusterView.leader val leader = clusterView.leader

View file

@ -435,7 +435,8 @@ object StressMultiJvmSpec extends MultiNodeConfig {
case RetryTick resend() case RetryTick resend()
} }
def done(replyTo: ActorRef): Unit = if (outstanding.isEmpty) { def done(replyTo: ActorRef): Unit =
if (outstanding.isEmpty) {
val duration = (System.nanoTime - startTime).nanos val duration = (System.nanoTime - startTime).nanos
replyTo ! WorkResult(duration, sendCounter, ackCounter) replyTo ! WorkResult(duration, sendCounter, ackCounter)
context stop self context stop self

View file

@ -125,7 +125,8 @@ trait Conductor { this: TestConductorExt ⇒
def blackhole(node: RoleName, target: RoleName, direction: Direction): Future[Done] = def blackhole(node: RoleName, target: RoleName, direction: Direction): Future[Done] =
throttle(node, target, direction, 0f) throttle(node, target, direction, 0f)
private def requireTestConductorTranport(): Unit = if (!transport.defaultAddress.protocol.contains(".gremlin.trttl.")) private def requireTestConductorTranport(): Unit =
if (!transport.defaultAddress.protocol.contains(".gremlin.trttl."))
throw new ConfigurationException("To use this feature you must activate the failure injector adapters " + throw new ConfigurationException("To use this feature you must activate the failure injector adapters " +
"(gremlin, trttl) by specifying `testTransport(on = true)` in your MultiNodeConfig.") "(gremlin, trttl) by specifying `testTransport(on = true)` in your MultiNodeConfig.")
@ -377,7 +378,7 @@ private[akka] class Controller(private var initialParticipants: Int, controllerP
case BarrierTimeout(data) failBarrier(data) case BarrierTimeout(data) failBarrier(data)
case FailedBarrier(data) failBarrier(data) case FailedBarrier(data) failBarrier(data)
case BarrierEmpty(data, msg) SupervisorStrategy.Resume case BarrierEmpty(data, msg) SupervisorStrategy.Resume
case WrongBarrier(name, client, data) client ! ToClient(BarrierResult(name, false)); failBarrier(data) case WrongBarrier(name, client, data) { client ! ToClient(BarrierResult(name, false)); failBarrier(data) }
case ClientLost(data, node) failBarrier(data) case ClientLost(data, node) failBarrier(data)
case DuplicateNode(data, node) failBarrier(data) case DuplicateNode(data, node) failBarrier(data)
} }

View file

@ -100,7 +100,8 @@ class LogRoleReplace {
def process(in: BufferedReader, out: PrintWriter): Unit = { def process(in: BufferedReader, out: PrintWriter): Unit = {
@tailrec @tailrec
def processLines(line: String): Unit = if (line ne null) { def processLines(line: String): Unit =
if (line ne null) {
out.println(processLine(line)) out.println(processLine(line))
processLines(in.readLine) processLines(in.readLine)
} }

View file

@ -298,7 +298,8 @@ private[remote] object EndpointManager {
endpoint endpoint
} }
def unregisterEndpoint(endpoint: ActorRef): Unit = if (isWritable(endpoint)) { def unregisterEndpoint(endpoint: ActorRef): Unit =
if (isWritable(endpoint)) {
val address = writableToAddress(endpoint) val address = writableToAddress(endpoint)
addressToWritable.get(address) match { addressToWritable.get(address) match {
case Some(policy) if policy.isTombstone // There is already a tombstone directive, leave it there case Some(policy) if policy.isTombstone // There is already a tombstone directive, leave it there
@ -328,7 +329,8 @@ private[remote] object EndpointManager {
case _ false case _ false
} }
def markAsFailed(endpoint: ActorRef, timeOfRelease: Deadline): Unit = if (isWritable(endpoint)) { def markAsFailed(endpoint: ActorRef, timeOfRelease: Deadline): Unit =
if (isWritable(endpoint)) {
addressToWritable += writableToAddress(endpoint) -> Gated(timeOfRelease) addressToWritable += writableToAddress(endpoint) -> Gated(timeOfRelease)
writableToAddress -= endpoint writableToAddress -= endpoint
} else if (isReadOnly(endpoint)) { } else if (isReadOnly(endpoint)) {

View file

@ -48,7 +48,8 @@ trait SchemeAugmenter {
protected def augmentScheme(address: Address): Address = address.copy(protocol = augmentScheme(address.protocol)) protected def augmentScheme(address: Address): Address = address.copy(protocol = augmentScheme(address.protocol))
protected def removeScheme(scheme: String): String = if (scheme.endsWith(s".$addedSchemeIdentifier")) protected def removeScheme(scheme: String): String =
if (scheme.endsWith(s".$addedSchemeIdentifier"))
scheme.take(scheme.length - addedSchemeIdentifier.length - 1) scheme.take(scheme.length - addedSchemeIdentifier.length - 1)
else scheme else scheme

View file

@ -135,7 +135,8 @@ private[remote] case class FailureInjectorHandle(_wrappedHandle: AssociationHand
override def disassociate(): Unit = wrappedHandle.disassociate() override def disassociate(): Unit = wrappedHandle.disassociate()
override def notify(ev: HandleEvent): Unit = if (!gremlinAdapter.shouldDropInbound(wrappedHandle.remoteAddress)) override def notify(ev: HandleEvent): Unit =
if (!gremlinAdapter.shouldDropInbound(wrappedHandle.remoteAddress))
upstreamListener notify ev upstreamListener notify ev
} }

View file

@ -70,7 +70,8 @@ object ThrottlerTransportAdapter {
case class TokenBucket(capacity: Int, tokensPerSecond: Double, nanoTimeOfLastSend: Long, availableTokens: Int) case class TokenBucket(capacity: Int, tokensPerSecond: Double, nanoTimeOfLastSend: Long, availableTokens: Int)
extends ThrottleMode { extends ThrottleMode {
private def isAvailable(nanoTimeOfSend: Long, tokens: Int): Boolean = if ((tokens > capacity && availableTokens > 0)) { private def isAvailable(nanoTimeOfSend: Long, tokens: Int): Boolean =
if ((tokens > capacity && availableTokens > 0)) {
true // Allow messages larger than capacity through, it will be recorded as negative tokens true // Allow messages larger than capacity through, it will be recorded as negative tokens
} else min((availableTokens + tokensGenerated(nanoTimeOfSend)), capacity) >= tokens } else min((availableTokens + tokensGenerated(nanoTimeOfSend)), capacity) >= tokens

View file

@ -68,7 +68,8 @@ private[remote] class TcpAssociationHandle(val localAddress: Address, val remote
override val readHandlerPromise: Promise[HandleEventListener] = Promise() override val readHandlerPromise: Promise[HandleEventListener] = Promise()
override def write(payload: ByteString): Boolean = if (channel.isWritable && channel.isOpen) { override def write(payload: ByteString): Boolean =
if (channel.isWritable && channel.isOpen) {
channel.write(ChannelBuffers.wrappedBuffer(payload.asByteBuffer)) channel.write(ChannelBuffers.wrappedBuffer(payload.asByteBuffer))
true true
} else false } else false

View file

@ -90,7 +90,8 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = "akka.remote.Re
(new TestFailureDetector, registry, transport, handle) (new TestFailureDetector, registry, transport, handle)
} }
def lastActivityIsHeartbeat(registry: AssociationRegistry) = if (registry.logSnapshot.isEmpty) false else registry.logSnapshot.last match { def lastActivityIsHeartbeat(registry: AssociationRegistry) =
if (registry.logSnapshot.isEmpty) false else registry.logSnapshot.last match {
case WriteAttempt(sender, recipient, payload) if sender == localAddress && recipient == remoteAddress case WriteAttempt(sender, recipient, payload) if sender == localAddress && recipient == remoteAddress
codec.decodePdu(payload) match { codec.decodePdu(payload) match {
case Heartbeat true case Heartbeat true
@ -99,7 +100,8 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = "akka.remote.Re
case _ false case _ false
} }
def lastActivityIsAssociate(registry: AssociationRegistry, cookie: Option[String]) = if (registry.logSnapshot.isEmpty) false else registry.logSnapshot.last match { def lastActivityIsAssociate(registry: AssociationRegistry, cookie: Option[String]) =
if (registry.logSnapshot.isEmpty) false else registry.logSnapshot.last match {
case WriteAttempt(sender, recipient, payload) if sender == localAddress && recipient == remoteAddress case WriteAttempt(sender, recipient, payload) if sender == localAddress && recipient == remoteAddress
codec.decodePdu(payload) match { codec.decodePdu(payload) match {
case Associate(c, origin) if c == cookie && origin == localAddress true case Associate(c, origin) if c == cookie && origin == localAddress true
@ -108,7 +110,8 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = "akka.remote.Re
case _ false case _ false
} }
def lastActivityIsDisassociate(registry: AssociationRegistry) = if (registry.logSnapshot.isEmpty) false else registry.logSnapshot.last match { def lastActivityIsDisassociate(registry: AssociationRegistry) =
if (registry.logSnapshot.isEmpty) false else registry.logSnapshot.last match {
case WriteAttempt(sender, recipient, payload) if sender == localAddress && recipient == remoteAddress case WriteAttempt(sender, recipient, payload) if sender == localAddress && recipient == remoteAddress
codec.decodePdu(payload) match { codec.decodePdu(payload) match {
case Disassociate true case Disassociate true

View file

@ -25,7 +25,8 @@ abstract class GenericTransportSpec(withAkkaProtocol: Boolean = false)
val nonExistingAddress = Address("test." + schemeIdentifier, "nosystem", "nohost", 0) val nonExistingAddress = Address("test." + schemeIdentifier, "nosystem", "nohost", 0)
def freshTransport(testTransport: TestTransport): Transport def freshTransport(testTransport: TestTransport): Transport
def wrapTransport(transport: Transport): Transport = if (withAkkaProtocol) { def wrapTransport(transport: Transport): Transport =
if (withAkkaProtocol) {
val provider = system.asInstanceOf[ExtendedActorSystem].provider.asInstanceOf[RemoteActorRefProvider] val provider = system.asInstanceOf[ExtendedActorSystem].provider.asInstanceOf[RemoteActorRefProvider]
new AkkaProtocolTransport(transport, system, new AkkaProtocolSettings(provider.remoteSettings.config), AkkaPduProtobufCodec) new AkkaProtocolTransport(transport, system, new AkkaProtocolSettings(provider.remoteSettings.config), AkkaPduProtobufCodec)
} else transport } else transport